Search code examples
pythonpython-2.7loopsinfinite-loop

Making a certain statement loop forever in Python


while 1 == 1:
    do = raw_input('What would you like to do?')

In the above example you can see that the code is meant to make something loop forever, for example:

if do == 'x':
    print 'y'
elif do == 'z':
    print 'a'

So this if statement has been carried out and I want the raw_input to be carried out again so that the person can enter something else and the program goes on again.

I would not like to put the entire program in a

while True:

program or a

while 1 != 2:

statement.


Solution

  • Normally you do this until a certain condition is met, for example, the user types q to quit; otherwise it is just an infinite loop and you would need to force quit the entire program.

    Try this logic instead:

    result = raw_input('What would you like to do? Type q to quit: ')
    
    while result.lower() != 'q':
        if result == 'x':
           print 'y'
        if result == 'z':
           print 'a'
        result = raw_input('What would you like to do? Type q to quit: ')
    print('Quitting. Good bye!')