basic calculator 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
num_one = int(input("Enter 1st number: "))
op = input("Enter operator: ")
num_two = int(input("Enter 2nd number: "))
if op == "+":
print(num_one + num_two)
elif op == "-":
print(num_one - num_two)
elif op == "*" or op == "x":
print(num_one * num_two)
elif op == "/":
print(num_one / num_two)
Example 3: 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()
Example 4: calculator in python
qus = input('')
if(qus=='ADDITON'):
no1 = int(input())
no2 = int(input())
print(no1+no2)
if(qus=='MULTIPLICATION'):
no1 = int(input())
no2 = int(input())
print(no1*no2)
if(qus=='DIVISION'):
no1 = int(input())
no2 = int(input())
print(no1/no2)
if(qus=='SUBTRACTION'):
no1 = int(input())
no2 = int(input())
print(no1-no2)