How can I make a conditional statement in Python, and if input is the same twice if will send an error

Question:

So I made a groceries list in Python. But, if the user answer the same input such as banana twice, it will check the banana is already in the basket. How can I do this?

fruit = ['Banana', 'Mandarine', 'Apple']
using = input('Which fruit are you going to buy')

if using in fruit:
    print('Good Fruit')
else:
    print('That is not a good fruit!')

So, what can I do better?

Asked By: Jackson Nguyen

||

Answers:

You can use a list for the fruits that the user has already input (as suggested by B Remmelzwaal). Considering the code that you have already written, you can implement it as:

basket = []
fruit = ['Banana', 'Mandarine', 'Apple']

n = 5
for i in range(n):
    
    using = input('Which fruit are you going to buy: ')
    
    if using in fruit:
        print('Good Fruit')
    else:
        print('That is not a good fruit!')
        
    if using not in basket:
        basket.append(using)
    else:
        print('Fruit was already in basket!')

print(basket)

Here I have set n (which is the number of times the user will be asked) to 5. Please edit it as desired.

Here is an example of its working:

Which fruit are you going to buy: Banana
Good Fruit
Which fruit are you going to buy: Apple
Good Fruit
Which fruit are you going to buy: Banana
Good Fruit
Fruit was already in basket!
Which fruit are you going to buy: Grapes
That is not a good fruit!
Which fruit are you going to buy: Apple
Good Fruit
Fruit was already in basket!
['Banana', 'Apple', 'Grapes']
Answered By: Dev Bhuyan
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.