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
2
x = 5
x -= 6

-1
Explanation:

The value of x has been decremented by 6 (x = x - 6) in the second line, giving a value of -1.

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
4
x = 5
y = 3
x %= y
x *= 2 + 3

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.

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
4
x, y, z = 1, 2, 3
x, y, z = z, y, x
y, x = z, y
print(x)

2
1
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).