View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
python

Python Tutorials - Elevate You…

  • 199 Lessons
  • 33 Hours

Operator Precedence in Python

Updated on 21/01/202520,919 Views

In Python, operator precedence refers to the order in which operators are evaluated in an expression. This means certain operations are performed before others when no parentheses are used to define the order explicitly.

Understanding operator precedence in Python with examples is essential. The wrong evaluation order can lead to unexpected results in your code.

Fortunately, learning the precedence of arithmetic operators in Python will help you avoid these issues. You can use parentheses to control the order of operations, ensuring your calculations are accurate.

Keep reading and learn how to make your code more predictable and error-free. Let’s dive in!

“Enhance your Python skills further with our Data Science and Machine Learning courses from top universities — take the next step in your learning journey!”

What is Operator Precedence in Python?

Operator precedence in Python determines the order in which different operators are evaluated in an expression. For example, when you write an expression like 3 + 4 * 2, the multiplication (*) happens first, because it has higher precedence than addition (+).

In simple terms, operator precedence helps Python decide which operation to perform first when multiple operators are used in a single expression. This ensures your expressions are evaluated consistently and correctly.

If you don’t specify the order using parentheses, Python will follow the predefined rules of precedence, ensuring operations like multiplication, division, and subtraction happen before addition.

Precedence of Operators in Python

To help you understand operator precedence in Python with examples, here's a simple table showing the order in which Python evaluates operators.

The higher the operator is on the list, the higher its precedence.

Operator

Description

()

Parentheses (highest precedence)

+x, -x, ~x

Unary plus, Unary minus, Bitwise NOT

****, *

Exponentiation, Multiplication, Division

+, -

Addition, Subtraction

>>, <<

Bitwise right and left shift

&

Bitwise AND

^

Bitwise XOR

|

Bitwise OR

==, !=, >, <, >=, <=

Comparison operators

=, +=, -=, *=, /=

Assignment operators (lowest precedence)

Knowing this precedence of arithmetic operators in Python allows you to predict how your expressions will be evaluated.

If you want to override the default order, just use parentheses () to make the evaluation clear.

Python Operators Precedence Rule - PEMDAS

When dealing with operator precedence in Python with examples, it’s helpful to remember the PEMDAS rule. This acronym stands for Parentheses, Exponents, Multiplication and Division (from left to right), Addition and Subtraction (from left to right). This is the order Python follows when evaluating expressions.

Here’s how it works:

  1. Parentheses (): Anything inside parentheses is evaluated first, no matter what.
  2. **Exponents **: Then, exponentiation (**) happens next.
  3. Multiplication (*) and Division (/): After that, multiplication and division are evaluated from left to right.
  4. Addition (+) and Subtraction (-): Finally, addition and subtraction are performed from left to right.

For example, in the expression 2 + 3 * 4, Python first evaluates 3 * 4 (multiplication) and then adds 2 to the result, following the PEMDAS rule.

If you need to change the order, just use parentheses to make the logic explicit.

Also Read: List of Operators In SQL [With Examples]

Associativity Rule for Operator Precedence in Python

The Associativity Rule in Python determines the order in which operators of the same precedence level are evaluated.

There are two types of associativity:

  1. Left-to-Right (LTR) Associativity: Most operators in Python, such as addition, subtraction, multiplication, and comparison operators, follow left-to-right associativity. This means Python evaluates the leftmost operator first.For example, in the expression 5 - 3 - 2, Python evaluates it as (5 - 3) - 2, going from left to right.
  2. Right-to-Left (RTL) Associativity: Some operators, like exponentiation (**), have right-to-left associativity. This means Python evaluates the rightmost operator first.For example, in 2 ** 3 ** 2, Python evaluates it as 2 ** (3 ** 2), meaning it performs 3 ** 2 first, and then raises 2 to the result.

These concepts will help you write more accurate and reliable code.

Examples of Comparison Operators

In Python, comparison operators are used to compare two values. These operators return either True or False based on the comparison.

Understanding operator precedence in Python with examples is key, as comparison operators have their own precedence when used with other operators in expressions.

Let's go through the comparison operators in Python:

1. Equal to (==)

This operator checks if two values are equal.

Example:

x = 5 + 2 
y = 3 * 2 + 1 
result = x ==
print(result)

Output:

