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 )
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.
math=40
english=50
avg=45
if math>=40 or english>=50 and avg>=50:
print("Passed")
else:
print("Failed")
Output is
Passed
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
Associativity
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