I am running into a problem, I am trying to make a calculator as my first program!(I am still a very beginner at programming), and i wan't it to print out a statement when someone enters a string rather than an integer , Here is my code:
add = ["add", "+", "plus"]
minus = ["minus", "-", "subtract"]
multiply = ["multiply", "*", "product"]
divide = ["divide", "/",]
quit = ["quit", "q", "leave", "shut down"]
retry = ["retry", "start again", "start", "r",]
leave = False
while True:
service = input("What would you like to do? ")
if service.lower() in add:
x = int(input("First number... "))
y = int(input("Second number... "))
print(x + y)
elif service.lower() in minus:
x = int(input("First number... "))
y = int(input("Second number... "))
print(x - y)
elif service.lower() in divide:
x = int(input("First number... "))
y = int(input("Second number... "))
print(x / y)
elif service.lower() in multiply:
x = int(input("First number... "))
y = int(input("Second number... "))
print(x * y)
elif service != int:
print("You entered a string , not an integer")
elif service.lower() in quit: #if the user types quit , it'll kill the loop
break
else:
print("Invalid command...Do you want to quit or retry? ")
lastOption = input()
if lastOption.lower() in quit: #If the user writes in quit , it'll kill the loop here
break
elif lastOption.lower() not in retry: #if the user inputs gibberish again, it begins a check otherwise it restarts
while True: #A loop begins if the user has entered an unrecognized input
print("Sorry I did not catch that, can you please repeat? ")
lastOption = input()
if lastOption.lower() in quit:
leave = True #sets leave condition to true as you cannot break two loops in one break statement
break
elif lastOption.lower() in retry:
break
if leave == True: #continuing on from the check loop for unrecognized inputs this allows you to break the loops
break
EDIT: Here is the "try" and "except" code added
while True:
service = input("What would you like to do? ")
if service.lower() in add:
try:
x = int(input("First number... "))
y = int(input("Second number... "))
print(x + y)
except ValueError:
print("You did not enter an integer")