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.
  • 9,282
  • 3
  • 40
  • 45
  • 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

3

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.

DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
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