do a calculator in python code example
Example 1: simple python calculator
num1 = input('Enter first number: ')
num2 = input('Enter second number: ')
sum = float(num1) + float(num2)
sum2 = float(num1) - float(num2)
sum3 = float(num1) * float(num2)
sum4 = float(num1) / float(num2)
choice = input('Enter an operator, + = addition, - = subtraction, * = multiplication and / = division: ')
if choice == '+':
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
if choice == '-':
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum2))
if choice == '*':
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum3))
if choice == '/':
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum4))
Example 2: python calculator
import time
def cal():
def add(x, y):
print(x + y)
def sub(x, y):
print(x - y)
def mul(x, y):
print(x * y)
def div(x, y):
print(x // y)
while True:
print('Adding?(+) Subtracting?(-) Multiplying?(*) Dividing?(/)')
answer = input('')
if answer == "+":
try:
x = float(input('First number! '))
y = float(input('Second Number! '))
except Exception as e:
print(f'Error: {e}')
time.sleep(5)
return
add(x, y)
elif answer == "-":
try:
x = float(input('First number! '))
y = float(input('Second Number! '))
except Exception as e:
print(f'Error: {e}')
time.sleep(5)
return
sub(x, y)
elif answer == "*":
try:
x = float(input('First number! '))
y = float(input('Second Number! '))
except Exception as e:
print(f'Error: {e}')
time.sleep(5)
return
mul(x, y)
elif answer == "/":
try:
x = float(input('First number! '))
y = float(input('Second Number! '))
except Exception as e:
print(f'Error: {e}')
time.sleep(5)
return
div(x, y)
else:
print('Error. Enter a valid input!')
cal()