Create simple calculator in python

In this example, you will learn to create a simple calculator in python with multiple methods with example.

Simple Calculator in Python using if-else Statements

This is the simplest and easiest way to make a simple calculator in python. We will take two numbers while declaring the variables and select operation (+, -, *, /). Then, find operations and results will be displayed on the screen using the if-else statement.

Example

    
# Python program to make a simple calculator

# taking user input
no1 = float(input("Enter first number: "))
no2 = float(input("Enter second number: "))

# choice operation
print("Operation: +, -, *, /")
select = input("Select operations: ")

# check operations and display result
if select == "+":
    print(no1, "+", no2, "=", no1+no2)

elif select == "-":
    print(no1, "-", no2, "=", no1-no2)

elif select == "*":
    print(no1, "*", no2, "=", no1*no2)

elif select == "/":
    print(no1, "/", no2, "=", no1/no2)

else:
    print("Invalid input")
       

Output :

    
Enter first number: 12.25
Enter second number: 4
Operation: +, -, *, /
Select operations: *
12.25 * 4.0 = 49.0
    

Explanation :

First of all, this program will ask user to input two numbers and ask for operation (+,-,*,/). Then it will calculate arithmetic operation based on user input using if else ladder technique.

Simple Calculator in Python using Functions

Example 2 : Using in-built methods

    
#Python program create simple calculator using functions
def add(x, y):
   return x + y
def subtract(x, y):
   return x - y
def multiply(x, y):
   return x * y
def divide(x, y):
   return x / y

#User input

no1 = float(input("Enter first number: "))
no2 = float(input("Enter second number: "))

print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
choice = input("Enter choice(1/2/3/4):")

if choice == '1':
   print(no1,"+",no2,"=", add(no1,no2))

elif choice == '2':
   print(no1,"-",no2,"=", subtract(no1,no2))

elif choice == '3':
   print(no1,"*",no2,"=", multiply(no1,no2))

elif choice == '4':
   print(no1,"/",no2,"=", divide(no1,no2))
else:
   print("Invalid input")
       

Output :

    
Enter first number: 12.5
Enter second number: 4
Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4):3
12.5 * 4.0 = 50.0
    

Explanations :

This example also ask user input and choice which is arithmetic operator but in-stand of calculating output directly it will pass both number to function based on choice and function will return answer. In this method you need to define function for every operation you want to perform.


Share your thoughts

Ask anything about this examples