Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x python while循环范围函数_Python 3.x_While Loop_Range - Fatal编程技术网

Python 3.x python while循环范围函数

Python 3.x python while循环范围函数,python-3.x,while-loop,range,Python 3.x,While Loop,Range,为什么不能在python中的范围函数上使用while循环 守则: def main(): x=1; while x in range(1,11): print (str(x)+" cm"); if __name__=="__main__": main(); 作为一个无限循环执行,重复打印1厘米。对于您正在执行的操作,使用For循环可能更合适: for x in range(1,11): print (str(x)+" cm") 如果你想使用while,

为什么不能在python中的范围函数上使用while循环

守则:

def main():
  x=1;

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


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

作为一个无限循环执行,重复打印1厘米。对于您正在执行的操作,使用
For
循环可能更合适:

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

如果你想使用while,你需要更新
x
,否则你会得到你正在描述的无限循环(如果你不改变它,x总是
=1
,所以条件总是真的;)。

我们可以在python中使用whilerange()函数

>>> 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

x的值永远不会改变,所以它一直满足你的“while”标准。你能用适当的缩进之类的方法在代码框中编写代码吗?查看“帮助”部分,了解如何创建代码框(4个空格或CTRL+K)。您从未更改
x
的值,因此它始终位于
范围内。“在范围内使用while循环”是什么意思?如果它的意思是“在范围内迭代”,那么答案是“因为这就是
for
循环的目的”。我想这不是最好的性能,对吧?因为它创建了一个不需要的元组,对吗?@DennyWeinberg
range(1,11)
不是元组,而是
range()
函数的参数。我以为range创建了一个元组(返回元组),但这不对。很抱歉