Python Simple Calculator Implementation
The following code implements a simple calculator with basic addition, subtraction, multiplication, and division of two numbers:
Example (Python 3.0+)
Filename : test.py
author by : www.runoob.com
Defining a function
def
add
(
x
,
y
)
:
"""
Sum
"""
return
x
y
def
subtract
(
x
,
y
)
:
"""
Subtract
"""
return
x
y
def
multiply
(
x
,
y
)
:
"""
Multiply
"""
return
x
y
def
divide
(
x
,
y
)
:
"""
Divide
"""
return
x
/
y
User input
(
"
Choose an operation:
"
)
(
"
1. Add
"
)
(
"
2. Subtract
"
)
(
"
3. Multiply
"
)
(
"
4. Divide
"
)
choice
=
input
(
"
Enter your choice (1/2/3/4):
"
)
num1
=
int
(
input
(
"
Enter the first number:
"
)
)
num2
=
int
(
input
(
"
Enter the second number:
"
)
)
if
choice
==
'
1
'
:
(
num1
,
"
"
,
num2
,
"
=
"
,
add
(
num1
,
num2
)
)
elif
choice
==
'
2
'
:
(
num1
,
"
"
,
num2
,
"
=
"
,
subtract
(
num1
,
num2
)
)
elif
choice
==
'
3
'
:
(
num1
,
"
"
,
num2
,
"
=
"
,
multiply
(
num1
,
num2
)
)
elif
choice
==
'
4
'
:
(
num1
,
"
/
"
,
num2
,
"
=
"
,
divide
(
num1
,
num2
)
)
else
:
(
"
Invalid input
"
)
The output of the code above is:
Selection operation:
1、相加
2、相减
3、相乘
4、相除
输入你的选择(1/2/3/4):2
输入第一个数字: 5
输入第二个数字: 2
5 - 2 = 3
Another implementation:
Example
Simple calculator program
Define a function to perform addition
def
add
(
x
,
y
)
:
return
x + y
Define a function to perform subtraction
def
subtract
(
x
,
y
)
:
return
x - y
Define a function to perform multiplication
def
multiply
(
x
,
y
)
:
return
x * y
Define a function to perform division
def
divide
(
x
,
y
)
:
if
y
!=
0
:
return
x / y
else
:
return
"Divisor cannot be zero"
Main program loop
while
True
:
(
"\nChoose an operation:"
)
(
"1. Addition"
)
(
"2. Subtraction"
)
(
"3. Multiplication"
)
(
"4. Division"
)
(
"5. Exit"
)
choice
=
input
(
"Enter the option number: "
)
if
choice
in
(
'1'
,
'2'
,
'3'
,
'4'
)
:
num1
=
float
(
input
(
"Enter the first number: "
)
)
num2
=
float
(
input
(
"Enter the second number: "
)
)
if
choice
==
'1'
:
(
f
"Result: {add(num1, num2)}"
)
elif
choice
==
'2'
:
(
f
"Result: {subtract(num1, num2)}"
)
elif
choice
==
'3'
:
(
f
"Result: {multiply(num1, num2)}"
)
elif
choice
==
'4'
:
(
f
"Result: {divide(num1, num2)}"
)
elif
choice
==
'5'
:
(
"Exiting the program."
)
break
else
:
(
"Invalid option, please try again."
)
Python3 Examples