Python While Loop Range Function

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

4

3 Answers

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
0

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 ;)).

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller
Author

David Miller

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.