1

Why the following while loop is exited when x reaches 0?

x = 1
while x:
    print(x)
    x -= 1

It prints only 1. Shouldn't the while statement be something like: while x "is something": and not just while x:?

Andreas K.
  • 8,158
  • 2
  • 35
  • 43
  • 2
    Because the integer object `0` evaluates to `False` in a boolean context: `bool(0) == False`. All objects in Python are either "truthy" or "falsy". – Christian Dean Sep 04 '17 at 23:17
  • Also, [_What is Truthy and Falsy in python? How is it different from True and False?_](https://stackoverflow.com/questions/39983695/what-is-truthy-and-falsy-in-python-how-is-it-different-from-true-and-false) would be useful as well. – Christian Dean Sep 04 '17 at 23:20

2 Answers2

2

Because bool(0) => False, and bool(x) for x!=0 => True, so it's like saying while x!=0 or while x>0 in your case.

MrGeek
  • 21,097
  • 4
  • 28
  • 52
0

In boolean, none zero value means 'true' and 0 means 'false'. The code reaches the argument while(0) or while(false) and terminate the body