Lesson 5 Writing Reusable and Self-explanatory Programs Chapter 1: Introduction Chapter 2: Shortcut assignment statements [2.1] Swapping the values of two variables [2.2] How to swap variables [2.3] Simultaneous variable assignments in Python [2.4] Augmented assignment operators [2.5] Test your understanding Chapter 3: Custom functions Chapter 4: Refactoring Chapter 5: Advanced function features Chapter 6: Function scope Chapter 7: Style conventions for functions Chapter 8: git branch Chapter 9: Refactoring the robot Chapter 10: Debugging and testing Chapter 11: Summary Chapter 2: Shortcut assignment statements Test your understanding face Josiah Wang Let’s test whether you actually understood what we covered in this chapter! 1 2 3 ❮ ❯ Question 1 What is the value of x at the end of the program? Type Error if you are expecting an error. 1 2x = 5 x -= 6 x -1 Explanation: The value of x has been decremented by 6 (x = x - 6) in the second line, giving a value of -1. Check answer! Question 2 What is the value of x at the end of the program? Type Error if you are expecting an error. 1 2 3 4x = 5 y = 3 x %= y x *= 2 + 3 x 10 Explanation: Line 3 results in x being 2 (x = x % y). You might think that multiplication has higher precedence in Line 4 (x = (x*2) + 3), but apparently augmented assignment operators have lower precedence than the usual operators, so it is actually x = x * (2+3). But please avoid writing such codes. Keep these augmented assignments to only a single number on the right hand side, otherwise your code will be increasingly unreadable. Check answer! Question 3 What is the value of x, y and z at the end of the program? Type Error if you are expecting an error. 1 2 3 4x, y, z = 1, 2, 3 x, y, z = z, y, x y, x = z, y print(x) x 2 y 1 z 1 Explanation: In Line 2, the values of x and z are swapped (y still points to what it was pointing to). At this point x==3, y==2 and z==1. In Line 3, y now points to the value of z, and x now points to the (old) value of y. So y==1, and x==2. Note that like swapping, x points to the old value of y, not the new value. z is not updated, so it stays what it was (1). Check answer!