3. Types and Values¶
3.1 Overview¶
Python has few types. You can check the type of a variable using:
type(x)
Python uses dynamic typing (or duck typing)
the type is determined by the definition (if it walks like a duck, it is a duck)
some types are
int
,float
,bool
,str
,NoneType
.
3.2 String¶
In Python3, all types are classes. (so they can be referenced).
'seven'
and"seven"
are identical in python. It’s a style choice.multline strings using three single/double quotes:
'''
x = 'seven'
.x
is an object.x.capitalize()
,x.upper()
,x.lower()
works.x = 'seven {} {}'.format(8, 9)
is another optionx = 'seven {1} {0}'.format(8, 9)
order can be reversedx = 'seven {1:<9} {0}'.format(8, 9)
first arg is left aligned with 9 spaces-x = 'seven {1:<09} {0}'.format(8, 9)
first arg is left aligned with 9 spaces and filled with 0s (9 is the total number of digits)x = f'seven {a} {b}'
f strings also work (3.6>). They use theformat
method.
3.3 Numeric types¶
Integer and floating are the main types. But since everything is an object, you can derive your own types.
7 * 3.0
is afloat
.7 / 3
is also afloat
(new in Python 3)7 // 3
isint
..1 + .1 + .1 - .3 = 5.551115123125783e-17
.accuracy is sacrificed for precision
how do you solve this?
from decimal import *
a = Decimal('0.10')
…
3.4 Bool type¶
for logical values and expressions
None
is used to represent the absence of a value
x = None
if x:
print('True')
else:
print('False')
prints False
0
,' '
also evaluate asFalse
3.5 Sequence¶
Python built-in sequence types:
Lists
Tuples
Dictionaries
Lists:
example:
x = [1, 2, 3, 4, 5]
list is a mutable sequence, i.e, we can reassign indices in the list.
x[2] = 42
.
Tuples:
example:
x = (1, 2, 3, 4, 5)
tuples are immutable
x[2] = 42
returns error
Range:
example:
x = range(10)
(0 to 9)more general:
x = range(start, stop, step)
to convert to list:
x = list(range(10))
, now it is mutable.
Dictionary:
example: `x = {‘one’: 1, ‘two’: 2}
to parse through keys, do
for i in x:
to parse through key-value pairs, do
for k, v in x.items():
dictionaries are mutable
Any element can be any type (and of mixed type)!
3.6 Type¶
Since everything is an object,
type
is the same as aclass
.
x = (1, 'two', 3.0, [4, 'four'], 5)
print('x is {}'.format(x))
print(type(x))
returns
tuple
but
type(x[1])
is astr
.
To check type,
if isinstance(x, tuple)
if isinstance(x, list)