English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python Basic Tutorial

Python Flow Control

Python Functions

Python Data Types

Python File Operations

Python Objects and Classes

Python Date and Time

Advanced Knowledge of Python

Python Reference Manual

Create a simple calculator using a Python program

Python example manual

In this example, you will learn to create a simple calculator that can add, subtract, multiply, or divide based on user input.

To understand this example, you should understand the followingPython programmingTopic:

Create a simple calculator through functions

# Program to create a simple calculator
# This function adds two numbers
def add(x, y):
   return x + y
# Subtract two numbers
def subtract(x, y):
   return x - y
# This function multiplies two numbers
def multiply(x, y):
   return x * y
# This function divides two numbers
def divide(x, y):
   return x / y
print("Select operation")
print("1.add")
print("2.subtract")
print("3.multiply")
print("4.divide")
# Accept user input
choice = input("Select (1/2/3/4):
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
if choice == '1':
   print(num1",+",num2,"=", add(num1,num2))
elif choice == '2':
   print(num1",-",num2,"=", subtract(num1,num2))
elif choice == '3':
   print(num1",*",num2,"=", multiply(num1,num2))
elif choice == '4':
   print(num1",/",num2,"=", divide(num1,num2))
else:
   print("Invalid input")

Output result

Select operation
1.add
2.subtract
3.multiply
4.divide
Select (1/2/3/4) 2
Enter the first number: 11
Enter the second number: 120
11.0 - 120.0 = -109.0

In this program, we ask the user to select the required operation. Option1、2、3and4Valid. Take two numbers and use an if...elif...else branch to execute specific parts. User-defined functions add(), subtract(), multiply(), and divide() perform different operations.

Python example manual