Procedence and Associativity of Operators

 

Procedence and Associativity of Operators


Operator Precedence

 

This is used in an expression with more than one operator with different precedence to determine which operation to perform first. Some operator has higher precedence and some has lower precedence. So, if not properly grouped using brackets there may be mistakes in expected output.

 

#Example of Operator Precedence

 

#Precedence of ‘+’ & ‘*’ * has higher precedence than ‘+’

 

V=10+20*30

print(v)

 

#precedence of ‘or’ & ‘and’ and has greater precedence than or so and is executed first

 

name=”Kumar”

age=0

if name==”kumar” or name==”Ravi” and age>=2:

          print(“Hello! Welcome.”)

else:

          print(“Good Bye!!”)

 

Output

 

610

Hello! Welcome.

 

Operator Associativity

 

If an expression contains two or more operators with the same precedence then Operator Associativity is used to determine which is to performed first and next. 

 

Few Example of Operator Associativity

 

#Left-right Associativity

#100/10*10 is calculated as

#(100/10)*10 and not

#as 100/(10*10)

print(100/10*10)

 

Output: 100.0

 

#Left-right associativity

#5-2+3 is calculated as

#(5-2)+3 and not

#as 5-(2+3)

print(5-2+3)

 

Output

6

 

#Left-right associativity

print(5-(2+3))

 

Output

0

 

#Right-left Associativity

#2**3**2 is calculated as

#2**(3**2) and not

#as (2**3)**2

print(2**3**2)

 

Output

512

 

Non associative operators

 

For example, x<y<z neither means (x<y)<z nor x<(y<z. x<y<z is equivalent to x<y and y<z, and is evaluated from left-to-right.

 

Further , while chaining of assignments like x=y=z=1 is perfectly valid, x=y=z+=2 will result in error, you cannot club other Assignment Operators in  Chaining Assignments.

 

Ternary Operators

 

Ternary operators are also known as Conditional expressions or operators that evaluate something based on a condition being true of false. It was added to Python only from version 2.5.

 

It simply allows testing a condition in a single line replacing the multiline if-else making the code compact.

 

Syntax

[on_true] if [expression] else [on_false]

 

Simple Method to use ternary Operator:

 

#Program to demonstrate conditional operator

a,b=10,20

 

#Copy value of a in min if a<b else copy b

min=a if a<b else b

print(min)

 

Output

10

 

Direct Method by using Tuples, Dictionary, and Lambda

 

Tuple type

Syntax:

(if_test_false,if_test_true)[test]

#Python program to demonstrate ternary operator

a,b=10,20

#Use tuple for selecting an item

#if [a<b] is true it returns 1 , so element with 1 index will print

#else if[a<b] is false it returns 0,so element with 0 index will print print((b,a)[a<b])

#Use Dictionary for selecting an item

#if [a<b] is true then value of True key will print

#else if[a<b] is false then value of False key  will print print({True:a,False:b}[a<b])

 

#lambda is more efficient than above two methods

#because in lambda we are assure that

#Only one expression will be evaluated unlike in Tuple or Dictionary

print((lambda:b,lambda:a)[a<b]())

Output:

10

10

10

 

Ternary operator can be used as nested if-else also:

#Python program to demonstrate nested ternary operator

a,b=10,20

print(“Both a and b are equal ” if a==b else “a is greater than b” if a>b else “b is greater than a”)

 

This can be also written as

#Python program to demonstrate nested ternary operator

a,b=10,20

if a!=b:

    if a>b:

        print(“a is greater than b”)

    else     :

        print(“b is greater than a”)

else:

        print(“ Both a and b are equal”)

 

Output:

b is greater than a

 

To use print function in Ternary  operator be like

Example: Find the Larger number among 2 using ternary operator in python3

 

a=5

b=7

# [statement_on_True]if[condition] else [statement_on_false]

print(a,”is greater”) if (a>b) else print(b,”is Greater”)

 

Output

7 is Greater

 

Important Points:

 

F      First the given condition is evaluated (a<b), then either a or b is returned based on the Boolean value returned by the condition.

F      Order of the arguments in the operator is different from other languages like C/C++ .

F      Conditional expressions have the lowest priority amongst all Python operations.

 

Method used prior to 2.5 when the ternary operator was not present

 

In an expression like the one given below, the interpreter checks the expression , if this returns true then on_true is evaluated, else the on_false is evaluated.

 

Syntax

“’When condition becomes true ,expression [on_false] is not executed and value of “True and [on_true]” is returned. Else value of “False or [on_false]” is returned.

 

Note that “True and x” is equal to x.

And “False or x” is equal to x.”’

 

[expression] and [on_true] or [on_false]

 

Example:

#Program to demonstrate conditional operator

a,b=10,20

#If a is less than b, then a is assigned

#else b is assigned (Note: it doesn’t work if a is 0).

min=a<b and a or b

print(min)

 

Output : 10

 

Note:

The only drawback of this method is that on_true must not be zero or False. If this happens on_false will be evaluated always. The reason for that is if the expression is true, the interpreter will check for on_false to give the final result of the whole expression.

No comments:

Post a Comment