在本教程中,我们将学习Python中的基本运算符。
算术运算符在执行数学运算(例如加法,减法,乘法等)时非常有用,
加法-----加两个数字----- +
减法-----将一个数减去另一个------
乘法-----将两个数字相乘----- *
除法-----用一个数字除以另一个----- /
楼层分割------除法后返回整数----- //
模量-----它给出余数-----%
让我们看看例子。
# initialising two numbers a = 5 b = 2 # addition print(f'Addition: {a + b}') # substraction print(f'Substraction: {a - b}') # multiplication print(f'Multiplication: {a * b}') # division print(f'Division: {a / b}') # floor division print(f'Floor Division: {a // b}') # modulus print(f'Modulus: {a % b}')
如果运行上面的程序,您将得到以下结果。
Addition: 7 Substraction: 3 Multiplication: 10 Division: 2.5 Floor Division: 2 Modulus: 1
关系运算符将结果返回True或False。这些运算符用于比较Python中相同类型的对象。让我们看一下关系运算符的列表。
大于-----> -----检查数字是否大于其他数字
大于或等于-----> = -----检查数字是否大于或等于其他
小于----- <-----检查数字是否小于其他
小于或等于----- <= -----检查数字是否小于或等于其他
等于----- == -----检查数字是否与其他数字相似
不等于-----!= -----检查数字是否与其他数字不相似
让我们看看例子。
# initialising two numbers a = 5 b = 2 # greater than print(f'Greater than: {a > b}') # greater than or equal to print(f'Greater than or equal to: {a >= b}') # less than print(f'Less than: {a < b}') # less than or equal to print(f'Less than or qual to: {a <= b}') # equal to print(f'Equal to: {a == b}') # not equal to print(f'Not equal to: {a != b}')
如果运行上面的代码,您将得到以下结果。
Greater than: True Greater than or equal to: True Less than: False Less than or qual to: False Equal to: False Not equal to: True
逻辑运算符用于执行逻辑运算,如和,或,和not。
和-----如果两者均为True,则为True
或-----如果两者均为False,则为False
不是-----反转操作数
让我们看看例子。
# initialising variables a = True b = False # and print(f'and: {a and b}') # or print(f'or: {a or b}') # not print(f'not: {not a}') print(f'not: {not b}')
如果运行上面的代码,您将得到以下结果。
and: False or: True not: False not: True
按位运算符用于执行按位运算符,如和,或,和not。
&-----如果两者都为真,则为真
| -----如果两者均为假则为False
〜-----反转操作数
让我们看看例子。
# initialising numbers a = 5 b = 2 # bitwise and print(f'Bitwise and: {a & b}') # bitwise or print(f'Bitwise or: {a | b}') # bitwise not print(f'Bitwise not: {~a}') # bitwise not print(f'Bitwise not: {~b}')
如果运行上面的程序,您将得到以下结果。
Bitwise and: 0 Bitwise or: 7 Bitwise not: -6 Bitwise not: -3
赋值运算符用于为变量赋值。我们有以下赋值运算符。
= -----给变量分配一个数字
+ = -----添加数字并分配给变量
-= -----减去一个数字并分配给变量
* = -----乘以数字并分配给变量
/ = -----除以数字并分配给变量
// = -----除(底除)一个数字并分配给变量
%= -----模数一个数字并分配给变量\
让我们看看例子。
# = a = 5 print(f'=:- {a}') # += a += 1 # a = a + 1 print(f'+=:- {a}') # -= a -= 1 # a = a - 1 print(f'-=:- {a}') # *= a *= 2 # a = a * 1 print(f'*=:- {a}') # /= a /= 2 # a = a / 1 print(f'/=:- {a}') # //= a //= 2 # a = a // 1 print(f'//=:- {a}') # %= a %= 10 # a = a % 1 print(f'%=:- {a}')
如果运行上面的程序,您将得到以下结果。
=:- 5 +=:- 6 -=:- 5 *=:- 10 /=:- 5.0 //=:-2.0- %=:-2.0-