Unit P2 - Numbers and Strings
Unit P2 - Numbers and Strings
Numbers and
Strings
VARIABLES, VALUES, TYPES, EXPRESSIONS
Chapter 2
Variables Values
base 6
height 4
area
address 24.0
residence_city 'Corso Duca Degli Abruzzi'
birth_city
'Torino'
Values
and types
Variable names
o Step 2: Store the result in the variable named on the left side of the
assignment operator
o taxRate = 5 # an int
Then later…
o taxRate = 5.5 # a float
And then
o taxRate = "Non-taxable" # a string
▪ If you use a variable and it has an unexpected type an error will occur in
your program
▪ print(taxRate + "??")
o Prints Non-taxable??
▪ So…
o Once you have initialized a variable with a value of a particular type you should
take great care to keep storing values of the same type in the variable
▪ When you use the “+” operator with strings the second argument
is concatenated to the end of the first, but both arguments must
be strings
o We’ll cover string operations in more detail later in this chapter
b * ((1 + r / 100) ** n)
▪ Remember:
o If you mix strings with integer or floating-point values the result is an error
https://docs.python.org/3/library/functions.html
o val = int(″Hola″)
ValueError: invalid literal for int() with
base 10: ‘Hola'
name = 'Bob' B
Traceback (most recent call last):
print(name[0]) File "main.py", line 5, in <module>
name[0] = 'G'
name[0] = 'G' TypeError: 'str' object does not support
item assignment
ASCII/Unicode
Character
value (integer)
'x'
120
▪ Functions are general and can accept ▪ Methods are specific to a type of
arguments of different types object
o All strings have a group of methods
▪ Functions are called directly, with a list
o All integers have a group of methods
of parameters
o…
o exmp. func(param), print(a)
▪ Functions may return a result, that may ▪ Methods are called with the dot-syntax
be stored in a variable o object.method()
o result = func(param) ▪ Methods may return a result, that may
be stored in a variable
o result = obj.method()