Skip to main content

Python Order of Arithmetic Operations

Note: This article is for my reference.

Python adheres to the rules of arithmetic order of operations. For instance, when we encounter 1 + 2 * 3 + 4, Python will first multiply 2 by 3 and subsequently carry out the addition operations, as demonstrated in the example below:

# Order of arithmetic operations
print(1 + 2 * 3 + 4)

# Output
11

Operator precedence

OperatorPrecedence
Parenthesis( )
Unarynegative (-), logical NOT (!)
Multiplication*, / ,%
Additive+, -
Relational<, >, <=, >=
Equality==, !=
Logical AND&&
Logical OR||

It's considered good practice to utilise parentheses ( ) to specify to Python which operation should be performed first. The operations within the parentheses will take precedence over all other operations.

# Use parentheses to determine the order of computation
print((1 + 2) * (3 + 4))

Post Tags: