user3089079
user3089079

Reputation: 59

How to get the mod of every number on a list in python

What's wrong with this code? (I'm trying to get the user to input 10 integers and then return the greatest odd number, if no odds then return a statement saying so)

numbers = raw_input('Enter 10 integers separated by comma ')
numbers = [numbers.split(',')]
odds = [x for x in numbers if x%2==1]

if not odds:
 print "no odd number was entered"
else:
 print max(odds)

Upvotes: 0

Views: 1084

Answers (2)

user2555451
user2555451

Reputation:

You need to do two things:

  1. Remove the square brackets on this line:

    numbers = [numbers.split(',')]
    

    Otherwise, the list returned by str.split will be placed inside another list.

  2. Convert the list of strings returned by str.split into a list of integers. This can be done with map and int:

    numbers = map(int, numbers.split(','))
    

    Otherwise, the % in the next line will be interpreted as string formatting, which will raise an error:

    Traceback (most recent call last):
      File ".\t.py", line 3, in <module>
        odds = [x for x in numbers if x%2==1]
    TypeError: not all arguments converted during string formatting
    

Below is a fixed version of your script:

numbers = raw_input('Enter 10 integers separated by comma ')
numbers = map(int, numbers.split(','))
odds = [x for x in numbers if x%2==1]

# The Python standard for indentation is 4 spaces
if not odds:
    print "no odd number was entered"
else:
    print max(odds)

Demo:

>>> numbers = raw_input('Enter 10 integers separated by comma ')
Enter 10 integers separated by comma 1,2,3,4,5,6,7,8,9,10
>>> numbers = map(int, numbers.split(','))
>>> odds = [x for x in numbers if x%2==1]
>>> if not odds:
...     print "no odd number was entered"
... else:
...     print max(odds)
...
9
>>>

Upvotes: 1

D.Shawley
D.Shawley

Reputation: 59563

I'd guess that numbers is a list of str instances. Try numbers = [int(n) for n in numbers.split(',')].

Upvotes: 3

Related Questions