算术运算,如和、减、乘、除,是任何编程语言的一个组成部分。这些操作通常在整数或浮动值上执行,Python也不例外。在这个例子中,我们将看到如何在Python中进行数字减法,并看到其各种使用情况。
Python减法
要在Python中减去两个数字,使用减法(-)运算符。减法运算符(-)接收两个操作数,第一个操作数在左边,第二个操作数在右边,并返回第二个操作数与第一个操作数的差。
为了打印减法的输出,我们将使用print()函数:
语法
output = first_operand - second_operand
参数
第一操作数和第二操作数是数字。
返回值
输出值是第二操作数与第一操作数之差。
例子
first_operand = 19
second_operand = 21
output = second_operand - first_operand
print(output)
输出
2
这是一个简单的例子,说明如何在Python中做两个数字的减法。
在Python中用用户输入法减去两个数字
要从用户那里获得输入,可以使用Python中的input()函数。
first_operand = int(input("Enter the first_operand: "))
second_operand = int(input("Enter the second_operand: "))
output = second_operand - first_operand
print(output)
输出
Enter the first_operand: 18
Enter the second_operand: 19
1
使用链式减去多个操作数
到现在为止,我们已经使用了两个操作数并应用了减法。接下来,我们将使用两个以上的操作数,在一条语句中使用链式运算从一个数字中减去一个以上的数字。
要在两个以上的操作数中操作减法运算符,请使用减法运算符的链式。
first_operand = int(input("Enter the first_operand: "))
second_operand = int(input("Enter the second_operand: "))
third_operand = int(input("Enter the third_operand: "))
output = third_operand - second_operand - first_operand
print(output)
输出
Enter the first_operand: 11
Enter the second_operand: 19
Enter the third_operand: 46
16
如何在Python中减去两个浮点数
要在Python中减去两个浮点数,请使用减法运算符(-)。Float是Python中最常用的数字数据类型之一。
first_operand = float(input("Enter the first_operand: "))
second_operand = float(input("Enter the second_operand: "))
third_operand = float(input("Enter the third_operand: "))
output = third_operand - second_operand - first_operand
print(output)
输出
Enter the first_operand: 11.9
Enter the second_operand: 22.9
Enter the third_operand: 44.9
10.1
如何在Python中减去复数
要在Python中减去复数,使用减去(-)运算符。
first_operand = 11 + 2j
second_operand = 22 + 3j
third_operand = 44 + 4j
output = third_operand - second_operand - first_operand
print(output)
输出
(11 - 1j)
本教程到此结束。