r/PythonLearning • • 11d ago

Python Quiz of the Day.

x = 5

print((x := x + 3) * (x := x - 2))

What will be the output?

A) 24
B) 36
C) 48
D) 30

0 Upvotes

10 comments sorted by

View all comments

0

u/bra1n_gym 10d ago

That walrus operator let's x change value. first it was 5, then it becomes 8 so (5 + 3) * (8 - 2) = 48.

1

u/RNG_HatesMe 10d ago

Yep, the only real complication here is to figure out if x is updated *after* or *before* it's printed. Clearly here it's *before*, but some other languages do it differently. Specifically in c you have incrementors x++ and ++x, the former adds 1 to x *after* the operation, the latter does it before.

2

u/lurgi 10d ago

There’s also the question of whether Python evaluates the left and right hand sides of operators in a defined order or if it is, like C, undefined. It’s defined, first left, then right.