-1

I want the program to find the number of times a particular number occurs within a list. What am I doing wrong here?

def list1():
    numInput = input("Enter numbers separated by commas: ")
    numList = numInput.split(",")
    numFind = int(input("Enter a number to look for: "))
    count = 0
    for num in numList:
        if num == numFind:
            count += 1
    length = len(numList)
    # dividing how many times the input number was entered 
    # by the length of the list to find the %
    fraction = count / length
    print("Apeared",count,"times")
    print("Constitutes",fraction,"% of this data set")
list1()   
GMan
  • 25
  • 3

2 Answers2

2

numList isn't a list of numbers, it's a list of strings. Try converting to integer before comparing to numFind.

    if int(num) == numFind:

Alternatively, leave numFind as a string:

numFind = input("Enter a number to look for: ")

... Although this may introduce some complications, e.g. if the user enters 1, 2, 3, 4 as their list (note the spaces) and 2 as their number, It will say "Appeared 0 time" because " 2" and "2" won't compare equal.

Kevin
  • 74,910
  • 12
  • 133
  • 166
1

There are 2 issues with the code, First you are comparing int with str and the second is count / length. In Python when you divide int with int you get an int returned not a float (as expected.) so fraction = flost(count) / length would work for you , also you need to convert all the elements in the list to integers which can be done as :

numList = map(int, numInput.split(","))
ZdaR
  • 22,343
  • 7
  • 66
  • 87
  • Thanks for the answers guys that was so simple I feel stupid now. I also see the question was asked already, sorry this was my first question I'll be more vigilant on future posts. – GMan May 11 '15 at 18:41
  • 1
    "In Python when you divide int with int you get an int returned not a float". Partially agree. In 2.7 you get an int. in 3.X you can get a float. – Kevin May 11 '15 at 18:44
  • @Kevin , Thanks for the insight, But I guess it is often a good practise to explicitly convert to `floats` when precision is needed, Just to be on a safer side to avoid any confusion – ZdaR May 11 '15 at 18:47