Is there a way to make my calculator function simpler and easier to read?
I tried looping it, but all in all it looks too complicated somehow.
def calculator():
while True:
calc = input("Enter 'add', 'sub', 'mul' or 'div': ")
if calc == 'add':
first = float(input("First number: "))
second = float(input("Second number: "))
result = first + second
print("Result:", result)
break
elif calc == 'sub':
first = float(input("First number: "))
second = float(input("Second number: "))
result = first - second
print("Result: ", result)
break
elif calc == 'mul':
first = float(input("First number: "))
second = float(input("Second number: "))
result = first * second
print("Result: ", result)
break
elif calc == 'div':
first = float(input("First number: "))
second = float(input("Second number: "))
if second != 0:
result = first / second
print("Result: ", result)
break
else:
print("It's not possible to divide by zero. Please try again.")
else:
print("Incorrect variables. Please try again.")
if __name__=="__main__":
calculator()
You could make use of operator:
Out: