0

Basically im building a basic calculator and im thinking of adding the feature where if an invalid value has been entered by the user it would say "Invalid number please try again" and have the user enter a number again.


#Obtaining the first number
numb_1 = input("Enter the first number:")

#Verifying if the value is valid
while True:
    try:
        float(numb_1)
    except ValueError:
         print("Invalid number please try again.")
         numb_1 = input("Enter the first number:")

    else :
        break

#Obtaining the operator
operator = input("Enter an operator:").strip()

#Verifying if the operator is valid
while operator != ("+") and operator != ("-") and operator != ("*") and operator != ("/"):
    print("Invalid operator please try again.")
    operator = input("Enter an operator:")

#Obtaining the second number
numb_2 = input("Enter the second number:").strip()

#Verifying if the value is  valid
while True:
    try:
        float(numb_2)

    except ValueError:
         print("Invalid number please try again.")
         numb_2 = input("Enter the second number:")

    else :
        break

#Doing the math
if operator == ("+"):
    print(numb_1 + numb_2)

elif operator == ("-"):
     print(numb_1 - numb_2)

elif operator == ("*"):
    print(numb_1 * numb_2)

elif operator == ("/"):
            print(numb_1/ numb_2)

The above is my code but whenever I run it i get the error

Traceback (most recent call last):
  File "C:\Users\User\PycharmProjects\Cactus\aopp.py", line 44, in <module>
    print(numb_1 - numb_2)
TypeError: unsupported operand type(s) for -: 'str' and 'str'

And currently I have come up with this solution, but im thinking if there's a better way to do this?

numb_3 = float(numb_1)
numb_4 = float(numb_2)

#Doing the math
if operator == ("+"):
    print(numb_3 + numb_4)

elif operator == ("-"):
     print(numb_3 - numb_4)

elif operator == ("*"):
    print(numb_3 * numb_4)

elif operator == ("/"):
            print(numb_3 / numb_4)
Dylan
  • 19
  • 2
  • 1
    You are on the right track with your code with the while-loop and the `try-except`, but you aren't doing anything with the result of `float(numb_1)`. You'd want something like `numb_1 = float(numb_1)`. Good job catching the `ValueError` explicitly. – juanpa.arrivillaga Feb 01 '21 at 09:16
  • 1
    Thanks for the reply. I understand why the error now! – Dylan Feb 01 '21 at 09:23

0 Answers0