0% found this document useful (0 votes)
3 views

Operators

The document provides a comprehensive overview of operators in Python, categorizing them into arithmetic, comparison, assignment, logical, bitwise, membership, and identity operators. It explains operator precedence and expression evaluation, emphasizing the importance of understanding these concepts for effective coding. Additionally, it covers mixed mode arithmetic and type conversion, illustrating how Python handles operations involving different data types.

Uploaded by

Remya Gopinadh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Operators

The document provides a comprehensive overview of operators in Python, categorizing them into arithmetic, comparison, assignment, logical, bitwise, membership, and identity operators. It explains operator precedence and expression evaluation, emphasizing the importance of understanding these concepts for effective coding. Additionally, it covers mixed mode arithmetic and type conversion, illustrating how Python handles operations involving different data types.

Uploaded by

Remya Gopinadh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Operators

June 10, 2024

Operators are special symbols which represents computation. They are applied on operand(s), which
can be values(constants) or variables. Same operator can behave differently on different data types.
Operators when applied on operands form an expression Operators are categorised as

Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bit wise Operators
Membership Operators
Identity Operators

Arithmetic Operators( Mathematical)

Symbol Description Example 1 Example 2

+ Addition 55+45 “Good” + “Morning”


100 GoodMorning

55-45 30-80
10 -50
- Subtraction

55*45 “Good” * 3
GoodGoodGood
* Multiplication

17/5 17.0/5
3 3.4
/ Division
17/5.0 28/3
3.4 9

Remainder/ 17%5 23%2


2 1
% Modulo

2**3 2**8
8 256
** Exponentiation
16**0.5
4.0

Integer/floor 7.0//2 -5/ / 2


3.0 -3
// Division

Comparison (Relational) Operators


These operators compare the values on either side of them and decide the relation among them.

They are also called Relational operators.

Symbol Description Example 1 Example 2

< Less than 7<10 Goodbye' < 'Hello'


True True

> Greater than 7>5 'Goodbye' > 'Hello'


True False

<= less than equal to 2<=5 "Hello" <= “Goodbye”


True False

>= greater than equal 10>=10 "Hello" >= “Goodbye”


to True True

!= not equal to 10!=11 ‟Hello”!= “HELLO"


True True

== equal to 10==10 "Hello" == “Hello”


True True

Note: two values that are of different data type will never be equal to each other.

Assignment Operators
Assignment Operator combines the effect of arithmetic and assignment operator

Symbol Description Example Explanation

Assigned values from x=12 x=12


right side y="greetings"
= ( we will assume x=12 for
operands to left
all examples)
variable

added and assign back x+=2 x=x+2


the result x=14
+=
to left operand

subtracted and assign x-=2 x will become 10


back the
-=
result to left operand

multiplied and assign x*=2 x will become 24


back the
*=
result to left operand
divided and assign back x/=2 x will become 6
the
/=
result to left operand

taken modulus using


two
x%=2 x will become 0
operands and assign
%= the result
to left operand

performed exponential x**=2 x will become 144


(power)
calculation on
**= operators and
assign value to the left
operand

performed floor x / /= 2 x will become


division on
//=
operators and assign
value to
the left operand

Logical Operators

The following logical operators are supported by Python language. Assume variable A holds True and
variable B holds False.

Symbol Description Example

or If any one of the operand is true, then the A or B is True


condition becomes true.

and If both the operands are true, then the A and B is False
condition becomes true.

not Reverses the state of operand/condition. not A is False

Note:The Python Virtual Machine sometimes knows the value of Boolean expression before it has
evaluated all of its operands. For instance, in the expression A and B, if A is false, then so is the
expression and there is no need to evaluate B.Likewise in the expression A or B, if A is true, then so is
the expression, and again there is no need to evaluate B. This approach, in which evaluation stops as
soon as possible is called short-circuit evaluation.

Python Bitwise Operators


Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60; and b = 13; Now
in binary format they will be as follows −

a = 0011 1100

b = 0000 1101

-----------------

a&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001

~a = 1100 0011

Python's built-in function bin() can be used to obtain binary representation of an integer number.

The following Bitwise operators are supported by Python language

Operator Description Example

& Binary AND Operator copies a bit, to the result, if it (a & b) (means 0000 1100)
exists in both operands

| Binary OR It copies a bit, if it exists in either (a | b) = 61 (means 0011 1101)


operand.

^ Binary XOR It copies the bit, if it is set in one (a ^ b) = 49 (means 0011 0001)
operand but not both.

~ Binary Ones (~a ) = -61 (means 1100 0011 in 2's


It is unary and has the effect of
Complement complement form due to a signed
'flipping' bits.
binary number.

<< Binary Left Shift The left operand's value is moved left a << 2 = 240 (means 1111 0000)
by the number of bits specified by the
right operand.

>> Binary Right Shift The left operand's value is moved right a >> 2 = 15 (means 0000 1111)
by the number of bits specified by the
right operand.

Membership Operators

Python’s membership operators test for membership in a sequence, such as strings, lists, or tuples.
There are two membership operators as explained below
Let S=”Python” c=’o’

Operator Description Example

in Evaluates to true if it finds a variable in the c in S will result True


specified sequence and false otherwise.

not in Evaluates to true if it does not finds a c not in S will result False
variable in the specified sequence and false
otherwise.

Identity Operators

Identity operators compare the memory locations of two objects. There are two Identity operators as
explained below

Let x=10 and y=x

id(x) and id(y) are same in this case

Operator Description Example

is Evaluates to true if the variables on x is y will return True


either side of the operator point to the
same object and false otherwise.

is not Evaluates to false if the variables on x is not y will return False


either side of the operator point to the
same object and true otherwise.

Note: Important Operators


Summary

Python provides a wide array of operators that allow for various operations on data, ranging from
simple arithmetic and comparison to bitwise operations and identity checks. Understanding these
operators is essential for writing efficient and effective Python code.

Operator Precedence and Expression Evaluation

June 09, 2024

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.

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.

You might also like