How do I get an if elif else statement to restart

Viewed 3235

I am a newbie, and am having trouble getting the following code to process.

choice

if: (statement is false)

  moves to elif statement

elif: (statement is false)

  moves to else statement

else: (I would like for the loop to go back up to choice to retry the if and elif statements

I tried some different indentations and such, but I'm sure I'm missing something else to retrigger the loop.

4 Answers

if is not a loop, it is a conditional. Therefore, there is no loop for you to restart.

while is a loop. (There are others that do slightly different things.) It can't branch like if, it just loops.

If you need to make a decision in a loop, put if inside of while. No single statement is designed to do everything.

while True:    # repeats forever
    feedback = get_user_feedback()
    if feedback_is_this_way(feedback):
        go_this_way()
    elif feedback_is_that_way(feedback):
        go_that_way()
    elif feedback_says_user_is_sick_and_tired(feedback):
        apologise_to_user()
        break    # exits the loop
    else:
        tell_the_user_not_to_mess_around()

You could try putting the conditional block in a function and then call the function again for the else condition:

def conditionCheck():
    if (...):
        #do stuff
    elif (...):
        #do stuff
    else:
        conditionCheck()

I believe you're looking for a while loop. For this example, the code will continue at the top until the user enters exit.

while True:
    item = input('Enter text: ')
    if item == 'banana':
        print('You entered: {}'.format(item))
    elif item == 'apple':
        print('You entered: {}'.format(item))
    elif item == 'cherry':
        print('You entered: {}'.format(item))
    elif item == 'exit':
        break
    else:
        print('You did not enter a fruit, try again!')

Some example output

Enter text: banana
You entered: banana
Enter text: apple
You entered: apple
Enter text: cherry
You entered: cherry
Enter text: exit
while True:
    if condition_one:
       pass
    elif condition_two:
       pass
    else:
        continue
    break
Related