How to Implement a Simple Calculator Using Python
How to Implement a Simple Calculator in Python
In our daily lives, we often need to perform various mathematical operations, such as addition, subtraction, multiplication, and division. A calculator is one of the tools that helps us perform these operations quickly. In this article, I will show you how to implement a simple calculator in Python, allowing you to easily perform basic mathematical operations.
Design Idea
Our calculator will have the following functions:
- Addition
- Subtraction
- Multiplication
- Division
- Exponentiation
- Square Root
To implement the above functions, we will design a Calculator class that contains methods for these operations. Users can perform calculations by entering the corresponding operators and numbers.
Code Implementation
The following is an example of Python code implementing calculator functionality:
import math
class Calculator:
def add(self, x, y):
return x + y
def subtract(self, x, y):
return x - y
def multiply(self, x, y):
return x * y
def divide(self, x, y):
if y == 0:
return "Error: division by zero!"
else:
return x / y
def power(self, x, y):
return x ** y
def square_root(self, x):
return math.sqrt(x)
# Instantiate the Calculator class
calc = Calculator()
# Addition example
print("1 + 2 =", calc.add(1, 2))
# Subtraction Example
print("5 - 3 =", calc.subtract(5, 3))
# Multiplication Example
print("4 * 6 =", calc.multiply(4, 6))
# Division Example
print("9 / 3 =", calc.divide(9, 3))
# Exponentiation Example
print("2 ^ 4 =", calc.power(2, 4))
# Square Root Example
print("Square root of 16 is", calc.square_root(16))
Running Results
Running the above code will output the following:
1 + 2 = 3
5 - 3 = 2
4 * 6 = 24
9 / 3 = 3.0
2 ^ 4 = 16
Square root of 16 is 4.0
The above code implements a simple calculator, including addition, subtraction, multiplication, division, exponentiation, and square root functions. Users can enter different numbers and operators to perform corresponding mathematical operations as needed. Although this calculator is simple, it is sufficient for most daily calculation needs.