Python 制作一个简单的计算器程序

Python 制作一个简单的计算器程序

在Python中,我们可以创建一个简单的计算器来执行不同的算术运算,如加法、减法、乘法和除法。

方法:

  • 我们可以从选项a、b、c和d中选择所需的操作。
  • 我们可以输入两个数,如果…elif…else用于执行特定的操作。
  • 我们将使用add()、subtract()、multiply()和divide()函数来计算计算器中的相应操作。

示例:

Please select operation -
a. Add
b. Subtract
c. Multiply
d. Divide
Select operations form a, b, c, d: "c"  
Please enter first number: 11
Please enter second number: 4
11 * 4 = 44

代码:用于简单计算器

def add(P, Q):  
   # This function is used for adding two numbers 
   return P + Q 
def subtract(P, Q): 
   # This function is used for subtracting two numbers 
   return P - Q 
def multiply(P, Q): 
   # This function is used for multiplying two numbers 
   return P * Q 
def divide(P, Q): 
   # This function is used for dividing two numbers  
   return P / Q  
# Now we will take inputs from the user  
print ("Please select the operation.")  
print ("a. Add")  
print ("b. Subtract")  
print ("c. Multiply")  
print ("d. Divide")  

choice = input("Please enter choice (a/ b/ c/ d): ")  

num_1 = int (input ("Please enter the first number: "))  
num_2 = int (input ("Please enter the second number: "))  

if choice == 'a':  
   print (num_1, " + ", num_2, " = ", add(num_1, num_2))  

elif choice == 'b':  
   print (num_1, " - ", num_2, " = ", subtract(num_1, num_2))  

elif choice == 'c':  
   print (num1, " * ", num2, " = ", multiply(num1, num2))  
elif choice == 'd':  
   print (num_1, " / ", num_2, " = ", divide(num_1, num_2))  
else:  
   print ("This is an invalid input")  

输出:

情况 – (1):

Please select the operation.
a. Add
b. Subtract
c. Multiply
d. Divide
Please enter choice (a/ b/ c/ d):  d
Please enter the first number:  1
Please enter the second number:  2
1 / 2 = 0.5

案例 – (2):

Please select the operation.
a. Add
b. Subtract
c. Multiply
d. Divide
Please enter choice (a/ b/ c/ d): b
Please enter the first number:  12
Please enter the second number:  11
12 - 11 = 1

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程