Python Forum
need help on logic for even or odd
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
need help on logic for even or odd
#1
what is the indentation error here ?

any suggestions at "else:" ?


for i in range(1 ,10):
  count_even=0
  count_odd=0
  if (i%2==0):
    count_even=count_even+1
print(count_even)
       else:
      count_odd=count_odd+1
print(count_odd)
  
Reply
#2
I see in line 4 is indented 2 spaces. This is good, it is in the loop on line 1. line 5 is indented 6 spaces. Still good, inside the line 4 if loop. Line 6, is not good, needs to be 6 spaces in. Line 7 needs to be 4 spaces in. Line 9 needs to be 6 spaces in. I think I am correct.
Reply
#3
The indentation should look like the following, note: you need to move the assigning of count_even and count_odd to before the loop otherwise they will be set to zero on each iteration.
count_even = 0
count_odd = 0

for i in range(1, 10):

    if (i % 2 == 0):
        count_even = count_even+1
        print(count_even)
    else:
        count_odd = count_odd+1
        print(count_odd)
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020