Python-operators-precedence-example
提供:Dev Guides
Python演算子の優先順位の例
次の表に、優先順位の高いものから低いものまで、すべての演算子を示します。
Operator | Description |
---|---|
** | Exponentiation (raise to the power) |
~ + - | Complement, unary plus and minus (method names for the last two are +@ and -@) |
*/%// | Multiply, divide, modulo and floor division |
+ - | Addition and subtraction |
>> << | Right and left bitwise shift |
& | Bitwise 'AND’td> |
^ | |
Bitwise exclusive `OR' and regular `OR' | ⇐ < > >= |
Comparison operators | <> == != |
Equality operators | = %=/=//= -= +=* = **= |
Assignment operators | is is not |
Identity operators | in not in |
Membership operators | not or and |
演算子の優先順位は、式の評価方法に影響します。
たとえば、x = 7 + 3 * 2;ここでは、演算子*の優先順位が+より高いため、xには20ではなく13が割り当てられます。したがって、最初に3 *2を乗算してから7に加算します。
ここでは、優先順位が最も高い演算子が表の上部に表示され、優先順位が最も低い演算子が下部に表示されます。
例
#!/usr/bin/python
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
Value of ((a + b)* c)/d is 90
Value of (a + b) *(c/d) is 90
Value of a + (b* c)/d is 50