0

I really just can't understand why this code is not working... It's probably just a typo. But even my more experienced friend is stumped here. The prompt is simply "write a program that tells you how many 4s there are in a given list." Its all working except that count says zero no matter how many 4s I submit.

def num_four(number_list): 
    count = 0

    print number_list
    for i in number_list:
        print i
        if i == 4:  
            count = count + 1
    return count
number_list = raw_input("Enter list of integers here: ")

print num_four(number_list)

the output looks like this:

Enter list of integers here: 123444
123444
1
2
3
4
4
4
0
Mike Graham
  • 73,987
  • 14
  • 101
  • 130

4 Answers4

6

raw_input returns a string like "8675409". When you iterate over this string (it's not a list), you get the string "8", then "6", then "7" -- it will eventually be "4", but never be the int 4.

Mike Graham
  • 73,987
  • 14
  • 101
  • 130
2

The problem is that you don't pass a list of numbers to your function because raw_input returns a string.

number_list = raw_input("Enter list of integers here: ")
number_list = map(int, number_list.split())
print num_four(number_list)

This assumes that the numbers you input are separated by whitespace. If you just put in strings like '1234', iterate over the string and check against '4' instead of the integer 4 in your function. If that's the case, consider renaming number_list to something more fitting like continuous_number_string.

And if you want to simplify your function, use the count method of either str or list:

>>> [1,2,3,4,4,5].count(4)
2
>>> '1234544'.count('4')
3
timgeb
  • 76,762
  • 20
  • 123
  • 145
0

raw_input will produce a string, not a list of integers, regardless of what you type in. So i will never equal 4 (integer) at most "4" (string).

zebralove79
  • 100
  • 7
0

Please check the answer of @Mike Graham.

And just in case you are looking for a more Pythonic solution:

from collections import Counter
Counter(raw_input()).get("4")
Jordan Jambazov
  • 3,460
  • 1
  • 19
  • 40