0

I want to make python identify if num1 and num2 were numbers or not in this calculator so that python can notify you're not typing in valid things. Maybe using if statements?

num1 = float(input("Enter a number: "))
num2 = float(input("Enter a number: "))
op = input("What operator would you use?")
if op == "+":
    print(num1 + num2)
elif op == "-":
    print(num1 - num2)
elif op == "*":
    print(num1 * num2)
elif op == "/":
    print(num1 / num2)
else:
    print("Invalid operator")

1 Answers1

2

You can wrap it in a try-except block:

try:
    num1 = float(input("Enter a number: "))
    num2 = float(input("Enter a number: "))
except ValueError:
    print("Invalid number")

If you wanted to keep prompting the user:

while True:
    try:
        num1 = float(input("Enter a number: "))
        break
    except:
        print("Invalid number")

And do the same for num2.

iz_
  • 15,923
  • 3
  • 25
  • 40