无法在 python 中跳出 while 循环: 我尝试将没有 main 和 getheight 函数的所有代码合并在一起,但它仍然给我一个无限循环。
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()
最佳答案
main()
中的
x
是一个局部变量,独立于
。您正在从后者返回新值但忽略了返回值。根据函数调用结果在x
中的变量>getheight()main
中设置x
:
while x not in range (1,23):
x = getheight()
if x in range (1,23):
break
您还需要修正您的 getheight()
函数以返回一个整数,而不是一个字符串:
def getheight():
x = input("Give me a positive integer no more than 23 \n")
return int(x)
关于python - 无法在 python 中跳出 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42318622/