Search code examples
pythonpython-3.xwhile-loopbreakpoints

Cannot break out of while loop in python


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

Solution

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