0% found this document useful (0 votes)
25 views3 pages

Python Operators: Types & Examples

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views3 pages

Python Operators: Types & Examples

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python Operators: Theory, Precedence

& Examples
1. Arithmetic Operators
Theory: These operators perform basic mathematical operations like addition, subtraction,
multiplication, etc.

Precedence: Highest → ** > *, /, //, % > +, -

Examples:

 Addition (+): 5 + 3 = 8
 Subtraction (-): 10 - 4 = 6
 Multiplication (*): 6 * 2 = 12
 Division (/): 10 / 2 = 5.0
 Floor Division (//): 9 // 2 = 4
 Modulus (%): 10 % 3 = 1
 Exponentiation (**): 2 ** 3 = 8

2. Logical Operators
Theory: These are used to combine conditional statements. Returns True or False.

Precedence: not > and > or

Examples:

 and: True and False = False


 or: True or False = True
 not: not True = False

3. Bitwise Operators
Theory: These work on bits (0s and 1s) of integers.

Precedence: ~ > << >> > & > ^ > |

Examples:

 & (AND): 5 & 3 = 1


 | (OR): 5 | 3 = 7
 ^ (XOR): 5 ^ 3 = 6
 ~ (NOT): ~5 = -6
 << (Left Shift): 5 << 1 = 10
 >> (Right Shift): 5 >> 1 = 2

4. Relational Operators
Theory: Used to compare two values. Returns True or False.

Precedence: > >= < <= == !=

Examples:

 == : 5 == 5 → True
 != : 5 != 3 → True
 > : 5 > 2 → True
 < : 3 < 5 → True
 >= : 5 >= 5 → True
 <= : 3 <= 5 → True

5. Membership Operators
Theory: Used to check if a value is present in a sequence (like string, list, etc.).

Precedence: Same as comparison operators

Examples:

 'a' in 'apple' → True


 'z' not in 'apple' → True

6. Identity Operators
Theory: Used to compare memory locations of two objects.

Precedence: Same as comparison operators

Examples:

 a is b: True if a and b point to same object


 a is not b: True if a and b point to different objects

7. Final Combined Example


Theory: Putting it all together in one example.

Precedence: Mixed usage of all types.

Examples:
 a = 5; b = 3
 if (a > b) and (a != b):
 print('a is greater and not equal to b')
 c = a + b # Arithmetic
 print(c in [8, 9]) # Membership
 print(a is b) # Identity

You might also like