0

I am trying to print numbers based on 2 user input numbers. If the first is smaller than the second, print from the smaller to larger. If the first is greater than the second, print from the larger down to the smaller.

Both the statements in if & else statements have been tested to contain the correct logic. However, only the if statement works, but when the else condition is tested, system fails to execute the else statements.

def question1c():
    firstNum = int(input("Enter first number: "))
    secondNum = int(input("Enter second number: "))
    if firstNum < secondNum: 
        for n in range(firstNum, secondNum + 1):
            print(n)
    else: 
        for n in range(secondNum, firstNum - 1, -1):
            print(n)
question1c()

Scenario 1:

Enter first number: 10
Enter second number: 12
10
11
12

Scenario 2:

Enter first number: 12
Enter second number: 10
12
11
10

Actual results for Scenario 2:

Enter first number: 12
Enter second number: 10 <-- fails to execute else statements
4
  • 4
    Check that range(secondNum, firstNum - 1, -1) does what you think it does. Aug 11, 2019 at 7:13
  • Hi @ItamarMushkin, yes the statement does work if i were to put it in the 'if' statement instead.
    – Jing Yi
    Aug 11, 2019 at 7:17
  • 1
    As mentioned by @ItamarMushkin, the else is definitely executing, but the for statement is being skipped due to the arguments you are giving the range() function.
    – MurrayW
    Aug 11, 2019 at 7:18
  • 1
    You are trying to count from 10 to 11 by a negative increment. Aug 11, 2019 at 7:24

2 Answers 2

2

Your problem is when firstNum = 12 and secondNum = 10, then the else is executed alright (because 12 >= 10), but then your range is:

range(10, 11, -1)

So the loop doesn't execute at all and nothing is printed (because you're trying to go down from 10 to 11.

As you can see you would want to change the range to:

range(firstNum, secondNum - 1, -1)

Alternatively, you could eliminate the conditions and use the direction in one range:

firstNum = int(input("Enter first number: "))
secondNum = int(input("Enter second number: "))

direction = 1 if firstNum < secondNum else -1

for n in range(firstNum, secondNum + direction, direction):
    print(n)
1

secondNum is smaller than firstNum so you cannot go down. Switch them.

else: 
    for n in range(firstNumNum, secondNum - 1, -1):
        print(n)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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