2

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
  • because your x in main is always 0, x=getheight() Commented Feb 18, 2017 at 17:52

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

3 Comments

I added the "x =". But still gives me an infinite loop. I think it's because the initial declaration of x in main. But if I remove it, Python wouldn't get into the while loop. Is there any way around that?
@user627154: Your code won't work at all unless x has been assigned before the loop. If you removed the x = 0 and not capture the return value of getheight(), then you must have a global name x that happens to be set to a valid value.
@user627154: Ah, I missed that you are returning the `input()`` value unchanged, so a string, not an integer.
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

x=getheight()

to update your variable x

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.