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.
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.
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("")
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.
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.
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("")