Python 执行算术操作程序

Python 执行算术操作程序

算术操作是由计算器执行的,我们可以进行加法、减法、乘法和除法。这个示例展示了基本的算术操作,即:

  • 加法
  • 减法
  • 乘法
  • 除法

让我们理解以下示例。

示例

# Simple Python program to understand the arithmetical operator addition
# Here, we are storing the first input numbers in num1  
num1 = input('Enter first number: ')  
# Here, we are storing the second input numbers in num2
num2 = input('Enter second number: ')  
# Here, we are declaring a variable sum to store the result
# Here, we are using the arithmetical operator to add the two numbers  
sum = float(num1) + float(num2)  
# Here, we are printing the sum of the given two numbers 
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))    

输出:

Enter first number: 10
Enter second number: 20
The sum of 10 and 20 is 30.0    

解释 –

在上述代码中,我们使用input()函数将用户输入作为整数进行了获取。然后,我们对给定的数字进行了算术运算,并使用print语句打印结果。我们使用了format()方法来格式化字符串。

示例1:

# Simple Python program to understand the arithmetical operator subtraction
# Here, we are storing the first input numbers in num1  
num1 = input('Enter first number: ')  
# Here, we are storing the second input numbers in num2
num2 = input('Enter second number: ')  
# Here, we are declaring a variable min to store the result
# Here, we are using the arithmetical operator to subtract the two numbers  
min = float(num1) - float(num2)  
# Here, we are printing the subtraction of the given two numbers 
print('The subtraction of {0} and {1} is {2}'.format(num1, num2, min))    

输出:

Enter first number: 10
Enter second number: 20
The subtraction of 10 and 20 is -10

例2:

# Simple Python program to understand the arithmetical operator muitiplication
# Here, we are storing the first input numbers in num1  
num1 = input('Enter first number: ')  
# Here, we are storing the second input numbers in num2
num2 = input('Enter second number: ')  
# Here, we are declaring a variable mul to store the result
# Here, we are using the arithmetical operator to multiply the two numbers  
Mul = float(num1) * float(num2)  
# Here, we are printing the multiplication of the given two numbers 
print('The multiplication of {0} and {1} is {2}'.format(num1, num2, mul))    

输出:

Enter first number: 10
Enter second number: 20
The multiplication of 10 and 20 is 200

示例3:

# Simple Python program to understand the arithmetical operator division
# Here, we are storing the first input numbers in num1  
num1 = input('Enter first number: ')  
# Here, we are storing the second input numbers in num2
num2 = input('Enter second number: ')  
# Here, we are declaring a variable div to store the result
# Here, we are using the arithmetical operator to divide the two numbers  
div = float(num1) - float(num2)  
# Here, we are printing the division of the given two numbers 
print('The division of {0} and {1} is {2}'.format(num1, num2, min))    

输出:

Enter first number: 10
Enter second number: 20
The division of 10 and 20 is 0.5

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程