Operator Precedence
Operator precedence decides which operations Python carries out first, and in what order.
Example
Parentheses outrank everything else, so whatever sits inside them gets worked out first:
Prompt
Write a Python program that demonstrates parentheses having the highest precedence by printing the result of (6 + 3) - (6 + 3).
Output: complete Python program
main.py
print((6 + 3) - (6 + 3))
Example
Multiplication * ranks above addition +, so Python multiplies before it adds:
Prompt
Write a Python program that demonstrates multiplication having higher precedence than addition by printing the result of 100 + 5 * 3.
Output: complete Python program
main.py
print(100 + 5 * 3)
Precedence Order
The table below lists the order, with the highest-ranking operators first and the lowest at the bottom:
Precedence Order Table
main.py
# Operator | Description
# () | Parentheses
# ** | Exponentiation
# +x -x ~x | Unary plus, unary minus, and bitwise NOT
# * / // % | Multiplication, division, floor division, and modulus
# + - | Addition and subtraction
# << >> | Bitwise left and right shifts
# & | Bitwise AND
# ^ | Bitwise XOR
# | | Bitwise OR
# == != > >= < <= is is not in not in | Comparisons, identity, and membership operators
# not | Logical NOT
# and | AND
# or | OR
Left-to-Right Evaluation
Operators with equal precedence are generally worked through from left to right.
Example
Addition + and subtraction - rank equally, so this expression is worked out from left to right:
Prompt
Write a Python program that demonstrates left-to-right evaluation when operators have the same precedence by printing the result of 5 + 4 - 7 + 3.
Output: complete Python program
main.py
print(5 + 4 - 7 + 3)