Skip to content

Strings

  • cats = "RickyandLucy"

Strings

  • cats is a string literal
  • sequence
    • cats[0], cats[1],
    • 0 and 1 are indexes
    • len()

pets = ""
cats = "RickyandLucy"
pets = cats
print(pets, end= " ")
print(len(pets))
print("Intials: \n\t", pets[0], "and", pets[8])

More on Strings

  • \
  • + concatenate

kitty_one = "Ricky"
kitty_two = "Lucy"
cats = kitty_one + 'and' + kitty_two
cats_2 = "Ricky" \
         "and" \
         "Lucy"
cats_3 = "ricky" + "and" + "lucy"
print(cats)
print(cats_2)
print(cats_3)

formatting strings

  • f-strings: builds a string
  • expression inside the curly brace
    • can have multiple expressions
  • ' ' are important
  • =
    my_string = (f' 2 + 3 equals {2+3}')
    print(my_string)
    print(f' multiplication {12 * 123 = :f}')
    

Airthmetic Expressions

  • expression: evaluates to a value
  • literal
    • string, literal, float
  • operators
    • +, -, *, /, **
    • unary
  • precedence rules
    result = -2 * 6 + 2**3 * 7
    

Type conversions

  • implicit
    • at least one float operand in expression result in a float
  • explicit
    • int() note: no rounding
    • float()
    • str()

Some examples

quantity = 10
value = 15.5
worth = quantity * value
# what type is worth?
print(worth)
number1 = int(input("Enter a number "))
number2 = int(input("Enter another number "))
print(number1 + number2)
print(float(number1) + number2)
print(number1)


Compound Operators

  • often want to increment or decrement a variable
    count = count + 1
    chances = chances -1
    
  • compound operators are shorthand
    count +=1
    chances -= 1
    

Divison

  • /
    • returns a float, even when two integer operands
  • //
    • divides but gives only the whole number result
    • returns integer if both operands are integers
    • returns float if one or both operands are floats
      print(9/2)
      print(9//2)
      print(9//2.0)
      

Modulo

  • %
    • returns the remainder
    • 2 integer operands, returns integer
    • one or both float operands, returns float.
      print(34 % 7)
      print (34 // 7)
      

Math Module

  • module: Python code located in another file
  • import a module so can use it
    • top of the file
  • functions from math module
    • call and arguments
    • math.sqrt(5)
      import math
      
      number = 5.6
      print(math.ceil(number))