问题
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