-2
name = input("What's your name?\n")
print("Hello, %s.\nWelcome to the best calculator program in the world.\nSelect an operation to get started.\n------------------------------------------------------------------" % name)
def add(x, y):
   return x + y
def subtract(x, y):
   return x - y
def multiply(x, y):
   return x * y
def divide(x, y):
   return x / y
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
choice = input("What operation would you like to use?: ")
num1 = float(input("Enter your first number, please: "))
num2 = float(input("Enter your second number, please: "))
if choice == '1':
   print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
   print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
   print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
   print(num1,"/",num2,"=", divide(num1,num2))
else:
   print("Looks like you tried to use something other than 1, 2, 3, or 4. Try again")

As you can see, I am creating a very simple calculator in Python 3 and I want to display an error message in case a user selects something that is not 1, 2, 3, or 4. How can I do that? This current code only displays the error message after the user has already entered the numbers they want to add, subtract, multiply, or divide, which seems a bit counter-intuitive.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
C.Obi
  • 1
  • I tried to use `if !=` but that didn't work either. I don't really know what else to do – C.Obi Dec 14 '19 at 15:51

1 Answers1

0

You'll have to ask for the input, and validate input in the order in which you'd like for things to happen. Ask the user for a selection in a loop. If they enter something invalid, ask them to try again. Don't break out of the loop until they enter something valid. Once they do, move on to the next input.

options = [
    ("1", "Add"),
    ("2", "Subtract"),
    ("3", "Multiply"),
    ("4", "Divide")
]

for option in options:
    print("{}. {}".format(*option))

message = "Enter your selection: "
while True:
    user_selection = input(message)
    if user_selection in map(lambda tpl: tpl[0], options):
        break
    message = "Try again: "

Output:

1. Add
2. Subtract
3. Multiply
4. Divide
Enter your selection: asdasd
Try again: 678
Try again: 5
Try again: 3
>>> 
Paul M.
  • 10,481
  • 2
  • 9
  • 15