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
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
NameError: name 'i' is not defined. Did you mean: 'id'?.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 ;)).
range(1,11) isn't a tuple but arguments for the range() function.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
Outside of a for-loop, x in range(..) mean something different. It's a test that returns a boolean
print(1 in range(1,11)) # prints True
So your while-loop actually means this:
def main():
x=1;
while True if x in range(1,11) else False:
print (str(x)+" cm");
if __name__=="__main__":
main();
xso it's alwaysinthe range.forloops are for".