Python Program for Simple Calculator

In this tutorial, we will discuss how to create a simple calculator that can perform basic arithmetic operations such as addition, subtraction, multiplication, and division using a Python program.

Related: Python Program for Temperature Converter

Program code for Simple Calculator in Python

# Simple Calculator in Python
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):
if y == 0:
return "Error! Division by zero."
return x / y

print("Select operation:")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

choice = input("Enter choice(1/2/3/4): ")

num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

if choice == '1':
print(f"{num1} + {num2} = {add(num1, num2)}")
elif choice == '2':
print(f"{num1} - {num2} = {subtract(num1, num2)}")
elif choice == '3':
print(f"{num1} * {num2} = {multiply(num1, num2)}")
elif choice == '4':
print(f"{num1} / {num2} = {divide(num1, num2)}")
else:
print("Invalid input")

Explanation

  1. Function Definitions: The program defines four functions: add, subtract, multiply, and divide to perform the respective arithmetic operations.
  2. Main Program: The program prompts the user to select an operation and enter two numbers. Based on the user’s choice, it performs the corresponding arithmetic operation and prints the result.

Output

Python Program for Simple Calculator

  • When you run the above program, it will prompt you to select an operation and enter two numbers.
  • After entering the numbers, it will perform the selected arithmetic operation and print the result.

Conclusion

  • In this tutorial, we learned how to create a simple calculator that can perform basic arithmetic operations using a Python program.
  • Understanding this concept is essential for solving various mathematical problems and enhancing your programming skills.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *