Write 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: calculator in python
from replit import clear
def add(n1, n2):
return n1 + n2
def subtract(n1, n2):
return n1 - n2
def multiply(n1, n2):
return n1 * n2
def divide(n1, n2):
return n1 / n2
operations = {
"+": add,
"-": subtract,
"*": multiply,
"/": divide
}
def calculator():
print(logo)
num1 = float(input("What's the first number?: "))
for symbol in operations:
print(symbol)
should_continue = True
while should_continue:
operation_symbol = input("Pick an operation: ")
num2 = float(input("What's the next number?: "))
calculation_function = operations[operation_symbol]
answer = calculation_function(num1, num2)
print(f"{num1} {operation_symbol} {num2} = {answer}")
if input(f"Type 'y' to continue calculating with {answer}, or type 'n' to start a new calculation: ") == 'y':
num1 = answer
else:
should_continue = False
clear()
calculator()
calculator()