Wednesday, April 1, 2015

Operator Precedence in Python - Python Numbers - Python Tutorial

Operator Precedence in PythonOperator Precedence in Python


In this Python tutorial, we are going to look at operator precedence in Python. We will be focusing on the operators we have already learned like **, *, /, //, %, + and -. It is important to understand what operator will run first.


Operator Precedence


The list below will show which operator has more precedence over the operators.  So the first operator in the list will run before the second operator below.


  1. ** – Exponent

  2. *, /, %, // – Multiplication, true division, modulo, floor division.  In this case if these operators where in the same equation then the equation would run left to right.

  3. +, – Addition and Subtraction are the last operators to run.

Operator Precedence Examples


Let’s look at some examples and figure out which operator will run in the equation. The order in which the operators run could have some serious effects on your results.


Exponent and Multiplication


Exponent will always run before the multiplication equation. Take a look at the example.


#Exponent and Multiplication

#Exponent Runs First

>>> 2 ** 2 * 2
8

#If multiplication ran first this answer would be 16
>>> 2 * 2 ** 2
8

Exponent and Division


Exponent will always run before a division equation. Take a look at this example.


#Exponent and Division

#exponent runs first
>>> 4 / 2 ** 6
0.0625

#2 ** 6 is 64
>>> 4 / 64
0.0625

Multiplication and Division


In this scenario Python will run the equation from left to right since multiplication and division have the precedence. Take a look at the example below.


#Multiplication and Division

#In this case division is ran first then multiplied by 3
>>> 5 / 4 * 3
3.75

#In this case 3 is multiplied by 4 then divided by 5
>>> 3 * 4 / 5
2.4

Multiplication and Addition


Multiplication will run before an addition equation since multiplication has more precedence over addition. Here is an example.


#Multiplication and Addition

>>> 2 + 4 * 4
18

Addition and Subtraction


In this scenario the equation will run left to right since addition and subtraction are on the same level.


#Addition and Subtraction

>>> 2 + 3 - 5 + 8 - 4 + 2 - 9
-3

Conclusion


In this Python tutorial, we took a look at Operator Precedence in Python it is important to remember which operator will run first because you can end up with different values if you are not paying attention when setting up your equations. In the next Python tutorial, we will look at a way to manually change the order.



No comments:

Post a Comment