Try what you've learned so far

Now we have some time fo you to try out Python basics that you've just learned.

1. Float point precision

One thing to be aware of with floating point arithmetic is that its precision is limited, which can cause equality tests to be unstable. For example:


In [ ]:
0.1 + 0.2 == 0.3

In [ ]:
0.2 + 0.2 == 0.4

Why is this the case? It turns out that it is not a behavior unique to Python, but is due to the fixed-precision format of the binary floating-point storage. All programming languages using floating-point numbers store them in a fixed number of bits, and this leads some numbers to be represented only approximately. We can see this by printing the three values to high precision:


In [ ]:
print("0.1 = {0:.17f}".format(0.1))
print("0.2 = {0:.17f}".format(0.2))
print("0.3 = {0:.17f}".format(0.3))
  • Python internally truncates these representations at 52 bits beyond the first nonzero bit on most systems.

  • This rounding error for floating-point values is a necessary evil of working with floating-point numbers.

  • The best way to deal with it is to always keep in mind that floating-point arithmetic is approximate, and never rely on exact equality tests with floating-point values.

2. Explore Booleans

Booleans can also be constructed using the bool() object constructor: values of any other type can be converted to Boolean via predictable rules. For example, any numeric type is False if equal to zero, and True otherwise:


In [ ]:
bool(2016)

In [ ]:
bool(0)

In [ ]:
bool(3.1415)

The Boolean conversion of None is always False:


In [ ]:
bool(None)

For strings, bool(s) is False for empty strings and True otherwise:


In [ ]:
bool("")

In [ ]:
bool("abc")

For sequences, which we'll see in the next section, the Boolean representation is False for empty sequences and True for any other sequences


In [ ]:
bool([1, 2, 3])

In [ ]:
bool([])

3. Mutability of lists and tuples


In [ ]:
s = (1, 2, 3) # tuple

In [ ]:
s[1] = 4 # Can you remember that tuples cannot be changed!

In [ ]:
s.append(4) # this is never going to work as it is a tuple! 
s

In [ ]:
t = [1, 2, 3] # But a list might just do the job:

In [ ]:
t[1] = 4

In [ ]:
t.append(4)
t

4. Dictionary attributes


In [ ]:
foo = dict(a='123', say='hellozles', other_key=['wow', 'a', 'list', '!'], and_another_key=3.14)

In [ ]:
# foo.update(dict(a=42))
## or
# foo.update(a=42)

In [ ]:
# foo.pop('say')

In [ ]:
# foo.items()

In [ ]:
# foo.keys()

In [ ]:
# foo.values()