无法突破python中的while循环 [英] Cannot break out of while loop in python
本文介绍了无法突破python中的while循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
无法在python中退出while循环:
我尝试将代码全部合并在一起,没有main和getheight函数,但这仍然给我一个无限循环。
Cannot break out of while loop in python: I tried merging the code all together with no main and getheight functions, and it still gives me an infinite loop.
def main():
x = 0
while x not in range (1,23):
getheight()
if x in range (1,23):
break
for i in range (x):
for j in range (x - j):
print (" ", end="")
for j in range (x):
print ("#", end="")
print (" ", end="")
for j in range (x):
print ("#", end="")
"\n"
def getheight():
x = input("Give me a positive integer no more than 23 \n")
return x
if __name__ == "__main__":
main()
推荐答案
x
main()
是一个局部变量,与<$中的 x
变量无关 c $ c> gethe ight()。您正在从后者返回新值,但是忽略了返回值。在函数调用结果的 main
中设置 x
:
x
in main()
is a local variable that is independent from the x
variable in getheight()
. You are returning the new value from the latter but areignoring the returned value. Set x
in main
from the function call result:
while x not in range (1,23):
x = getheight()
if x in range (1,23):
break
您还需要修复 getheight()
函数返回整数,而不是字符串:
You also need to fix your getheight()
function to return an integer, not a string:
def getheight():
x = input("Give me a positive integer no more than 23 \n")
return int(x)
这篇关于无法突破python中的while循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文