True

Here, x becomes 7 (5 + 2), and y also evaluates to 7 (3 * 2 + 1), so x == y returns True.

2. Not equal to (!=)

This operator checks if two values are not equal.

Example:

a = 10 - 3 
b = 5 * 2 
result = a !=
print(result)

Output:

False

Here, a is 7 (10 - 3), and b is also 10 (5 * 2), so a != b evaluates to False.

3. Greater than (>)

This operator checks if the value on the left is greater than the value on the right.

Example:

x = (3 + 2) * 2
y = 10
result = x > y
print(result)

Output:

True

Here, x becomes 10 ((3 + 2) * 2), and y is also 10. The comparison x > y returns False because they are equal, so it will evaluate as False.

4. Less than (<)

This operator checks if the value on the left is less than the value on the right.

Example:

x = 8 - 3 * 2
y = 6
result = x < y
print(result)

Output:

True

In this case, the multiplication happens first (3 * 2 = 6), so x becomes 2 (8 - 6). Since 2 is indeed less than 6, the result is True.

5. Greater than or equal to (>=)

This operator checks if the value on the left is greater than or equal to the value on the right.

Example:

a = 6 + 4 * 3
b = 18
result = a >= b
print(result)

Output:

True

The multiplication 4 * 3 = 12 happens first, so a becomes 18. Since a is equal to b, the result of a >= b is True.

6. Less than or equal to (<=)

This operator checks if the value on the left is less than or equal to the value on the right.

Example:

a = 15 / 3
b = 6 + 2
result = a <= b
print(result)

Output:

True

Here, a becomes 5.0 (15 / 3), and b becomes 8 (6 + 2). Since 5.0 is less than 8, the result is True.

Key Points to Remember

  • Comparison operators have a lower operator precedence than arithmetic operators, which means they are evaluated after operations like addition, subtraction, and multiplication.

However, if you use parentheses, you can control the evaluation order.

Practice these examples and learn how to control program flow by making decisions based on values.

“Start your coding journey with our complimentary Python courses designed just for you — dive into Python programming fundamentals, explore key Python libraries, and engage with practical case studies!”

Examples of Logical Operators

Logical operators in Python are used to combine conditional statements, allowing you to evaluate multiple conditions at once. These operators return True or False based on the conditions.

Here are the main logical operators in Python:

1. AND (and)

This operator returns True if both conditions are true.

Example:

x = 5
y = 10
result = (x > 3) and (y < 15)
print(result)

Output:

True

Both conditions (x > 3 and y < 15) are True, so the result is True.

2. OR (or)

This operator returns True if at least one condition is true.

Example:

x = 5
y = 20
result = (x > 10) or (y < 25)
print(result)

Output:

True

Since one condition (y < 25) is True, the result is True.

3. NOT (not)

This operator inverts the truth value of the condition. If the condition is True, it returns False and vice versa.

Example:

x = 5
result = not (x > 10)
print(result)

Output:

True

Since x > 10 is False, not inverts it to True.

Key Takeaways

  • AND returns True only if both conditions are true.
  • OR returns True if at least one condition is true.
  • NOT inverts the result of the condition.

Keep experimenting to strengthen your understanding!

Examples of Arithmetic Operators

Arithmetic operators in Python are used to perform mathematical operations on numbers. These operators allow you to perform basic calculations like addition, subtraction, multiplication, and more.

Let’s look at precedence of arithmetic operators in Python:

1. Addition (+)

Adds two numbers together.

Example:

x = 10
y = 5
result = x + y
print(result)

Output:

15

Here, 10 + 5 gives 15.

2. Subtraction (-)

Subtracts the right-hand number from the left-hand number.

Example:

x = 20
y = 8
result = x - y
print(result)

Output:

12

Subtracting 8 from 20 results in 12.

3. Multiplication (*)

Multiplies two numbers together.

Example:

x = 7
y = 6
result = x * y
print(result)

Output:

42

Multiplying 7 by 6 gives 42.

4. Division (/)

Divides the left-hand number by the right-hand number, always returning a float.

Example:

x = 15
y = 4
result = x / y
print(result)

Output:

3.75

Dividing 15 by 4 gives 3.75 (float result).

5. Modulus (%)

Returns the remainder of the division.

Example:

x = 17
y = 5
result = x % y
print(result)

