Home > Net >  using if-elif-else statments for adding two integers
using if-elif-else statments for adding two integers

Time:11-30

I have just starting learning python and as I creating this program, which asks user to input two numbers, which then adds them to together using a simple if-elif-else statement, however the else part of the code just seems to not work if, an user types out the six, for example, in words instead of the number.

num_1 = int(input("Enter the first number: "))
num_2 = int(input("Enter the second number: "))
Total = num_1   num_2

print("The total is: ",Total)

if num_1 > num_2:
    print("num_1 is greater then num_2")
elif num_2 > num_1:
    print("num_2 is greater then num_1")
elif num_1 == num_2:
    print("Equal")
else:
   if num_1 == str:
       if num_2 == str:
           print("invalid")

CodePudding user response:

In your first two lines you’re calling int() on a string in the situation you’re describing. This won’t work, and your code will stop running here. What you want is probably something call a try-catch statement.

CodePudding user response:

This should be what you are looking for:

try:
    num_1 = int(input("Enter the first number: "))
    num_2 = int(input("Enter the second number: "))
except ValueError:
   print("invalid")
   exit()
Total = num_1   num_2
print("The total is: ", Total)

if num_1 > num_2:
    print("num_1 is greater then num_2")
elif num_2 > num_1:
    print("num_2 is greater then num_1")
elif num_1 == num_2:
    print("Equal")
  • Related