-1

Just like how num1 will only except an integer, I want op to only except the symbols "/*-+" and if the person inputs something otherwise I can then throw up an "invalid operator" message right after they input something other than those 4 symbols.

try:
    num1 = float(input("enter a number"))
    op = input(("enter a operator"))
    num2 = float(input("enter another number"))
    if op == "+":
         print(num1 + num2)
    elif op == "-":
         print(num1 - num2)
    elif op == "*":
         print(num1 * num2)
    elif op == "/":
        print(num1 / num2)
except ValueError:
        print("invalid operator")
except:
        print("invalid")
MSeifert
  • 145,886
  • 38
  • 333
  • 352
caleb282
  • 11
  • 3
  • It looks like the indentation is a bit off in the `except` clauses. – MSeifert Aug 17 '19 at 16:13
  • similar question [here](https://stackoverflow.com/questions/23326099/how-can-i-limit-the-user-input-to-only-integers-in-python) - maybe you can apply something like that? – FObersteiner Aug 17 '19 at 16:15

3 Answers3

1

You can do a while loop and check the string each time user enters a value.

while True:
    user_input = input('Operation: ')
    if len(user_input) == 1 and user_input in '+-*/':  break
    else: print('Invalid operation!')
enzo
  • 9,861
  • 3
  • 15
  • 38
0

I took a different approach and only allowed the user to continue after entering valid information.

import operator

def get_int_only(s: str):
    while True:
        in_str = input(s)

        try:
            out = int(in_str)
        except ValueError:
            continue
        else:
            return out


def get_str_in_list_only(s: str, ls: list):
    while True:
        in_str = input(s)

        if in_str in ls:
            return in_str

table = {"+": operator.add,
         "-": operator.sub,
         "*": operator.mul,
         "/": operator.truediv,
         "//": operator.floordiv,
         "^": operator.pow
         }

num1 = get_int_only("Number 1: ")
num2 = get_int_only("Number 2: ")
op = get_str_in_list_only("Operator: ", table.keys())

print(table.get(op)(num1, num2))

Operator module

Dictionary datatype

Joshua Nixon
  • 1,379
  • 2
  • 12
  • 25
0

You can try to make an array with all the operators, like so: operators = ['+', '-', '*', '/'] and then loop over each item and compare.

operators = ['+', '-', '*', '/']

for operator in operators:
    if op == operator:
        # Do something...
    else:
        print("Invalid operator")
        break
Ayaan Siddiqui
  • 300
  • 1
  • 3
  • 10