Pop Quiz!

Tested with: Python 3.7.2

def is_true_or_false():
    try:
        1/0
    except:
        return True
    else:
        return True
    finally:
        return False

What does that print?

Go ↓ for solution or
→ for next question

# https://docs.python.org/3/tutorial/errors.html#defining-clean-up-actions
#
# "The try statement has another optional clause which is intended to
# define clean-up actions that must be executed under all circumstances."

>>> def is_true_or_false():
...     try:
...         1/0
...     except:
...         return True
...     else:
...         return True
...     finally:
...         return False
... 
>>> is_true_or_false()
False
>>> a = 42
>>> b = 42
>>> a is b
?
>>> a = 316
>>> b = 316
>>> a is b
?

What does that print?

Go ↓ for solution or
→ for next question

>>> a = 42
>>> b = 42
>>> a is b
True
>>> a = 316
>>> b = 316
>>> a is b
False

Click: https://kate.io/blog/2017/08/22/weird-python-integers/ to see all the crazy details ;D

>>> [] == []
>>> [] is []

What does that print?

Go ↓ for solution or
→ for next question

>>> [] == []  # The `==` operator checks if both sides are of the same value
True
>>> [] is []  # The `is` operator checks if both sides are the same obj in memory
False
>>> 'something' is not None
>>> 'something' is (not None)

What does that print?

Go ↓ for solution or
→ for next question

>>> 'lollipop' is not None
True
>>> 'lollipop' is (not None)
False
  • The `is not` operator is not the same as the `is` and `not` operators
  • `is not` evaluates `False` if  the obj on both sites are the same obj
>>> value = 11
>>> valuе = 32
>>> value
11

What does that print?

Go ↓ for solution or
→ for next question

or better: WHY does that print 11?

>>> ord('е') # cyrillic 'e' (Ye), ord() gives us the unicode point
1077
>>> ord('e') # latin 'e', as used in English and typed using standard keyboard
101
>>> 'е' == 'e'
False

>>> value = 42 # latin e
>>> valuе = 23 # cyrillic 'e', Python 2.x would raise a `SyntaxError` here
>>> value
42
a = [1, 2, 3, 4]
b = a
a = a + [5, 6, 7, 8]

>>> a
[1, 2, 3, 4, 5, 6, 7, 8]
>>> b
[1, 2, 3, 4]

What does that print?

Go ↓ for solution or
→ for next question

a = [1, 2, 3, 4]
b = a
a += [5, 6, 7, 8]

...does print what?
>>> a
[1, 2, 3, 4, 5, 6, 7, 8]
>>> b
[1, 2, 3, 4, 5, 6, 7, 8]
  • a += b doesn't always behave the same way as a = a + b. Classes may implement the op= operators differently, and lists do this.
  • The expression a = a + [5,6,7,8] generates a new list and sets a's reference to that new list, leaving b unchanged.
  • The expression a += [5,6,7,8] is actually mapped to an "extend" function that operates on the list such that a and b still point to the same list that has been modified in-place.
Made with Slides.com