We have already encountered booleans when talking about if
statements, but just to summarize, a boolean
is one of the simplest Python types, and it can have two values: True
and False
(with uppercase T
and F
):
a = True
b = False
Booleans can be combined with logical operators to give other booleans:
True and False
False
True or False
True
(False and (True or False)) or (False and True)
False
When you write an if
statement or a while
loop, Python is actually converting the expression into a boolean, then will act accordingly. You can just give a boolean directly to an if
statement:
a = True
if a:
print "a is true"
a is true
In other words, you do not need to do:
if a == True:
Tuples are, like lists, a type of sequence, but they use round parentheses rather than square brackets:
t = (1, 2, 3)
They can contain heterogeneous types like lists:
t = (1, 2.3, 'spam')
and also support item access and slicing like lists:
t[1]
2.3
t[:2]
(1, 2.3)
The main difference is that they are immutable, like strings:
t[1] = 2
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-10-9d97237db197> in <module>() ----> 1 t[1] = 2 TypeError: 'tuple' object does not support item assignment
We will not go into the details right now of why this is useful, but you should know that these exist as you may encounter them in examples.
One of the data types that we have not talked about yet is called dictionaries (dict
). If you think about what a 'real' dictionary is, it is a list of words, and for each word is a definition. Similarly, in Python, we can assign definitions (or 'values'), to words (or 'keywords').
Dictionaries are defined using curly brackets {}
:
d = {'a':1, 'b':2, 'c':3}
Items are accessed using square brackets and the 'key':
d['a']
1
d['c']
3
Values can also be set this way:
d['r'] = 2.2
print d
{'a': 1, 'c': 3, 'b': 2, 'r': 2.2}
The keywords don't have to be strings, they can be many (but not all) Python objects:
e = {}
e['a_string'] = 3.3
e[3445] = 2.2
e[complex(2,1)] = 'value'
print e
{3445: 2.2, (2+1j): 'value', 'a_string': 3.3}
e[3445]
2.2
If you try and access an element that does not exist, you will get a KeyError
:
e[4]
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-17-a79b29c56d88> in <module>() ----> 1 e[4] KeyError: 4
Also, note that dictionaries do not know about order, so there is no 'first' or 'last' element.
If you try iterating over a dictionary, it will iterate over the keys (not the values), in no specific order:
for key in e:
print key
3445 (2+1j) a_string
But you can easily get the value with:
for key in e:
print key, e[key]
3445 2.2 (2+1j) value a_string 3.3