"countOut" -- while loop entries not from the list are not counted in augmented assignment Python 3.6

47 Views Asked by At

This simple program should count entries from the list and print how many there were as well as counting entries that are not from the list. But for some reason it counts all entries as countIn despite if they are from the list or not... Appreciate your suggestions!

   fruitsList = ['Apple', 'Banana', 'Grape', 'Peach', 'Mango',
                      'Pear', 'Papaya', 'Plum', 'Grapefruit', 'Cantaloupe']
    countIn=0
    countOut=0

    while True:
        response=input('Enter a fruit name (enter X to exit): ')
        if response.upper() == 'X':
            break
        for response in fruitsList:
            if response in fruitsList:
               countIn += 1
               break
            else:
               countOut += 1
    print('The user entered' , countIn, ' items in the list')
    print('The user entered' , countOut, ' items not in the list')
1

There are 1 best solutions below

2
On BEST ANSWER

Try:

#!user/bin/env python

fruitsList = ['Apple', 'Banana', 'Grape', 'Peach', 'Mango',
                      'Pear', 'Papaya', 'Plum', 'Grapefruit', 'Cantaloupe']
countIn=0
countOut=0

while True:
    response=input('Enter a fruit name (enter X to exit): ')
    if response.upper() == 'X':
        break
    elif response.title() in fruitsList:
        countIn += 1
    else:
        countOut += 1
print('The user entered' , countIn, ' items in the list')
print('The user entered' , countOut, ' items not in the list')

There is no need for a for-loop.

EDIT: I also made it case-insensitive now by adding the title() function for the response string.