Python: How to easily make specific string characters the only possible input

Viewed 40

I'm a beginner to coding, and I'm still doing my "first" calculator, and I was wondering how to make only 5 characters ("-" "+" "/" "x" "^") into the only possible input the user can answer, or it will result in a message saying "Invalid", sorry for my limited knowledge about this, it's also my first post here, thanks in advance! This is what I did so far -

try:
    number_1 = float(input("Insert number 1 here: "))
    sign = str(input("+ - / x ^: "))
    number_2 = float(input("Insert number 2 here: "))
except ValueError:
    print("Invalid")
    exit()
if sign != "-" "+" "/" "x" "^":
    print("Invalid")
    exit()
elif sign == "-":
    print(number_1 - number_2)
elif sign == "+":
    print(number_2 + number_1)
elif sign == "/":
    if number_2 == 0:
        print("Invalid")
        exit()
    print(number_1 / number_2)
elif sign == "x":
    print(number_1 * number_2)
elif sign == "^":
    print(number_1 ** number_2)
else:
    print("Invalid")
1 Answers

You can use the power of functions! Make a function that repeatedly asks for user input until they give you something valid!

def ask_float(title):
    while True:
        try: 
            return float(input(title))
        except ValueError:
            print("Invalid choice. Try again!")

def ask_sign():
    while True:
        sign = input("+ - / x ^: ").strip()
        if sign in ("+", "-", "/", "x", "^"):
            return sign
        print("Invalid choice. Try again!")

Now in your code you can do:

number_1 = ask_number("Insert number 1 here: ")
sign = ask_sign()
number_2 = ask_number("Insert number 2 here: ")
Related