6.Operator Precedence and Expression Evaluation

Operators Precedence

Operator precedence in Python determines the order in which operations are performed when an expression contains multiple operators. Operators with higher precedence are evaluated before operators with lower precedence. When operators have the same precedence, their associativity determines the order of evaluation.

The precedence rule learned in algebra is applied during the evaluation of arithmetic expression in Python.

  • Exponentiation has the highest precedence and is evaluated first.
  • Unary negation is evaluated next before multiplication and division
  • Multiplication, division and mod operators are evaluated before addition and subtraction
  • Addition and subtraction are evaluated before assignment
  • Operations of equal precedence are left associative, so they are evaluated from left to right.Exponentiation and assignment operations are right associative, so consecutive instances of these are evaluated from right to left
  • We can use parentheses to change the order of evaluation
Parentheses have the highest precedence and can be used to force the evaluation order.

The following table lists all operators from highest precedence to the lowest.

Sr.No.

Operator & Description

1

**

Exponentiation (raise to the power)

2

~ + -

Complement, unary plus and minus

3

* / % //

Multiply, divide, modulo and floor division

4

+ -

Addition and subtraction

5

>>    <<

Right and left bitwise shift

6

&

Bitwise 'AND'

7

^ |

Bitwise exclusive `OR' and regular `OR'

8

<=   <   >    >=

Comparison operators


Arithmetic Expressions and Evaluation

When we have an expression consisting of several operators how does Python decide the order of operations? It is done based on precedence of operator. Higher precedence operator is worked on before lower precedence operator.

Operator associativity determines the order of evaluation when they are of same precedence and are not grouped by parenthesis. Parenthesis has high precedence.

An operator may be Left-associative or Right –associative. In left associative, the operator falling on left side will be evaluated first, while in right assosiative operator falling on right will be evaluated first.


Note: In python “=” and “**” are Right Associative.Other operators are left associative means they are evaluated from left to right.
Examples:
>>>2+3**2
11
here 3**2 will be evaluated first because it is having high precedence. So 2+9=11 will be the result.

>>>2**3**2
512
Here 3**2 will be evaluated first because the associativity is from right to left. So 2**9=512 will be the result.>>>-4**2 # here unary operator applied later
-16
>>4%0
This will produce division by zero exception
>>>2+3/2*4**2
18
Here the sub expression 4**2 will be evaluated first because ** having high precedence. So the expression becomes 2+3/2*16. Now we have two operators / and * having same precedence. The associativity is from left to right so division will be done first. The expression become 2 + 1 * 16 after integer division. Now we have two operators + and * .But * is having high precedence so multiplication will be done first followed by the addition and the final result become 18.
>>2*3//2+3/2
4.5

Expression

Evaluation

Value

5+3*2

5+6

11

(5+3)*2

8*2

16

6%2

0

0

2*3**2

2*9

18

-3**2

-(3**2)

-9

2**3**2

2**9

512

(2**3)**2

8**2

64

45/0

Error: cannot divide by 0

 

45%0

Error: cannot divide by 0

 


Try your own examples....

Mixed Mode Arithmetic and Type Conversion

In Python, mixed mode arithmetic refers to operations involving operands of different data types. When performing such operations, Python automatically converts the operands to a common data type before performing the operation. This process is known as type conversion.

Here's an example to illustrate mixed mode arithmetic and type conversion in Python:
# Mixed mode arithmetic example

# Integer and float operands
integer_operand = 5
float_operand = 2.5

# Addition of an integer and a float
result = integer_operand + float_operand

# Display the result and its data type
print("Result:", result)
print("Data type of the result:", type(result))

Output:
Result: 7.5
Data type of the result: <class 'float'>

In this example, we have an integer operand (integer_operand with a value of 5) and a float operand (float_operand with a value of 2.5). The operation being performed is addition (+). Even though the operands are of different types (integer and float), Python performs type conversion implicitly to a common data type (float in this case) before performing the addition.

As you can see, the result is a float (7.5) because Python converted the integer operand to a float before performing the addition. This automatic type conversion helps in handling mixed-type arithmetic operations without explicitly converting the operands.

Type Conversion:

Type conversion, also known as type casting, is the process of converting a variable from one data type to another. Python provides built-in functions for explicit type conversion, allowing you to convert variables from one type to another.

# Type conversion example
integer_value = 5
float_value = float(integer_value)

print(float_value)  # Output: 5.0

In this example, the float() function is used to explicitly convert the integer_value from an int to a float. The resulting value is 5.0. Similarly, you can use functions like int(), str(), etc., to convert variables to integer, string, etc., respectively.


Combining Mixed Mode Arithmetic and Type Conversion:

You may encounter scenarios where you need to mix different data types and perform explicit type conversion in the same operation.

# Combined example of mixed mode arithmetic and type conversion
integer_number = 10
float_number = 5.5

result = integer_number + int(float_number)

print(result)  # Output: 15

In this example, int(float_number) is used to convert the float_number to an integer before performing the addition. The result is 15, which is of type int.

Understanding mixed mode arithmetic and type conversion is crucial for writing robust and flexible code, especially when dealing with diverse data types in Python.

Summary

Understanding operator precedence helps in writing correct and efficient Python code. When in doubt, using parentheses can clarify the intended order of operations and improve code readability.

Comments

Popular posts from this blog

Python For Machine Learning - CST 283 - KTU Minor Notes- Dr Binu V P

46.Classes and Objects in Python- Accessors and mutators

KTU Python for machine learning Sample Question Paper and Answer Key Dec 2020