FAQ: Learn Python: Loops - While Loops

I think I follow. Thanks!

1 Like

I would like to know why “countdown -1” does not work, instead of “countdown -= 1”:

countdown = 10
print('Starting countdown!')
while countdown >= 0:
  print('{}'.format(str(countdown)))
  countdown - 1
  print(' ----- ')
print('We have liftoff!')

I end up in an infinite loop but I do not quite get why.

The above is an expression with zero side effect, and as such leaves countdown as unchanged. It should be written as an assignment statement:

countdown -= 1

Now it will have a side effect, namely decrementing the value by 1 and re-assigning it to the same variable.

3 Likes

Oh I get it now! I realized that “countdown - 1” can work if I rewrite it as “countdown = countdown - 1”.
Since “x -= y” also means “x = x - y”, I just had to add a “=” sign so the variable could have it’s value changed properly.
Thank you so much for helping me notice that!
The code below should work now:

countdown = 10
print('Starting countdown!')
while countdown >= 0:
  print('{}'.format(str(countdown)))
  countdown = countdown - 1
  print(' ----- ')
print('We have liftoff!')

“countdown -= 1” is fancier tho :grin:

1 Like