'python while loop range function

Why can't while loop be used on a range function in python ?

The code:

def main():
  x=1;

  while x in range(1,11):
     print (str(x)+" cm");


if __name__=="__main__":
    main();

executes as an infinite loop repeatedly printing 1 cm



Solution 1:[1]

Simply we can use while and range() function in python.

>>> while i in range(1,11):
...     print("Hello world", i)
... 
Hello world 1
Hello world 2
Hello world 3
Hello world 4
Hello world 5
Hello world 6
Hello world 7
Hello world 8
Hello world 9
Hello world 10

>>> i
10

Solution 2:[2]

For what you're doing, a for loop might be more appropriate:

for x in range(1,11):
    print (str(x)+" cm")

If you want to use while, you need to update x since you'll otherwise end up getting the infinite loop you're describing (x always is =1 if you don't change it, so the condition will always be true ;)).

Solution 3:[3]

while just evaluates boolean (true or false).

def main():
  x=1;

  while x in range(1,11):
     print(str(x)+" cm");


if __name__=="__main__":
    main();

In the above code x is initialised to 1 and it is in the range(1,11) so the while executed and went in loop since the condition in while x in range(1,11): is satisfied every time. To fix this, increment x in the while loop ex:

while x in range(1,11):
    print (str(x)+" cm")
    x= x+1

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Ivo
Solution 3 Javad Nikbakht