Anu*_*ama 5 range while-loop python-3.x
为什么不能在 python 中的范围函数上使用 while 循环?
编码:
def main():
x=1;
while x in range(1,11):
print (str(x)+" cm");
if __name__=="__main__":
main();
Run Code Online (Sandbox Code Playgroud)
作为无限循环执行,重复打印 1 cm
很简单,我们可以在 python 中使用while和range()函数。
>>> i = 1
>>> while i in range(0,10):
... print("Hello world", i)
... i = i + 1
...
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
>>> i
10
Run Code Online (Sandbox Code Playgroud)
对于您正在做的事情,for循环可能更合适:
for x in range(1,11):
print (str(x)+" cm")
Run Code Online (Sandbox Code Playgroud)
如果你想使用 while,你需要更新,x因为否则你最终会得到你所描述的无限循环(x 总是=1如果你不改变它,所以条件将永远为真;))。