Friday, April 3, 2015

Manually Adjust The Operator Precedence - Python Numbers - Python Tutorial

Manually Adjust the Operator PrecedenceManually Adjust The Operator Precedence


In the previous Python tutorial, we took a look at how Python evaluates equations using the operator precedence. In this Python tutorial, we are going to throw out all the information you learned in the previous tutorial and show you how you can control the operator precedence with parentheses in your equations.


Python will evaluate parentheses first then default to the operator precedence. This gives us the ability to adjust how Python will run an equation and gives us more control over our mathematical equations in our programs.


The Operator Precedence


A little review how the operator precedence is evaluated in Python.


  1. **

  2. *, /, %, //

  3. +, -

In the default operator precedence exponent(**) will always run before any other operator.  Then multiplication(*), true division(/), modulo(%), and floor division(//) will run after the exponent(**).  Then finally addition(+) and subtraction(-) will run.


If an equation contains operators in the precedence like addition(+) and subtraction(-) then the equation will run left to right.


Manually Adjust The Operator Precedence


With Python we have the ability to manually adjust the operator precedence using parentheses which Python will run first then go to the default operator precedence after running the equation in the parentheses. This option gives us more control over our code and helps control flow of our math equations.


Manually Adjust The Operator Precedence Examples


#Manually Adjust The Operator Precedence Examples

#Default Operator Precedence Exponent first
>>> 2 ** 2 + 2
6

#Still runs exponent first
>>> 2 + 2 ** 2
6

#runs addition
>>> (2 + 2) ** 2
16

#runs left to right
>>> 3 * 8 / 2
12.0

#runs division first
>>> 3 * (8 / 2)
12.0

#runs division first
>>> 6 * (7 / 4)
10.5

#test the equation
>>> 7/4
1.75

#test the equation
>>> 1.75 * 6
10.5

#Python runs multiplication first
>>> 6 + 5 - 3 + 4 * 10
48

#Python runs addition and subtraction first
>>> (6 + 5 - 3 +4) * 10
120

Conclusion 


In this tutorial, we learned how to Manually Adjust the Operator Precedence which gives us more control over our code and gives the flexibility to write quality programs. It is important to know that Python will default to its operator precedence after running the parentheses.


If you have any questions leave a comment below and we will do our best to help you out.


 


 



No comments:

Post a Comment