Reputation: 1
I need to write a program which checks whether each number on a comma separated string is even or odd.
I have to do it with a for
loop, the code I have is this:
getallen = '12, 3, 7, 25, 771, 45, 6, 98, 55, 546'
for number in getallen:
if number %2 == 0:
print(f'{int(number)} is even')
else:
print(f'{int(number)} is odd')
The output should be something like this:
12 is even
3 is odd
7 is odd etc etc.
Upvotes: 1
Views: 798
Reputation: 52019
Your string is a tuple literal, so you can just use ast.literal_eval
to safely convert it to a tuple of integers. This can be directly used in your for
loop.
import ast
getallen = '12, 3, 7, 25, 771, 45, 6, 98, 55, 546'
for number in ast.literal_eval(getallen):
if number %2 == 0:
print(f'{int(number)} is even')
else:
print(f'{int(number)} is odd')
Upvotes: 0
Reputation: 7056
Matt is right that you're iterating over a string, and not an array, but after splitting you also need to convert each value to a number. There's a couple ways to do this:
You can use map
to convert each item of the array to a number using int
:
for number in map(int, getallen.split(',')):
if number %2 == 0:
print(f'{int(number)} is even')
else:
print(f'{int(number)} is odd')
Or you can convert each number as you test it:
for number in getallen.split(','):
if int(number) %2 == 0:
print(f'{int(number)} is even')
else:
print(f'{int(number)} is odd')
Both of these will yield:
12 is even
3 is odd
7 is odd
25 is odd
771 is odd
45 is odd
6 is even
98 is even
55 is odd
546 is even
Upvotes: 1
Reputation: 518
Your code is not working because getallen
is a string, not an array. You need to convert it to an array first with getallen = getallen.split(',')
Upvotes: 1