1

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 Answer 1

3

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: ")
Sign up to request clarification or add additional context in comments.

3 Comments

Shouldn't you be sleeping now? Good rest is important ;) +1 to get you to go :p
@mozway LMAO. Fair enough. Away I go :P
Omg you just blew my mind away, I knew about functions but I didn't know when to use them, but now I got a good idea of it, thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.