Python Precedence of Operators

print(4+2*3)   # Output 10 
print(4+(2*3)) # Output 10
print((4+2)*3) # Output 18
In the first line the output is 10 ( not 18 ) as multiplication is first done and then the addition is performed. In next two lines the operation within the Parentheses is executed first. This action is done based on the precedence to be followed while performing actions using operators.

This is in the order of decreasing precedence.
Operator Details
( )Parentheses ( By grouping the expressions the precedence can change )
+x, -x, ~xPositive, negative, bitwise NOT
*, @, /, //, %Multiplication, matrix multiplication, division, floor division, remainder
+,- Addition and subtraction
<<, >> Shifts
&Bitwise AND
^ Bitwise XOR
| Bitwise OR
in, not in, is, is not, <, <=, >, >=, !=, == Comparisons, including membership tests and identity tests
not x Boolean NOT
and Boolean AND
or Boolean OR
if – else Conditional Expression
lambda Lambda expression
:= Assignment expression
MD : multiplication and division have the same precedence.
AS : Addition, Subtraction have the same precedence.

PEMDAS isn't about order of operations, it doesn't decide what order things are evaluated in. It's really about argument grouping.
PEMDAS says that x+y+z*a is same as (x+y)+(z*a).

and or

Precedence of and is higher than or. Here to pass the exam, student has to score average of more than or equal to 50. In this case average is less than 50 but the output is Pass as and is having higher precedence than or.
if math>=40 or english>=50 and avg>=50:
Output is
Due to the higher Precedence of and following grouping is done.
if math>40 or (english > = 50 and avg > 50) 
The actual grouping should be like this to get correct result.
(if math>40 or english > = 50) and avg > 50 


When two operators have same associativity, the execution is done from left to right.
print(10/2*6) # output is 30.0
print(24/6//2)# output is 2.0 
Operators All Built in Functions in Python dir() ord()

Post your comments , suggestion , error , requirements etc here

Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2021 All rights reserved worldwide Privacy Policy Disclaimer