Getting strange and unexpected output from python while loop

Question:

I made a simple while loop to increase a number. And then I made a completely separate if condition to print a statement under certain circumstances. I don’t understand why the two are being joined together…..

Write a program whose input is two integers. Output the first integer
and subsequent increments of 5 as long as the value is less than or
equal to the second integer.

Ex: If the input is:

-15
10

the output is:

-15 -10 -5 0 5 10 

Ex: If the second integer is less than the first as in:

20
5

the output is:

Second integer can't be less than the first.

For coding simplicity, output a space after every integer, including
the last.

My code:

''' Type your code here. '''
firstNum = int(input())
secondNum = int(input())

while firstNum <= secondNum:
    print(firstNum, end=" ")
    firstNum +=5
    


if firstNum > secondNum:
    print("Second integer can't be less than the first.")

Enter program input (optional)

-15
10

Program output displayed here

-15 -10 -5 0 5 10 Second integer can't be less than the first.
Asked By: skysthelimit91

||

Answers:

Your while loop is ensuring firstNum > secondNum by the time it finishes running. Then, you check to see if firstNum > secondNum (which it is), and your print statement gets executed.

Answered By: Josh Clark
a = int(input())
b = int(input())
if b < a:
    print("Second integer can't be less than the first.")
else:
    while a <= b:
        print(a, end=" ")
        a = a + 5
    print("")
Answered By: Farmita Fariha
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.