Reputation: 19
to_ten=['1','2','3','4','5','6','7','8','9','10']
for i in range(10):
if i %2==0:
i='Number is even'
else: i='Number is odd'
print(i)
Create a list called to_ten containing the numbers from 1-10.Write a for loop that iterates over to_ten and prints out whether the number is even or odd. Please help me understand how to get a statement for each number in the 1-10 list about whether it is even or odd.
Upvotes: 0
Views: 1242
Reputation: 41872
There are three issues with your code: first, you substitute a range()
for to_ten
so don't actually implement the problem as stated; you make to_ten
a list
of str
instead of a list
of int
; your print(i)
statement is in the wrong order and at the wrong indentation. The solution of @biplobbiswas does a nice job of addressing all of these minor issues. (+1)
We can simplify the problem by making to_ten
a list
of int
, and have Python generate it for us, to avoid errors. We can also use the result of i % 2
as an index rather than test it explicitly with a series of if
statements:
to_ten = [*range(1, 11)] # a list containing the numbers from 1-10
for number in to_ten:
print("{} is {}".format(number, ['even', 'odd'][number % 2]))
There are numerous ways to go about a problem like this.
Upvotes: 0
Reputation: 27567
but you need to indent the print statement in order for the program to print the number in each iteration.
And, range(num) will begin at 0, and the num will not be included in the iteration.
[1,2,3,4,5,6,7,8,9,10]
is equivalent to range(1,11)
in python.
for i in range(1,11):
if i % 2 == 0: # If the number divided by two leaves no remainder:
print(f'{i} is even')
else:
print(f'{i} is odd')
Output:
1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
10 is even
Upvotes: 0
Reputation: 104
to_ten=['1','2','3','4','5','6','7','8','9','10']
for i in to_ten:
if int(i)%2 == 0:
print(f'{i} is even')
else:
print(f'{i} is odd')
Out:
1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
10 is even
Upvotes: 1