Search code examples
pythonif-statementraw-input

how to go back and check for another input


is there a way to go back to this line of code to check for input again?:

say=raw_input("say: ")

after i do a if statement to check what the user inputed:

if say == "hello":
    do something

It does the if statement but then It ends the program and i have to run it again.I really don't want to have to start the file back up again. How do i make it where it goes back to that line of code to check for another input i enter.


Solution

  • You can use a while loop:

    while True:
        say = raw_input('say: ')
        if say == 'hello':
            print "hi!"
            break
        elif say == 'bye':
            print "bye!"
            break
    

    while True is an infinite loop. Every time the loop loops, it will ask the user what they want to say. If the reply is "hello", then the loop will break. Same for if it was "bye".

    If neither "hello" nor "bye" was given, then the loop will continue until it has been inputted.

    Or, you can use this approach:

    say = ''
    while say not in ['hello', 'bye']:
        say = raw_input('say: ')
    
    if say == 'hello':
        print "hi"
    elif say == 'bye':
        print 'goodbye!'