-1

Is while True !=0: valid , if so what does it mean? Because in my program using that or "while True" (by itself) provides the same output. I can't remember why I used it before in my code.

Thanks in advance.

the_R
  • 17
  • 5
  • It works since True and int can be mixed in expressions because: "For historic reasons, bool is a subclass of int, so True is an instance of int. (Originally, Python had no bool type, and things that returned truth values returned 1 or 0. When they added bool, True and False had to be drop-in replacements for 1 and 0 as much as possible for backward compatibility, hence the subclassing.)" [Source](https://stackoverflow.com/questions/37888620/comparing-boolean-and-int-using-isinstance) – DarrylG Oct 24 '20 at 11:34

3 Answers3

3

This is used to create infinite loops (or loops that exit via a break or return statement within the loop body). The standard way to do this is:

while True:
    ...

The other version you showed, while True != 0:, is equivalent, but needlessly convoluted. It works because, when treated as an integer, True has the value 1, so it's equivalent to while 1 != 0: which, in turn, is equivalent to while True:, which is the most direct way to express it.

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41
1

Yes, while True != 0: is valid and it has the same meaning as while True: which you should use from now on.

This works because int(True) evaluates to 1.

quamrana
  • 37,849
  • 12
  • 53
  • 71
0

It's simple, true != 0 => 1 != 0 is always 1 (true) .

Ayan Bhunia
  • 479
  • 3
  • 14