Home > Mobile >  Calculator not working if you enter a letter instead of a number
Calculator not working if you enter a letter instead of a number

Time:11-07

My Calculator is half working. I really put my brain in it but I cant figure out why its not working. Can someone help me?

number1 = input("Enter first number: ")
number2 = input("Enter second number: ")
operator = input("Enter the operation character: ")
result = number1   operator   number2

if operator == ' ':
    result = int(number1)   int(number2)
elif operator == '-':
    result = int(number1) - int(number2)
elif operator == '*':
    result = int(number1) * int(number2)
elif operator == '/':
    result = int(number1) / int(number2)
if number1.isdigit() == True:
    print (result)
elif number2.isdigit() == True:
    print(result)
else:
    print("Enter a number.")

It's printing the calculated value, but if you enter a letter instead of a number. For example: Enter a first number: 5 Enter a second number: f Now it should print "enter a number". But im getting this message istead ValueError: invalid literal for int() with base 10: 'a'

if number1.isdigit() == True:
    print (result)
elif number2.isdigit() == True:
    print(result)
**else:
    print("Enter a number.")**

CodePudding user response:

You have lines like these:

if operator == ' ':
    result = int(number1)   int(number2)

Before lines like these:

if number1.isdigit() == True:
    print (result)
elif number2.isdigit() == True:
    print(result)
else:
    print("Enter a number.")

So, if operater is indeed a , Python will try to evaluate int(number1) int(number2) and fail if number1 or number2 is not the string representation of a number.

This raises a ValueError (as it should) and a raised exception that isn't caught in a try .. except .. block will cause your program to terminated. You cannot continue with uncaught exceptions.

Either you should check first and then try to convert these strings, or you should catch the exception.

Also, you seem to expect your code to continue running after the mistake is made, so you'll need some sort of loop that keeps the program running until the user enters some input that makes sense.

CodePudding user response:

I am not sure that I understood what you what but I think this solves the problem

number1 = input("Enter first number: ")
number2 = input("Enter second number: ")
operator = input("Enter the operation character: ")
result = number1   operator   number2

if number1.isdigit() == True and number2.isdigit() == True:
    if operator == ' ':
        result = int(number1)   int(number2)
    elif operator == '-':
        result = int(number1) - int(number2)
    elif operator == '*':
        result = int(number1) * int(number2)
    elif operator == '/':
        result = int(number1) / int(number2)
    print (result)
else:
    print("Enter a number.")

CodePudding user response:

If you are just starting on coding, I suggest you to use this as a reason to search and learn on some few important concepts that will help you to get going.

First, you must validate your inputs before doing anything else with them. In your case, validate that your first and second numbers are actually valid integers, right after they are input. As it is the same validation to be done on both, you can create a function so you can reuse the logic.

def input_number():
    num = input("Enter a number: ")
    if num.isdigit():
        return int(num)
    else:
        print("Invalid number.")
        return input_number()

Here, I check if the input is valid (isdigit is true), and then I return the value already converted to int. If it is not, I call the same function again, and repeat the process. This is called recursion.

You should also validate the operator, because it is only valid among a few options.

def input_operator():
    while True:
        op = input("Enter the operation character: ")
        if op in [" ", "-", "*", "/"]:
            return op
        else:
            print("Invalid operator.")

Here I used a different technique. It is called while statement, and it will repeat the execution inside it until the condition is not True, or until it is explicitly broken (in this case, with a return statement).

Now, you have to add both function definitions on top of your code, then adjust you logic accordingly.

number1 = input_number()
operator = input_operator()
number2 = input_number()

if operator == " ":
    result = number1   number2
elif operator == "-":
    result = number1 - number2
elif operator == "*":
    result = number1 * number2
elif operator == "/":
    result = number1 / number2

print (result)
  • Related