May-22-2019, 01:52 PM
I just started learning python 3 this week and I'm trying to a code a simple calculator. I'm a straight beginner and have a good passion to learn python.
What I'm trying to do is have my code throw out an error to user if they do not enter in a valid number.
Example: if user enters in a 5 then the program does nothing and continues to the next line, but if the user enters in a letter then the program will tell the user "Hey that's not a valid number!".
Here is my code:
-Currently the program spits out an error to user if they enter in something other than a valid math operation.
-Desired is to have the program spit out another error to the user if they don't enter in a proper integer/float
What I'm trying to do is have my code throw out an error to user if they do not enter in a valid number.
Example: if user enters in a 5 then the program does nothing and continues to the next line, but if the user enters in a letter then the program will tell the user "Hey that's not a valid number!".
Here is my code:
-Currently the program spits out an error to user if they enter in something other than a valid math operation.
-Desired is to have the program spit out another error to the user if they don't enter in a proper integer/float
#Simple Calculator v1.0 print("::: Welcome To My Calculator :::") print("::: Welcome To My Calculator :::") print("::: Welcome To My Calculator :::\n") print("Math Operations") print(" +\n" " -\n" " *\n" " /\n") num1 = float(input("Enter First Number: ")) op = input("Enter Operation: ") num2 = float(input("Enter Second Number: ")) try: val = int(num1) except ValueError: print("Error: Enter A Valid Number") try: val = int(num2) except ValueError: print("Error: Enter A Valid Number") if op == "+": print(num1 + num2) elif op == "-": print(num1 - num2) elif op == "*": print(num1 * num2) elif op == "/": print(num1 / num2) else: print("Not a valid math problem")Console Error:
Enter First Number: 54 Enter Operation: - Enter Second Number: Hi Traceback (most recent call last): File "C:/Users/Xerxes/PycharmProjects/New Projects/Calculator.py", line 10, in <module> num2 = float(input("Enter Second Number: ")) ValueError: could not convert string to float: 'Hi' Process finished with exit code 1