Python中的# 运算符
·
Python 运算符通常用于对值和变量执行操作。这些是用于逻辑和算术运算的标准符号。在本文中,我们将研究不同类型的 Python 运算符。
算术运算符
算术运算符用于执行数学运算,例如加法、减法、乘法和除法。

# Examples of Arithmetic Operator
a = 9
b = 4
# Addition of numbers
add = a + b
# Subtraction of numbers
sub = a - b
# Multiplication of number
mul = a * b
# Division(float) of number
div1 = a / b
# Division(floor) of number
div2 = a // b
# Modulo of both number
mod = a % b
# Power
p = a ** b
# print results
print(add)
print(sub)
print(mul)
print(div1)
print(div2)
print(mod)
print(p)
13
5
36
2.25
2
1
6561
位运算符
位运算符作用于位并执行逐位操作。这些用于对二进制数进行操作。

# Examples of Bitwise operators
a = 10
b = 4
# Print bitwise AND operation
"""
a = 00001010
b = 00000100
------------
00000000 = 0
"""
print(a & b)
# Print bitwise OR operation
"""
a = 00001010
b = 00000100
------------
00001110 = 14
"""
print(a | b)
# Print bitwise NOT operation
"""
a = 00001010 =10
~a = 11110101 = -11
or -10-1=-11
"""
print(~a)
# print bitwise XOR operation
"""
a= 00001010
b= 00000100
------------------
xor= 00001110 = 14
"""
print(a ^ b)
# print bitwise right shift operation
print(a >> 2) #00001010 >>2 => 00000101 => 00000010 =2
# print bitwise left shift operation
print(a << 2) #00001010 <<2 => 00010100 => 00101000 =40
0
14
-11
14
2
40
运算符优先级
到目前为止,您会遇到许多运算符,例如加法、乘法等。但是当您在一个表达式中有多个运算符时,您会怎么做?
这是我们使用运算符的优先级来获得正确结果的情况。

Python中的运算符优先级表:

Python 中的 PEMDAS 规则: 我们会在优先考虑运算符的同时了解数学中的 BODMAS 规则。我们在 Python 中有一个类似的规则,那就是 PEMDAS。在哪里,
-
P 表示括号
-
E 表示指数
-
M 表示乘法
-
D 表示除法
-
A 表示加法
-
S 表示减法
a = 20
b = 10
c = 15
d = 5
e = 0
e = (a + b) * c / d #( 30 * 15 ) / 5
print ("Value of (a + b) * c / d is ", e)
e = ((a + b) * c) / d # (30 * 15 ) / 5
print ("Value of ((a + b) * c) / d is ", e)
e = (a + b) * (c / d); # (30) * (15/5)
print ("Value of (a + b) * (c / d) is ", e)
e = a + (b * c) / d; # 20 + (150/5)
print ("Value of a + (b * c) / d is ", e)
Value of (a + b) * c / d is 90.0
Value of ((a + b) * c) / d is 90.0
Value of (a + b) * (c / d) is 90.0
Value of a + (b * c) / d is 50.0
更多推荐

所有评论(0)