在python中无法突破while循环

时间:2022-10-18 17:57:18

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.

在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()

2 个解决方案

#1


1  

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:

main()中的x是一个局部变量,它独立于getheight()中的x变量。您将从后者返回新值,但会返回返回的值。从函数调用结果中设置main中的x:

while x not in range (1,23):
    x = getheight()
    if x in range (1,23):
        break

You also need to fix your getheight() function to return an integer, not a string:

您还需要修复getheight()函数以返回整数,而不是字符串:

def getheight():
    x = input("Give me a positive integer no more than 23 \n")
    return int(x)

#2


0  

Return does not mean that it will automatically update whatever variable name in main matches the return variable. If you do not store this return value, the return value will be gone. Hence you must do

返回并不意味着它会自动更新main中的任何变量名称与返回变量匹配。如果不存储此返回值,则返回值将消失。因此你必须这样做

x=getheight()

to update your variable x

更新变量x

#1


1  

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:

main()中的x是一个局部变量,它独立于getheight()中的x变量。您将从后者返回新值,但会返回返回的值。从函数调用结果中设置main中的x:

while x not in range (1,23):
    x = getheight()
    if x in range (1,23):
        break

You also need to fix your getheight() function to return an integer, not a string:

您还需要修复getheight()函数以返回整数,而不是字符串:

def getheight():
    x = input("Give me a positive integer no more than 23 \n")
    return int(x)

#2


0  

Return does not mean that it will automatically update whatever variable name in main matches the return variable. If you do not store this return value, the return value will be gone. Hence you must do

返回并不意味着它会自动更新main中的任何变量名称与返回变量匹配。如果不存储此返回值,则返回值将消失。因此你必须这样做

x=getheight()

to update your variable x

更新变量x