Output:

2

17 % 5 gives a remainder of 2.

6. Exponentiation (**)

Raises the left-hand number to the power of the right-hand number.

Example:

x = 3
y = 2
result = x ** y
print(result)

Output:

9

3 ** 2 equals 9 (3 raised to the power of 2).

7. Floor Division (//)

Divides the left-hand number by the right-hand number and returns the largest integer less than or equal to the result.

Example:

x = 17
y = 3
result = x // y
print(result)

Output:

5

17 // 3 gives 5, which is the floor division result.

Key Takeaways

  • Addition, Subtraction, and Multiplication are straightforward calculations.
  • Division always returns a float, while floor division returns the largest integer less than or equal to the result.
  • Modulus gives the remainder of the division.
  • Exponentiation raises a number to a power.

Experiment with more complex expressions to deepen your knowledge!

Examples of Bitwise Operators

Bitwise operators in Python are used to manipulate individual bits of integer values. These operators work on the binary representations of numbers, allowing you to perform operations at the bit level.

Here are the key bitwise operators in Python:

1. AND (&)

Performs a bitwise AND operation. It returns 1 if both bits are 1; otherwise, it returns 0.

Example:

x = 10  # 1010 in binary
y = 4   # 0100 in binary
result = x & y
print(result)

Output:

0

Here, 1010 & 0100 gives 0000 in binary, which is 0 in decimal.

2. OR (|)

Performs a bitwise OR operation. It returns 1 if at least one bit is 1, otherwise, it returns 0.

Example:

x = 10  # 1010 in binary
y = 4   # 0100 in binary
result = x | y
print(result)

Output:

14

Here, 1010 | 0100 gives 1110 in binary, which is 14 in decimal.

3. XOR (^)

Performs a bitwise XOR (exclusive OR) operation. It returns 1 if the bits are different, otherwise returns 0.

Example:

x = 10  # 1010 in binary
y = 4   # 0100 in binary
result = x ^ y
print(result)

Output:

14

Here, 1010 ^ 0100 gives 1110 in binary, which is 14 in decimal.

4. NOT (~)

Performs a bitwise NOT operation, which inverts the bits. It flips 1 to 0 and 0 to 1.

Example:

x = 10  # 1010 in binaryresult = ~xprint(result)

Output:

-11

The bitwise NOT of 10 (which is 1010 in binary) inverts all the bits, resulting in -11 due to the way negative numbers are represented in Python.

5. Left Shift (<<)

Shifts the bits of a number to the left by a specified number of positions, effectively multiplying the number by 2 for each position shifted.

Example:

x = 5   # 0101 in binaryresult = x << 1print(result)

Output:

10

Shifting 5 (which is 0101 in binary) one position to the left gives 1010, which is 10 in decimal.

6. Right Shift (>>)

Shifts the bits of a number to the right by a specified number of positions, effectively dividing the number by 2 for each position shifted.

Example:

x = 10  # 1010 in binary
result = x >> 1
print(result)

Output:

5

Shifting 10 (which is 1010 in binary) one position to the right gives 0101, which is 5 in decimal.

Key Takeaways

  • AND returns 1 only when both bits are 1.
  • OR returns 1 if at least one bit is 1.
  • XOR returns 1 if the bits are different.
  • NOT inverts the bits, flipping 1 to 0 and vice versa.
  • Left and Right Shift operations shift the bits left or right, multiplying or dividing by 2 for each shift.

Keep practicing with these operators to get comfortable with bitwise manipulation!

Also Read: Comprehensive Guide to Binary Code: Basics, Uses, and Practical Examples

Examples of Assignment Operators

Assignment operators in Python are used to assign values to variables. These operators not only assign values but also perform arithmetic or bitwise operations in a shorthand way.

Here are the main assignment operators in Python:

1. Simple Assignment (=)

The = operator is used to assign a value to a variable.

Example:

x = 10
print(x)

Output:

10

Here, 10 is assigned to the variable x.

2. Add and Assign (+=)

This operator adds the right operand to the left operand and assigns the result to the left operand.

Example:

x = 5
x += 3
print(x)

Output:

8

Here, 3 is added to x, and the result is assigned back to x, so x becomes 8.

3. Subtract and Assign (-=)

This operator subtracts the right operand from the left operand and assigns the result to the left operand.

Example:

x = 10
x -= 4
print(x)

Output:

6

Here, 4 is subtracted from x, and the result is assigned back to x, so x becomes 6.

4. Multiply and Assign (*=)

This operator multiplies the left operand by the right operand and assigns the result to the left operand.

Example:

x = 6
x *= 2
print(x)

Output:

12

Here, x is multiplied by 2, and the result is assigned back to x, so x becomes 12.

5. Divide and Assign (/=)

This operator divides the left operand by the right operand and assigns the result to the left operand.

Example:

x = 10
x /= 2
print(x)

Output:

5.0

Here, 10 is divided by 2, and the result (5.0, since division always returns a float) is assigned to x.

6. Modulus and Assign (%=)

This operator takes the modulus of the left operand by the right operand and assigns the result to the left operand.

Example:

x = 10
x %= 3
print(x)

Output:

1

Here, the modulus of 10 by 3 is 1, and the result is assigned to x.

7. Exponentiate and Assign (**=)

This operator raises the left operand to the power of the right operand and assigns the result to the left operand.

Example:

x = 2
x **= 3
print(x)

Output:

8

Here, x is raised to the power of 3, so x becomes 8.

8. Floor Divide and Assign (//=)

This operator performs floor division (divides and rounds down) on the left operand by the right operand and assigns the result to the left operand.

Example:

x = 15
x //= 4
print(x)

Output:

3

Here, 15 // 4 gives 3 because floor division rounds down to the nearest integer.

Key Takeaways

  • Assignment Operators combine the assignment operation with other arithmetic operations, allowing for shorthand code.
  • You can use *+=, -=, =, /=, and others to update the value of variables without repeating the variable name.

Experiment with these operators in different scenarios to simplify your code and improve efficiency!

How upGrad can help you?

With upGrad, you can access global standard education facilities right here in India. upGrad also offers free Python courses that come with certificates, making them an excellent opportunity if you're interested in data science and machine learning.

By enrolling in upGrad's Python courses, you can benefit from the knowledge and expertise of some of the best educators from around the world. These instructors understand the diverse challenges that Python programmers face and can provide guidance to help you navigate them effectively.

So, reach out to an upGrad counselor today to learn more about how you can benefit from a Python course.

Here are some of the best data science and machine learning courses offered by upGrad, designed to meet your learning needs:

Similar Reads: Top Trending Blogs of Python

FAQ's

1. What is operator precedence in Python?

Operator precedence in Python determines the order in which operations are performed in an expression. Higher precedence operators are evaluated first.

2. How does Python handle operator precedence?

Python follows specific rules like PEMDAS (Parentheses, Exponents, Multiplication/Division, Addition/Subtraction) to handle operator precedence in Python with examples.

3. Can I change operator precedence in Python?

No, operator precedence is fixed in Python. However, you can use parentheses () to explicitly define the order of operations.

4. What happens if I don’t use parentheses in an expression?

Python will follow the default operator precedence in Python. Without parentheses, operations will follow the fixed precedence rules, which may lead to unexpected results.

5. Do logical operators have higher precedence than arithmetic operators?

No, logical operators have lower precedence than arithmetic operators. Arithmetic operators like +, -, *, / are evaluated before logical operators like and, or.

6. What is the precedence of comparison operators in Python?

Comparison operators (like ==, !=, >, <) have lower precedence than arithmetic operators but higher precedence than logical operators.

7. How do bitwise operators work in terms of precedence?

Bitwise operators (like &, |, ^, <<, >>) have lower precedence than arithmetic operators but higher than comparison and logical operators.

8. Can I mix arithmetic and logical operators in an expression?

Yes, but be mindful of operator precedence in Python. Arithmetic operations will be performed first unless parentheses are used to alter the order.

9. What is the difference between and and or in Python?

The and operator returns True only if both conditions are true, while the or operator returns True if at least one condition is true.

10. Does the order of operations matter in Python?

Yes, understanding operator precedence is essential in Python to ensure expressions are evaluated as intended. Parentheses can be used to control the order explicitly.

11. How do I check operator precedence in Python?

You can refer to Python’s official documentation or use a precedence table to check how different operators are evaluated in Python.

image

Take our Free Quiz on Python

Answer quick questions and assess your Python knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.