Home > Back-end >  Is there a way to find out if the user has inputted the same value?
Is there a way to find out if the user has inputted the same value?

Time:10-27

Is there a way, in the print statement, to find out if they have inputted the same thing? For example if they input dog, it will then output ‘You have 1 dog…(and some more code).’

But, because I just put 1 as a string, it will never go up if they input the same thing. I’m wondering if there is a way to do that?

pet = input('What pet do you have? ')


num_p = 0


while pet.lower() != 'stop':
    num_p = num_p   1
    print('You have 1 '   pet   '. Total # of Pets: '   str(num_p))
    pet = input('What pet do you have? ')

My question was pretty rough, and if you need me to clarify please ask!

CodePudding user response:

An optimal approach would be to use a dict to store the pets data. You can then increment and extract everything you need from the dict in one go.

So this works:

pets = {}

# ask 10 times (you can use a while loop if preferred)
for i in range(10):
    pet = input('What pet do you have? ')
    pet = pet.lower()

    # break the loop
    if pet == 'stop':
        break

    # do the increments

    if pet in pets:
        pets[pet]  = 1
    else:
        pets[pet] = 1
    
    print(f'you have {pets[pet]} {pet}. Total number of pets {sum(pets.values())}')

result (example):

you have 1 dog. Total number of pets 1
you have 2 dog. Total number of pets 2
you have 1 cat. Total number of pets 3
  • Related