Printing an extra number

Question:

I’m asking the user to enter a number, then printing every even number up to the number entered. problem is if the inputed number is odd then the program prints an extra number.

What’s happening?

num1 = int(input("Please enter a number : "))
num2 = 0

while num1 > num2:
    num2 += 2
    if num2 % 2 == 0:
        print(num2)
    else:
        num2 -= 2
        print(num2)
Asked By: Thorn

||

Answers:

num1 = int(input("Please enter a number: "))
num2 = 0

while num1 > num2:
    if num2 % 2 == 0:
        num2 += 2
        if num2 > num1:
            break
        print(num2)
Answered By: user20251230

Let’s settle this problem first step by step

If else statement is not needed
Your if else checks if num2 is even, but since num2 will always start at 0, and then be incremented by 2, it will always be even.
So this is what your code currently does :

num1 = int(input("Please enter a number : "))
num2 = 0

while num1 > num2:
    num2 += 2
    print(num2)

This should explain better why the program prints an extra number for an even input number.

Correct version
A very simple way to correct this code, would be to slightly change the while condition and add +1 to num2

num1 = int(input("Please enter a number : "))
num2 = 0

while num1 > num2 + 1:
    num2 += 2
    print(num2)

So here, it will print even numbers from 2 to num1
If num1 is even, it stops at num2 == num1 + 1
If num1 is not even, it stops at num2 == num1 + 2

Answered By: Skoh
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.