python - 无法在 python 中跳出 while 循环

标签 python python-3.x while-loop breakpoints

无法在 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/

相关文章:

python - 添加多个停靠的小部件

python - 通过pycomm读取标签时超时

python - While循环: UnboundLocalError: local variable referenced before assignment

python - sqlalchemy postgres : AttributeError: can't set attribute

python - 如何删除 Pandas 数据框中具有特定字符的子字符串?

python - 如何在 while 循环中连续检查小时数?

python - 如何让 on_press 在自定义按钮中工作?

Python RegEx 以给定单词开头的整行

php - 删除PHP中指定目录中的所有子目录?

c - 用ctrl+d结束while循环,scanf?