How to check the priority of operators (+, -, *, /) in Python

Python provides us with different types of operators to work with. This answer will compare the priorities of four such operators +, -, *, /.

The operators * and / belong to a priority group. This means that they take priority over the + and - operator group.

Since we cannot compare them directly, we will assign them a priority and store them in a dictionary, in which keys are operators and values are operator priority.

Let's take a look at an example of this.

Example

#operators dictionary
operators = {
'+':1,
'-':1,
'*':2,
'/':2
}
#function to check priority
def check_priority(p1, p2):
return operators[p1] >= operators[p2]
print(check_priority("+","*"))
print(check_priority("*","-"))
print(check_priority("/","+"))

Explanation

In the code snippet above,

  • Lines 2–7: We declare and assign the dictionary operators, in which + and - belong to the same operator group. We assign these a priority value of 1. On the other hand, * and / belong to a higher priority, so we assign them a priority value 2.

  • Lines 10–11: We declare and define a function check_priority that accepts two operators as parameters and returns the boolean value.

  • Line 13: We check if the operator + has more priority than the operator *. This returns False.

  • Line 14: We check if the operator * has more priority than the operator -. This returns True.

  • Line 15: We check if the operator / has more priority than the operator +. This also returns True.

Free Resources

Copyright ©2026 Educative, Inc. All rights reserved