⚙️ Python Operators and Expressions

 

🔹 1. What Are Operators?
Operators are symbols that perform operations on values or variables.
Example:

x = 10
y = 5
print(x + y)   # 15
 

Here, + is the operator, and x and y are operands.

🔹 2. Types of Operators in Python

🧮 A. Arithmetic Operators
Used for mathematical operations.

OperatorDescriptionExampleOutput
+Addition5 + 38
-Subtraction10 - 46
*Multiplication2 * 36
/Division10 / 33.333...
%Modulus10 % 31
**Exponentiation2 ** 38
//Floor Division10 // 33

Example:

a, b = 15, 4
print(a + b, a - b, a * b, a / b, a % b, a ** b, a // b)
 

⚖️ B. Comparison (Relational) Operators
Used to compare values — return True or False.

OperatorDescriptionExampleOutput
==Equal to5 == 5True
!=Not equal to5 != 3True
>Greater than10 > 2True
<Less than3 < 5True
>=Greater or equal10 >= 10True
<=Less or equal7 <= 9True

Example:

x, y = 7, 10
print(x > y, x == y, x != y)
 

💡 C. Logical Operators
Used to combine conditions.

OperatorDescriptionExampleOutput
andTrue if both are true(5 > 3) and (6 > 2)True
orTrue if at least one is true(5 > 8) or (6 > 2)True
notReverses conditionnot(5 > 3)False

Example:

a, b = True, False
print(a and b, a or b, not a)
 

📦 D. Assignment Operators
Used to assign values to variables.

OperatorExampleEquivalent To
=x = 5x = 5
+=x += 3x = x + 3
-=x -= 2x = x - 2
*=x *= 4x = x * 4
/=x /= 2x = x / 2
%=x %= 3x = x % 3

Example:

x = 10
x += 5
print(x)  # 15
 

⚙️ E. Bitwise Operators
Work on binary numbers.

OperatorDescriptionExampleOutput
&AND5 & 31
  OR5
^XOR5 ^ 36
<<Left shift5 << 110
>>Right shift5 >> 12

Example:

a, b = 5, 3
print(a & b, a | b, a ^ b, a << 1, a >> 1)
# Note: 5 (0101), 3 (0011)
 

🧩 F. Membership Operators
Used to check if a value exists in a sequence.

OperatorDescriptionExampleOutput
inTrue if found'a' in 'apple'True
not inTrue if not found'z' not in 'apple'True

Example:

fruits = ["apple", "banana", "mango"]
print("apple" in fruits)
 

🎯 G. Identity Operators
Compare memory locations of objects.

OperatorDescriptionExampleOutput
isTrue if same objectx is yTrue/False
is notTrue if differentx is not yTrue/False

Example:

x = [1, 2, 3]
y = x
z = [1, 2, 3]
print(x is y)   # True
print(x is z)   # False
 

🔹 3. Expressions
An expression combines variables, constants, and operators to produce a value.


Example:

x = 10 

y = 5 

z = (x + y) * 2 

print(z)  # 30

 

🧠 Quick Practice Tasks

Arithmetic Practice: Input two numbers and show sum, difference, product, quotient, remainder.

Eligibility Checker: Ask user’s age → print “Adult” if ≥18 else “Minor”.

Password Validation: Check if “@” exists in entered password using in.

Bitwise Practice: Display binary representation and perform bitwise & and |.