Python Text Menu Infinite Loop

You’re missing a line in menu, or else missing an input elsewhere. You’re not actually accepting a choice from your user yet. If you want to keep your current structure, menu should look like:

def menu():
    print 'options...'
    return int(raw_input())

Or, a little cleaner (same effect):

def menu():
    return int(raw_input('options...'))

Otherwise, you can just call menu() and then separately accept the user’s selection:

while loop == 1:
    menu()
    choice = int(raw_input())

Note that I’ve changed your input() calls to int(raw_input()). This is a much safer way of accepting input from your user, since it prevents them from embedding arbitrary Python code in their input!


Not-quite-on-topic:

Now, just because I happened to notice it, I’m also going to mention that loop is a potentially-misleading variable name. Since you’re just using it as a boolean, you could rewrite the while loop like this:

loop = 1
while loop: # !
    #do stuff

This is kind of funny, but not very intuitive to read. It’s usually better to simply loop indefinitely, and use break when your end condition is met:

while True:
    # Do stuff
    if choice == 5: #Or whatever end condition
        break

Leave a Comment