2

I would like to protect the python calculator I have created from crashing when a user inputs a string instead of an integer.

I have tried doing so with an else statement printing "Invalid Input" (or something else I cant remember) when ever a user inputs a string instead of numbers.

I would also like to know if there is a way to let a user do another operation instead of having to restart the application.

If any importing is required (if you can) please list if it is compatible with cx_Freeze.

Source code:

def add (x, y):
    return(x + y)

def subtract(x, y):
    return(x - y)

def multiply(x, y):
    return(x * y)

def divide(x, y):
    return(x / y)

print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

choice = input("Enter choice(1/2/3/4):")

num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

if choice == '1':
   print(num1,"+",num2,"=", add(num1,num2))

elif choice == '2':
   print(num1,"-",num2,"=", subtract(num1,num2))

elif choice == '3':
   print(num1,"*",num2,"=", multiply(num1,num2))

elif choice == '4':
   print(num1,"/",num2,"=", divide(num1,num2))
else:
   print("Invalid input")

3 Answers 3

7

you can use something like this for input

while True:
    try:
        num1 = int(input("Enter first number: "))
    except ValueError:
        continue
    else:
        break
Sign up to request clarification or add additional context in comments.

3 Comments

I was writing a similar answer. Why not put that code in a function so it can be reused? :)
@AlokShankar can be. Just write an example and I think author should think is there a need for func or not :)
s/he is using the same functionality twice to get two inputs which is why I made the comment, but like you said, It is up to the author.
2

Take a look at the changes I have made to your code as follows:

def add (x, y):
    return(x + y)

def subtract(x, y):
    return(x - y)

def multiply(x, y):
    return(x * y)

def divide(x, y):
    return(x / y)

def input_number(prompt):
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            print("That was not a number")

# Keep going around the loop until the user chooses 5 to quit

while True:
    print
    print("Select operation.")
    print("1.Add")
    print("2.Subtract")
    print("3.Multiply")
    print("4.Divide")
    print("5.Quit")

    choice = input("Enter choice(1/2/3/4/5):")

    # Do they want to quit?

    if choice == 5:
        break

    num1 = input_number("Enter first number: ")
    num2 = input_number("Enter second number: ")

    if choice == 1:
        print(num1,"+",num2,"=", add(num1,num2))

    elif choice == 2:
        print(num1,"-",num2,"=", subtract(num1,num2))

    elif choice == 3:
        print(num1,"*",num2,"=", multiply(num1,num2))

    elif choice == 4:
        print(num1,"/",num2,"=", divide(num1,num2))

    else:
        print("%s - Invalid input" % choice)

In order to ask for more input, you needed to wrap your prompts in a loop. You would then need to add an option to the user to allow them to quit.

Also, you can move the prompting for numbers to a function. This would keep asking for number if the user typed in a character.

1 Comment

Bare except is generally a bad idea. Whilst I accept that in this case it's probably OK, it is not a good example to suggest.
1

This code snippet should help :-

def is_string(test_data):
    if type(test_data) is str:
        return True
    else:
        return False

Comments

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.