1

Python: print even numbers including 0

guys!

I'm trying to solve a Python quiz given a program that outputs all the numbers from 0 to 10, but I must print only the even numbers. I'm using this code:

x = 0
while x <= 10:
    x += 1
    if x % 2 == 0:
        print(x)

The output shows numbers from 2 to 10, excluding 0, which I need to include. How can I print even numbers from 0 to 10?

Thanks!

Submitted May 05th 2021 by Admin

Answers
0

Increment x after the if block.

Admin | 4 months ago


0

x = 0
while x <= 10: if x % 2 == 0: print(x) x += 1 # increment x AFTER the if statement, otherwise you never check if 0%2 == 0

You could also use a for-loop to simplify things further:

for x in range(11): if x%2 == 0: print(x)

Admin | 4 months ago


0

hmmm....can you ask quiz questions on here? anyhow, I think the small edit to the order of operations in your loop should do it?

x = 0
while x <= 10: if x % 2 == 0: print(x) x += 1

Admin | 4 months ago


0

As others have said, the problem is that you're incrementing x before you check if it's even, so you increment from 0 to 1 before printing.

But there's no need for the test, you can just loop over the even numbers:

for x in range(0, 11, 2): print(x)

The third argument to range() is the steps, and stepping by 2 just returns even numbers.

Admin | 4 months ago



Relevant Questions