1

I'm starting to learn Python I wrote a code to get a list of numbers from the user and show the even numbers:

numbers=list(input("Please enter numbers:"))

def is_even_num():
    enum = []
    for n in numbers:
        if n % 2 == 0:
            enum.append(n)
    return enum

print(is_even_num())

But unfortunately it shows the following error Can you please tell me what the error means and how can I fix the error?

Mace
  • 1,270
  • 7
  • 12
Y.Z
  • 9
  • 1

4 Answers4

0

But unfortunately it shows the following error Can you please tell me what the error means and how can I fix the error?

You are getting TypeError exception at if n % 2 == 0: as interpreter is trying to apply formatting using %. input() returns a str object and if you pass it to list constructor, it will form a list of characters in your string.

Therefore, numbers=list(input("Please enter numbers:")) will be forming a list of str objects (For example, if you pass 1 2 3 to your program, it will convert it to a list of str object: ['1', ' ', '2', ' ', '3']).

You need to convert them to int using int constructor. If you can just change the first line in your program to numbers=list(map(int, input("Please enter numbers: ").split(" "))), it will start working

Try this:

numbers=list(map(int, input("Please enter numbers: ").split(" ")))
def is_even_num():

    enum = []
    for n in numbers:
        if n % 2 == 0:
            enum.append(n)
    return enum
print(is_even_num())

Pythonic way of doing the same thing using list comprehension:

print([i for i in map(int, input("Please enter the number: ").split(" ")) if not i % 2])
abhiarora
  • 8,763
  • 5
  • 30
  • 50
0

numbers=list(input("Please enter numbers:")) will convert each char to an element in a list, i.e. if you input 1 2 3 4, each whitespace will also be an element. Try

numbers=input("Please enter numbers:").split()

This will omit whitespaces.

Also, you're trying to compare a string literal to an integer. In your loop, parse n as an integer, i.e.

if int(n) % 2 == 0:
Badgy
  • 799
  • 3
  • 14
0
numbers=[int(i) for i in input().split()]
def is_even_num():

    enum = []
    for n in numbers:
        if n % 2 == 0:
            enum.append(n)
    return enum
print(is_even_num())

Input is stored as a string , we need to type cast it into an integer before performing any kind of arithmetic operations on it

Sai Teja
  • 1
  • 1
  • 4
0

numbers is a list of strings, including strings with only spaces

['3', ' ', '5', ' ', '8']

These spaces you have to remove and then convert the remaining number strings to ints before you use the modulo %

numbers = list(input("Please enter numbers:"))

print(numbers)

def is_even_num():
    enum = []
    for n in numbers:
        if n.strip(' '):
            if int(n) % 2 == 0:
                enum.append(int(n))
    return enum

print(is_even_num())
Mace
  • 1,270
  • 7
  • 12