1

Write a Python program to count the number of even and odd numbers from input.

count_even = 0
count_odd = 0
numbers = input()
for x in numbers:
  for i in x:
    if i % 2 == 0 :
      count_even += 1
    else:
      count_odd += 1
print(count_even)
print(count_odd)

ERROR: Traceback (most recent call last): File "main.py", line 6, in if i % 2 == 0 : TypeError: not all arguments converted during string formatting 

2
  • What is your input ? From what I understand, input() returns a string Commented Oct 20, 2020 at 12:30
  • input example :12 Commented Oct 20, 2020 at 13:03

2 Answers 2

1

First, I'm not sure why you are iterating twice over one list. Second, if you're expecting a list delinated by spaces, you need to split it into it's elements and then you need to convert each item to an integer that you can then iterate over.

count_even = 0
count_odd = 0
numbers = input()
print(numbers)
for x in numbers.split():
    if int(x) % 2 == 0:
        count_even += 1
    else:
        count_odd += 1
print(count_even)
print(count_odd)

Sign up to request clarification or add additional context in comments.

Comments

-1

I see a couple issues with the code. The first thing is, I don't see x and i being created or declared. The second thing is, when you do numbers = input(), the variable type of numbers is a string. You might want to change it to numbers = int(input())

3 Comments

File "main.py", line 1, in <module> numbers = int(input()) ValueError: invalid literal for int() with base 10: '1 2 3' 
if you have spaces in your input, you can use : num=numbers.split() for i in num : if int(i)%2==0 :...
x and i are declared in the for loop. The question may have been modified since you posted this answer but you should now remove or update this answer as there is no need to explicitly create x and i.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.