Method of choice with while

Asked

Viewed 525 times

2

I have two options and the program should say which one was chosen, if the input is wrong should ask to repeat the request.

Problems: Option 2 repeats 2 times until right. Option 1 does not say a name that is not in script

print('''Choice your number
[1] Banana
[2] Apple ''')

    option = int(input('Your option: '))
    while option != 1 and 2:
        print('Try again')
        option = int(input('Your option: '))
        if option == 1:
            print('Banana choiced')
        elif option == 2:
            print('Apple choiced')

Resultado

  • @Andersoncarloswoss though it may sound, I don’t think it’s because she has a peculiarity that valid options are tested. I thought it might even be the same case as the one I answered earlier, but it’s a little different.

  • I’m suspicious to comment on, but certainly not.

1 answer

2


It’s easier than it looks:

print('''Choice your number
[1] Banana
[2] Apple ''')
while True:
    option = int(input('Your option: '))
    if option == 1:
        print('Banana choiced')
        break
    elif option == 2:
        print('Apple choiced')
        break
    print('Try again')

See working on ideone. And in the repl it.. Also put on the Github for future reference.

How do you check the accepted options and if one of them is typed should end the execution is just close the loop when entering one of them (break). If you do not enter the options allowed and validated with if it only stays in the loop indefinitely until you type in what it’s worth.

  • it’s really simple, I’m taking my first steps in Python. I appreciate your help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.