Extra Topic: The Walrus Operator (:=)
Note: extra topics are not in CS Academy, but are required
and can appear on any future
homework, writing session, quiz, or exam.
Basic Example:
x = 5
if (x := x + 1) == 6:
print('yes')
else:
print('no')
print(x)
Better Example:
Instead of this:
print('Enter some numbers. Enter 0 to quit.')
total = 0
while True:
nextValue = int(input('> '))
if nextValue == 0:
break
total += nextValue
print(f'Total = {total}')
You can do this:
print('Enter some numbers. Enter 0 to quit.')
total = 0
while (nextValue := int(input('> '))) != 0:
total += nextValue
print(f'Total = {total}')