Reputation: 11
available_fruits = ['apple', 'grape', 'banana']
choice = input('Please pick a fruit I have available: ')
while True : choice= input('You made an invalid choice. Please pick again:')
if choice not in available_fruits
else print('You can have the fruit')
I want to make this loop stop when user inputs something in the list "available_fruits". But when I enter 'apple', it says "You can have the fruit" but as well as "You made an invalid choice. Please pick again:" again.
How can I make this loop to stop when I enter the fruit which is in the list? when I put the "break" at the end of the code, it says its an invalid syntax..
Upvotes: 0
Views: 80
Reputation: 1709
I don't know if its the formatting of your question of if that's your actual code. You some have syntax errors:
if
or else
you need to use :
as you did with the while
condition.Once you fix those errors, check the condition you want to meet in order to get out of the loop with break
.
Upvotes: 1
Reputation: 123
This would work:
available_fruits = ['apple', 'grape', 'banana']
choice = input('Please pick a fruit I have available: ')
while True:
if choice in available_fruits:
print('You can have the fruit')
break
else:
choice = input('You made an invalid choice. Please pick again: ')
But in general I'd suggest you create while loops with an actual condition. That's what while-loops are for. They automatically break when the condition evaluates to False. It's much cleaner, too.
Example:
available_fruits = ['apple', 'grape', 'banana']
choice = input('Please pick a fruit I have available: ')
while choice not in available_fruits:
choice = input('You made an invalid choice. Please pick again: ')
print('You can have the fruit')
Upvotes: 2
Reputation: 5889
Give this a try. Assuming you need to use break.
available_fruits = ['apple', 'grape', 'banana']
choice = input('choose a fruit: ')
while True :
if choice in available_fruits:
print('you picked a valid fruit')
break
else:
choice = input('choose a fruit: ')
Upvotes: 1
Reputation: 305
Use the while condition instead of just while True, something like this works:
available_fruits = ['apple', 'grape', 'banana']
choice = input('Please pick a fruit I have available: ')
while choice not in available_fruits:
choice= input('You made an invalid choice. Please pick again:')
print('You can have the fruit')
Upvotes: 3