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 dictionaryoperators = {'+':1,'-':1,'*':2,'/':2}#function to check prioritydef 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 of1. On the other hand,*and/belong to a higher priority, so we assign them a priority value2.Lines 10–11: We declare and define a function
check_prioritythat accepts two operators as parameters and returns the boolean value.Line 13: We check if the operator
+has more priority than the operator*. This returnsFalse.Line 14: We check if the operator
*has more priority than the operator-. This returnsTrue.Line 15: We check if the operator
/has more priority than the operator+. This also returnsTrue.
Free Resources