Reputation: 9
def calculation():
num1 = float(input())
num2 = float(input())
op = input()
if op == "+": #code for addition
print(num1 + num2)
elif op == "-": #code for subtraction
print(num1 - num2)
elif op == "/": #code for division
print(num1 / num2)
elif op == "*": #code for multiplication
print(num1 * num2)
#elif ZeroDivisionError:
#print("Divided by zero")
else: #code if invalid operator is entered
print("Invalid operator entered")
calculation() #calling the fucntion
Right now the code only runs when I call the function. Id like it to run non-stop, like a physical calculator. I am also trying to sort out how to not break the code if division by 0 occurs. Thank you for any help.
Upvotes: 0
Views: 600
Reputation: 73460
A simple infinite loop will do:
while True:
calculation()
You can also shorten your calculation
function, mapping your symbols to the appropriate operator
functions and handling exceptions as they occur:
from operator import add, sub, mul, truediv
ops = {"+": add, "-": sub, "*": mul, "/": truediv}
def calculation():
num1 = float(input())
num2 = float(input())
op = input()
try:
print(ops[op](num1, num2))
except KeyError:
print("Invalid operator entered")
except ZeroDivisionError:
print("Divided by zero")
Upvotes: 1
Reputation: 578
I believe the default way is to use while True
:
while True:
# your code here
True is by default True, so your program will run until it is manually terminated.
As with the division by zero, you can do
...
elif op == "/": #code for division
if num2 == 0:
print('Cannot divide by zero!')
else:
print(num1 / num2)
Upvotes: 1