0

Why this code is not infinite loop. I thought if a number in while condition, then it is always True.negative is still a number even though it changes from negative to positive. But when I run this code in spyder, it was stopped after negative is changed to 0. Why "while" loop stopped when negative changed ?

>>> positive = -9
>>> negative = -12
>>> while negative:
...    if positive:
...        print(negative)
...    positive += 3
...    negative += 3
Erik Johnsson
  • 111
  • 1
  • 1
  • 5
  • `0` is "falsy" in Python. Try writing a `while 0:` loop and see how many times it executes. Different languages handle this differently, for example `0` is "truthy" in Ruby. – Michael Geary May 04 '21 at 03:39

1 Answers1

0

If the number is zero, it's considered a falsey value and that would cause the loop to end.

See https://stackoverflow.com/a/39984051/47453 for lots of falsey values.

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173