0

I'm trying to create a code that will print every number in a range set by the user, and then identify how many numbers in that range are odd numbers and how many are even.

I've tried a few different formats, but I'm very much a beginner and can't seem to nail down where I'm going wrong. I'm trying to keep the code as simple as possible.

for i in range(x,y+1):
       print(i)

range = (x,y+1)
count_odd = 0
count_even = 0
for n in range:
        if   n%2==0:
             count_even = count_even+1
        else:
             count_odd = count_odd+1
print("Number of even numbers :",count_even)
print("Number of odd numbers :",count_odd)

Currently when I run this, even numbers always comes to 0 and odd to 2.

3 Answers 3

2

On line 4 you have:

range = (x,y+1)

This is the tuple (x, y+1) not the range between them. So when you loop through it you are only looping through those two numbers. I assume in your case they are both odd. I would recommend removing that line and starting your second for loop like this:

for n in range(x, y + 1):
0

range is a builtin function, which returns an iterable from [start, end). You likely want something like:

count_odd = 0
count_even = 0
for n in range(x,y+1):
    if n % 2 == 0:
        count_even = count_even + 1
    else:
        count_odd = count_odd + 1

print("Number of even numbers :", count_even)
print("Number of odd numbers :", count_odd)
0
0

There's no point for a loop. If your range consists of even elements, then half of values is even and half is odd. If it consists og odd elements and starts from odd value then half+1 is odd and half-1 is even. It starts with even value then it's opposite.

1
  • Since OP mentions s/he's a beginner, this is likely an exercise to learn how to use for loops and ranges. Feb 17, 2019 at 6:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.