Cannot break out of while loop in python

孤者浪人 提交于 2020-01-04 17:33:14

问题


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

回答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:

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:

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



回答2:


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

x=getheight()

to update your variable x



来源:https://stackoverflow.com/questions/42318622/cannot-break-out-of-while-loop-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!