Explanation
If you read through , which defines assignment expressions, you’ll see a section called
Exceptional cases, which has an example similar to the one in this quiz. They call this syntax
“Valid, though not recommended”.
That sums up this code well. You would not write an assignment expression like the one you see in
this code in your production code, and it’s terrible form.
It may help you understand how assignment expressions work.
A good way to figure out this quiz is to run it in smaller pieces. You can start by running the first
expression in your Python REPL:
1 >>> (a := 6, 9)
2 (6, 9)
3 >>> a
4 6
The REPL tells you that you constructed a tuple ((6, 9), which was immediately discarded), and
during the tuple creation the variable a was assigned the value 6.
Now run the second assignment expression in your REPL and inspect the variables:
1 >>> (a, b := 16, 19)
2 (6, 16, 19)
3 >>> a
4 6
5 >>> b
6 16
Output :
a = 6 , b = 16
Once again we see a tuple was created, this time with the value from a, 16, and 19. The value 16 was
assigned to b by the walrus operator, and the 19 was discarded after being displayed.
0 Comments:
Post a Comment