Motaz Abo Elnasr
Motaz Abo Elnasr

Reputation: 55

What is the wrong in that easy python code?

my_list = input("Enter a list of numbers separated by space")
my_list = my_list.split(' ')
counter = 0
for i in my_list:
    if i == 4:
        counter = counter + 1
print('the count is ', counter)

The expected output is how many times the number 4 occurs in the list. The actual output is zero no matter what the input is.

Upvotes: 1

Views: 107

Answers (4)

Pythonista
Pythonista

Reputation: 19

line 5. You should put '4' instead of just 4 because 4 is integer and the list is made of strings. So you can't expect that a programe will look for integers in a string "group".

Upvotes: 0

Shmygol
Shmygol

Reputation: 933

As some answerers already pointed out, you're trying to compare 4 with '4'. Here are you options:

1) Cast i to string. But make sure, that your script doesn't crash in case of non-integer input:

my_list = input("Enter a list of numbers separated by space")
my_list = my_list.split(' ')
counter = 0
for i in my_list:
    try:
        i = int(i)
    except ValueError:
        continue
    if i == 4:
        counter = counter + 1

print('the count is ', counter)

2) 4 is hardcoded. You could use just '4' instead of 4

my_list = input("Enter a list of numbers separated by space")
my_list = my_list.split(' ')
counter = 0
for i in my_list:
    try:
        i = int(i)
    except ValueError:
        continue
    if i == '4':
        counter = counter + 1

print('the count is ', counter)hth

3) You don't really need a for loop to count symbols:

my_list = input("Enter a list of numbers separated by space")
my_list = my_list.split(' ')
counter = my_list.count('4')

print('the count is ', counter)

Or even so, but it gives a bit different result for cases like 'a4a 4':

input_value = input("Enter a list of numbers separated by space")

print('the count is ', input_value.count('4'))

Upvotes: 1

totallyhuman
totallyhuman

Reputation: 155

my_list is a list of strings.

>>> '4' != 4
True

The string '4' is not equivalent to the integer 4.

>>> my_list = input("Enter a list of numbers separated by space")
1 42 3 5 4
>>> my_list = my_list.split(' ')
>>> my_list
['1', '42', '3', '5', '4']
>>> for i in my_list:
...     if i == 4:
...         print("It's 4!")
>>> for i in my_list:
...     if int(i) == 4:
...         print("It's 4!")
It's 4!

You need to convert i to an int in your check for equality with 4. You can do this with the function int.

The other alternative is to map int over the list of strings.

>>> for i in map(int, my_list):
...     if i == 4:
...         print("It's 4!")
It's 4!

Upvotes: 3

Kashyap Murali
Kashyap Murali

Reputation: 39

They are all in string so you need to convert them into integers

Upvotes: 0

Related Questions