Operators, Expressions & Statements – Chapter 4 | O Level M3-R5 | Boosting Skills

Operators, Expressions and Python Statements – NIELIT O Level (M3-R5)

इस chapter में हम Python में operators, expressions और statements के बारे में सीखेंगे। इसमें Arithmetic, Relational, Logical, Bitwise Operators, Conditional Statements और Loop Control Statements जैसे break, continue, pass, else और assert शामिल हैं।

👉 Swipe to see more
1️⃣ Assignment Statement

💡 Introduction

Python में Assignment Statement का प्रयोग किसी variable को value देने के लिए किया जाता है। यह statement memory में data store करने का तरीका बताता है।

Definition: Assignment Statement वह statement है जो किसी variable को एक specific value assign करता है।

🧩 Syntax


variable_name = value
  

यहाँ = एक assignment operator है जो right side की value को left side variable में store करता है।

📘 Examples

Example 1:

x = 10
y = 20
z = x + y
print("Sum =", z)
    
Output: Sum = 30
Example 2 (Multiple Assignment):

a, b, c = 5, 10, 15
print(a, b, c)
    
Output: 5 10 15
Example 3 (Chained Assignment):

x = y = z = 100
print(x, y, z)
    
Output: 100 100 100

🔍 Flowchart Logic

  1. Start
  2. Initialize variable
  3. Assign value to variable
  4. Use variable in expression
  5. Display output
  6. Stop

⚙️ Types of Assignment

  • Simple Assignment → x = 10
  • Multiple Assignment → a, b = 5, 10
  • Chained Assignment → x = y = z = 20
  • Augmented Assignment → x += 5 (means x = x + 5)
Example (Augmented Assignment):

x = 10
x += 5   # same as x = x + 5
print("New value of x =", x)
    
Output: New value of x = 15

🧠 Key Points

  • Python में variable declare करते समय datatype specify नहीं करना पड़ता।
  • Assignment operator right-to-left काम करता है।
  • Multiple और chained assignments एक ही line में values assign करने देते हैं।
  • Augmented operators code को short और clean बनाते हैं।

🧩 Summary

  • Assignment Statement variable को value देने के लिए use होता है।
  • ‘=’ operator assignment के लिए प्रयोग किया जाता है।
  • Python में Multiple और Augmented assignment supported हैं।
2️⃣ Expressions in Python

💡 Introduction

Expression Python का एक बहुत ही महत्वपूर्ण हिस्सा है। Expression किसी value या result को produce करने वाला logical combination होता है जिसमें operands (values or variables) और operators शामिल होते हैं। जैसे गणित में हम लिखते हैं 2 + 3 × 4 — Python में यही concept code के रूप में लागू होता है।

Definition:
Expression is a combination of variables, constants, operators, and functions that produces a value.

🧩 Example (Basic Expression)


x = 10
y = 5
z = x + y * 2
print("Result =", z)
  
Output: Result = 20

यहाँ Python पहले multiplication (y * 2) करेगा, फिर addition (x + ...)। यानी Operator Precedence rule follow होता है।

📘 Flowchart Logic

  1. Start
  2. Initialize variables
  3. Perform operations (Arithmetic / Logical / etc.)
  4. Store result in variable
  5. Display output
  6. Stop

⚙️ Types of Expressions in Python

  • 1️⃣ Arithmetic Expression
  • 2️⃣ Relational (Comparison) Expression
  • 3️⃣ Logical Expression
  • 4️⃣ Bitwise Expression
  • 5️⃣ Assignment Expression
  • 6️⃣ String Expression
  • 7️⃣ Compound Expression

1️⃣ Arithmetic Expressions

Arithmetic expressions में +, -, *, /, %, //, ** जैसे operators का प्रयोग होता है। ये mathematical calculations करने के लिए उपयोगी हैं।


a = 15
b = 4
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Floor Division:", a // b)
print("Modulus:", a % b)
print("Exponent:", a ** b)
  
Output:
Addition: 19 Subtraction: 11 Multiplication: 60 Division: 3.75 Floor Division: 3 Modulus: 3 Exponent: 50625
📘 Explanation: Arithmetic expression हमेशा numeric result देता है। Exponentiation (**) का मतलब power होता है (15⁴)।

2️⃣ Relational (Comparison) Expressions

Relational expressions दो values की तुलना करते हैं और True या False result return करते हैं। Operators: >, <, ==, !=, >=, <=


x = 10
y = 20
print("x == y:", x == y)
print("x != y:", x != y)
print("x > y:", x > y)
print("x < y:", x < y)
print("x >= y:", x >= y)
print("x <= y:", x <= y)
  
Output: x == y: False x != y: True x > y: False x < y: True x >= y: False x <= y: True
Use: Relational expressions का प्रयोग decision making (if statements) में होता है।

3️⃣ Logical Expressions

Logical expressions का उपयोग multiple conditions को combine करने के लिए किया जाता है। Operators हैं: and, or, not.


a = 10
b = 20
c = 5

print(a > b and b > c)   # False
print(a < b or b < c)    # True
print(not(a < b))        # False
  
💡 Explanation:
- and → दोनों conditions True हों तभी True।
- or → कोई एक True हो तो True।
- not → result को उलट देता है।

4️⃣ Bitwise Expressions

Bitwise operators binary digits (0 और 1) पर काम करते हैं। Operators: &, |, ^, ~, <<, >>


x = 5    # 0101
y = 3    # 0011

print("AND:", x & y)
print("OR:", x | y)
print("XOR:", x ^ y)
print("NOT x:", ~x)
print("Left Shift:", x << 1)
print("Right Shift:", x >> 1)
  
Output:
AND: 1 OR: 7 XOR: 6 NOT x: -6 Left Shift: 10 Right Shift: 2
📗 Explanation: Bitwise operations बहुत useful होते हैं low-level programming, encryption, और optimization में।

5️⃣ Assignment Expressions

Assignment expression value को variable में store करने के लिए प्रयोग होता है। Example: x = 10, x += 2, (n := len(list)) (walrus operator)।


x = 10
x += 5
print("x =", x)

# Walrus Operator (Python 3.8+)
if (n := len("Hello")) > 3:
    print("Length is:", n)
  
🦭 Walrus operator (:=) एक expression के अंदर ही assignment करने की अनुमति देता है।

6️⃣ String Expressions

जब operators को strings पर use किया जाता है तो उन्हें string expressions कहते हैं। Example: concatenation (+), repetition (*).


name = "Python"
greet = "Hello " + name
print(greet)

line = "Hi! " * 3
print(line)
  
Output: Hello Python Hi! Hi! Hi!
💬 String expressions text manipulation और display formatting के लिए widely used हैं।

7️⃣ Compound Expressions

Compound expressions में एक से अधिक operators और sub-expressions combine होते हैं। Example: (a + b) * (c - d) / e


a, b, c, d, e = 10, 5, 8, 3, 2
result = (a + b) * (c - d) / e
print("Result =", result)
  
Output: Result = 37.5
💡 Compound expressions में operator precedence और parentheses का ध्यान रखना जरूरी है।

📊 Operator Precedence (Highest to Lowest)

LevelOperatorsDescription
1**Exponentiation
2~, +, -Unary plus, minus, bitwise NOT
3*, /, //, %Multiplication, division
4+, -Addition, subtraction
5<<, >>Bitwise shifts
6&Bitwise AND
7^, |XOR, OR
8<, <=, >, >=, ==, !=Comparisons
9not, and, orLogical operations
10=, +=, -=, *=, /=Assignments

🧠 Real-Life Examples

  • 📱 Arithmetic: Calculator applications
  • ⚖️ Relational: Age comparison for voting eligibility
  • 🔒 Logical: Login authentication (username & password)
  • 🧾 String: Dynamic message creation and UI labels

🧩 Summary

  • Expressions produce a result by combining variables, constants, and operators.
  • Python supports many types — Arithmetic, Logical, Relational, Bitwise, String.
  • Operator precedence decides execution order.
  • Parentheses () are used to control evaluation order.
  • Expressions are the building blocks of all Python programs.
📘 Remember: हर valid Python statement एक expression हो सकता है, और हर expression एक value return करता है।
3️⃣ Arithmetic Operators

💡 Introduction

Arithmetic Operators का प्रयोग गणितीय (mathematical) operations करने के लिए किया जाता है जैसे – जोड़ (addition), घटाना (subtraction), गुणा (multiplication), भाग (division) आदि। Python में arithmetic operators integer, float, और complex data types पर काम करते हैं।

Definition: Arithmetic operators are used to perform mathematical calculations between operands (numbers or variables).

📘 List of Arithmetic Operators

OperatorDescriptionExampleOutput
+Addition10 + 515
-Subtraction10 - 37
*Multiplication6 * 318
/Division10 / 42.5
//Floor Division10 // 42
%Modulus (Remainder)10 % 42
**Exponentiation (Power)3 ** 481

🧩 Flowchart Logic

  1. Start
  2. Input two numbers
  3. Apply operator (e.g., +, -, *, /, ...)
  4. Store result in variable
  5. Display output
  6. Stop

⚙️ Example 1 – Basic Arithmetic Operations


a = 10
b = 4

print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Floor Division:", a // b)
print("Modulus:", a % b)
print("Exponent:", a ** b)
  
Output:
Addition: 14 Subtraction: 6 Multiplication: 40 Division: 2.5 Floor Division: 2 Modulus: 2 Exponent: 10000
💡 Explanation: - Division (/) हमेशा float result देता है। - Floor Division (//) integer result देता है। - Modulus remainder देता है। - Exponentiation (**) power का कार्य करता है।

🧮 Example 2 – Arithmetic with Variables


x = int(input("Enter first number: "))
y = int(input("Enter second number: "))

sum = x + y
diff = x - y
prod = x * y
quot = x / y
rem = x % y

print("Sum =", sum)
print("Difference =", diff)
print("Product =", prod)
print("Quotient =", quot)
print("Remainder =", rem)
  
Explanation: यह example user input लेता है और सभी arithmetic results दिखाता है।
📘 Tip: हमेशा input को int() या float() में convert करें क्योंकि input() default रूप से string देता है।

🧠 Example 3 – Compound Arithmetic Expression


a, b, c = 10, 5, 2
result = (a + b) * c ** 2 / 5
print("Result =", result)
  
Output: Result = 60.0
Explanation: Operator precedence के अनुसार पहले **, फिर * /, और अंत में + execute होते हैं। हमेशा parentheses का प्रयोग करके expression को readable बनाएं।

🧩 Example 4 – Average of Three Numbers


a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
c = float(input("Enter third number: "))

avg = (a + b + c) / 3
print("Average =", avg)
  
Flow: Start → Input 3 numbers → Add → Divide by 3 → Output average → Stop Output: Average = (depends on input values)
📘 यह real-life example है जो school/college result calculation में उपयोग होता है।

🔢 Example 5 – Calculate Simple Interest


p = float(input("Enter Principal: "))
r = float(input("Enter Rate of Interest: "))
t = float(input("Enter Time (years): "))

si = (p * r * t) / 100
print("Simple Interest =", si)
  
Output: Simple Interest = (p×r×t)/100
🧠 Use: Banking systems और finance apps में arithmetic expressions extensively use होते हैं।

🧮 Example 6 – Swap Two Numbers Using Arithmetic


a = 5
b = 7

a = a + b
b = a - b
a = a - b

print("After Swapping: a =", a, ", b =", b)
  
Output: After Swapping: a = 7 , b = 5
⚙️ यहाँ किसी temporary variable की आवश्यकता नहीं है — सिर्फ arithmetic operations से values swap की गई हैं।

🧩 Example 7 – Convert Temperature


celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32
print("Temperature in Fahrenheit =", fahrenheit)
  
Explanation: Formula used → F = (C × 9/5) + 32 यही logic arithmetic expressions से directly compute किया गया है।

📊 Operator Precedence (Order of Execution)

PriorityOperatorMeaning
1**Exponentiation
2*, /, //, %Multiplication / Division / Modulus
3+, -Addition / Subtraction
🧠 जब एक ही expression में कई operators हों, Python precedence order और associativity (left-to-right) follow करता है।

⚙️ Example 8 – Precedence Test


x = 5 + 3 * 2 ** 2
print(x)
  
Output: 17 Explanation: Order: 2 ** 2 → 4, then 3 * 4 → 12, then 5 + 12 → 17

🧩 Real-Life Applications

  • Finance apps → Interest, EMI, Loan calculations
  • Engineering → Area, volume, formula computations
  • Gaming → Score calculation and animation logic
  • Science → Unit conversion (Celsius ↔ Fahrenheit)

🧠 Practice Corner

  • ✅ Write a Python program to find area and perimeter of a rectangle.
  • ✅ Calculate compound interest using formula.
  • ✅ Find average of n numbers entered by user.

🧩 Summary

  • Arithmetic operators perform mathematical computations.
  • Operators follow a fixed precedence order.
  • Expressions can be simple or compound.
  • Used everywhere — from basic calculation to real-world apps.
📘 Remember: Arithmetic operators Python के सभी numeric programs की foundation हैं। Practice them daily for strong logic building.
4️⃣ Relational (Comparison) Operators

💡 Introduction

Relational (या Comparison) Operators का उपयोग दो values की तुलना (comparison) करने के लिए किया जाता है। इन operators का result हमेशा True या False होता है। ये decision making (जैसे if statements) में बहुत उपयोगी होते हैं।

📘 Definition: A relational operator compares two operands and returns a boolean value (True or False).

📊 List of Relational Operators

OperatorDescriptionExampleOutput
==Equal to5 == 5True
!=Not equal to5 != 3True
>Greater than7 > 4True
<Less than3 < 7True
>=Greater than or equal to7 >= 7True
<=Less than or equal to4 <= 5True

🧩 Flowchart Logic

  1. Start
  2. Input two numbers (A, B)
  3. Apply comparison (A > B, A == B, etc.)
  4. Decision: True / False
  5. Display result
  6. Stop

⚙️ Q&A Based Examples

Q1. Check if two numbers are equal.

a = 10
b = 10
print(a == b)
    
Output: True Explanation: Both numbers are same, so condition is True.
Q2. Check if two numbers are not equal.

a = 15
b = 20
print(a != b)
    
Output: True Explanation: 15 and 20 are different, so result is True.
Q3. Is 8 greater than 5?

print(8 > 5)
    
Output: True
Q4. Is 12 less than 9?

print(12 < 9)
    
Output: False
Q5. Compare 7 and 7 using >= operator.

print(7 >= 7)
    
Output: True Explanation: Greater OR equal condition satisfied.
Q6. Compare 2 and 10 using <= operator.

print(2 <= 10)
    
Output: True
Q7. Compare two strings: "apple" and "banana"

print("apple" < "banana")
    
Output: True Explanation: Strings are compared alphabetically (lexicographically).
Q8. Compare uppercase and lowercase letters.

print("A" < "a")
    
Output: True Explanation: ASCII value of 'A' (65) is smaller than 'a' (97).
Q9. Compare boolean values.

print(True > False)
    
Output: True Explanation: Internally, True = 1 and False = 0.
Q10. Compare lists (lexicographically).

print([1, 2, 3] < [1, 3, 0])
    
Output: True Explanation: Python compares element-by-element like dictionary order.
Q11. Check if student passed (marks ≥ 40).

marks = int(input("Enter marks: "))
if marks >= 40:
    print("Pass")
else:
    print("Fail")
    
Output: If marks = 55 → Pass If marks = 30 → Fail
Q12. Find greater of two numbers.

a = 12
b = 8
if a > b:
    print("A is greater")
else:
    print("B is greater")
    
Output: A is greater
Q13. Check eligibility for voting (age ≥ 18).

age = int(input("Enter your age: "))
if age >= 18:
    print("Eligible for voting.")
else:
    print("Not eligible.")
    
Output: (depends on input)
Q14. Check if number is between 10 and 50.

n = int(input("Enter number: "))
if 10 <= n <= 50:
    print("Within range")
else:
    print("Out of range")
    
Output: Input = 25 → Within range Input = 70 → Out of range
Q15. Check equality of two strings ignoring case.

a = "HELLO"
b = "hello"
print(a.lower() == b.lower())
    
Output: True Explanation: Both converted to lowercase before comparison.

📘 Operator Precedence (In Comparisons)

  • All comparison operators have equal precedence.
  • They are evaluated from left to right.
  • Multiple comparisons can be chained: a < b < c
Example:

a, b, c = 5, 10, 15
print(a < b < c)
    
Output: True

🧠 Real-Life Applications

  • 🔐 User authentication (password match)
  • 🎓 Grade classification (marks ≥ criteria)
  • ⚙️ Conditional execution in programs
  • 📊 Data filtering and sorting in databases

📈 Practice Corner

  • ✅ Write a program to compare three numbers and print the largest.
  • ✅ Check if a number is positive, negative, or zero.
  • ✅ Input marks and print grade according to range.
  • ✅ Compare two strings alphabetically and show which comes first.

🧩 Summary

  • Relational operators always return boolean values (True/False).
  • Used in if, while, and filtering conditions.
  • Strings and lists can also be compared lexicographically.
  • They form the foundation of all decision-making logic in Python.
📘 Remember: Comparison is the heart of logical programming — हर program में decision लेने का आधार यही operators हैं।
5️⃣ Logical Operators

💡 Introduction

Logical Operators का प्रयोग conditions को जोड़ने या उनके result को manipulate करने के लिए किया जाता है। Python में 3 मुख्य logical operators होते हैं: and, or, और not। ये expressions का boolean (True/False) result देते हैं और decision making में अत्यंत उपयोगी होते हैं।

📘 Definition: Logical operators are used to combine or invert the results of two or more conditional (boolean) expressions.

📊 List of Logical Operators

OperatorDescriptionExampleResult
andReturns True if both conditions are True(5>3) and (8>5)True
orReturns True if at least one condition is True(5>10) or (8>5)True
notReverses the result (True→False, False→True)not(5>3)False

🧩 Flowchart Logic

  1. Start
  2. Input two conditions
  3. Apply logical operator (and/or/not)
  4. Generate True/False result
  5. Display result
  6. Stop

⚙️ Q&A Based Examples

Q1. Check if both conditions are True.

a = 10
b = 5
print(a > b and b < 10)
    
Output: True Explanation: दोनों conditions True हैं, इसलिए result True।
Q2. Check if at least one condition is True.

x = 8
print(x < 5 or x == 8)
    
Output: True Explanation: पहली condition False है लेकिन दूसरी True है, इसलिए output True।
Q3. Reverse a boolean result using not.

a = 10
print(not(a > 5))
    
Output: False Explanation: (a > 5) True है, not इसे उलटकर False बना देता है।
Q4. Check if number is between 10 and 20.

n = 15
print(n > 10 and n < 20)
    
Output: True
Q5. Check if a student passes (marks ≥ 40) and attendance ≥ 75.

marks = 60
attendance = 80
if marks >= 40 and attendance >= 75:
    print("Pass")
else:
    print("Fail")
    
Output: Pass
Q6. Check if number is positive or zero.

n = 0
if n > 0 or n == 0:
    print("Positive or Zero")
else:
    print("Negative")
    
Output: Positive or Zero
Q7. Check if a number is NOT even.

n = 7
print(not (n % 2 == 0))
    
Output: True Explanation: 7 odd है, तो (n%2==0) False है, और not उसे True बना देता है।
Q8. Check login authentication.

username = "admin"
password = "1234"

if username == "admin" and password == "1234":
    print("Login Successful")
else:
    print("Invalid credentials")
    
Output: Login Successful
Q9. Check if a number is divisible by 3 or 5.

n = 10
if n % 3 == 0 or n % 5 == 0:
    print("Divisible by 3 or 5")
else:
    print("Not divisible")
    
Output: Divisible by 3 or 5
Q10. Check if a person is teenager (13–19 years).

age = 17
if age >= 13 and age <= 19:
    print("Teenager")
else:
    print("Not a Teenager")
    
Output: Teenager
Q11. Check if both strings are same ignoring case.

a = "Hello"
b = "HELLO"
print(a.lower() == b.lower() and len(a) == len(b))
    
Output: True
Q12. Logical chaining example.

x, y, z = 5, 10, 15
print(x < y and y < z or z == 15)
    
Output: True Explanation: and का result True है और or condition भी True, इसलिए final True।
Q13. Combine not and and together.

a = 10
b = 5
print(not(a < b and a != b))
    
Output: True
Q14. Check if a number is outside range 50–100.

n = 120
if not(50 <= n <= 100):
    print("Out of range")
else:
    print("Within range")
    
Output: Out of range
Q15. Evaluate complex logical expression.

a, b, c = True, False, True
print(a and not b or c)
    
Output: True Explanation: not b = True, तो (a and True) = True, फिर or c → True.

📘 Operator Precedence (Logical)

  • not → Highest
  • and → Middle
  • or → Lowest
Example:

x = True or False and not False
print(x)
    
Output: True Explanation: not पहले चलता है, फिर and, फिर or।

🧠 Real-Life Applications

  • 🔐 Login validation (username & password check)
  • 🎓 Eligibility checking (age ≥ 18 and nationality == "Indian")
  • 🧮 Range-based filters in data
  • ⚙️ Complex condition handling in automation

📈 Practice Corner

  • ✅ Write a program to check if year is leap year (divisible by 4 and not by 100 or divisible by 400).
  • ✅ Input two numbers and print whether both are even or both are odd.
  • ✅ Check if entered character is vowel or consonant.
  • ✅ Create a login system using `and` and `not` operators.

🧩 Summary

  • Logical operators control multiple boolean expressions.
  • They return True or False only.
  • Precedence: not > and > or.
  • Used widely in decision making and looping.
📘 Remember: Logical operators Python के brain जैसे हैं — ये तय करते हैं कि कौन-सी condition True है और कौन-सी False।
6️⃣ Bitwise Operators

💡 Introduction

Bitwise Operators का प्रयोग integers के binary bits पर operation करने के लिए किया जाता है। ये operators direct bits (0s और 1s) पर काम करते हैं, इसलिए ये बहुत fast और efficient होते हैं। Bitwise operators का उपयोग low-level programming, encryption, और device control में किया जाता है।

📘 Definition: Bitwise operators perform operations on the binary representation of integers.

📊 List of Bitwise Operators

OperatorNameDescriptionExampleResult
&ANDSets bit to 1 if both bits are 15 & 31
|ORSets bit to 1 if at least one bit is 15 | 37
^XORSets bit to 1 if bits are different5 ^ 36
~NOTInverts all bits~5-6
<<Left ShiftShift bits to left, adds 0s on right5 << 110
>>Right ShiftShift bits to right, drops bits on right5 >> 12

🧩 Binary Representation


  Decimal : 5 → Binary : 0101
  Decimal : 3 → Binary : 0011
  

⚙️ Q&A Based Examples

Q1. Perform bitwise AND of 5 and 3.

a = 5  # 0101
b = 3  # 0011
print(a & b)
    
Output: 1 Explanation: 0101 & 0011 = 0001 → 1
Q2. Perform bitwise OR of 5 and 3.

print(5 | 3)
    
Output: 7 Explanation: 0101 | 0011 = 0111 → 7
Q3. Perform bitwise XOR of 5 and 3.

print(5 ^ 3)
    
Output: 6 Explanation: 0101 ^ 0011 = 0110 → 6
Q4. Find bitwise NOT of 5.

print(~5)
    
Output: -6 Explanation: ~n = -(n+1) → ~5 = -6
Q5. Perform left shift by 1 on 5.

print(5 << 1)
    
Output: 10 Explanation: 0101 → 1010 → 10
Q6. Perform right shift by 1 on 5.

print(5 >> 1)
    
Output: 2 Explanation: 0101 → 0010 → 2
Q7. Check bitwise AND of 12 and 25.

a = 12  # 1100
b = 25  # 11001
print(a & b)
    
Output: 8
Q8. Combine AND and OR.

x, y = 7, 3
print((x & y) | (x ^ y))
    
Output: 7
Q9. Turn off a specific bit (use AND with mask).

n = 13      # 1101
mask = 1<<2 # 0100
print(n & ~mask)
    
Output: 9 Explanation: Third bit cleared → 1001 → 9
Q10. Turn on a specific bit (use OR with mask).

n = 9       # 1001
mask = 1<<1 # 0010
print(n | mask)
    
Output: 11
Q11. Toggle a bit (use XOR).

n = 10      # 1010
mask = 1<<1 # 0010
print(n ^ mask)
    
Output: 8 Explanation: Second bit flipped → 1000 → 8
Q12. Left shift by 3 (multiply by 2³).

print(4 << 3)
    
Output: 32 Explanation: 4 × 2³ = 32
Q13. Right shift by 2 (divide by 2²).

print(20 >> 2)
    
Output: 5
Q14. Check if number is even using bitwise operator.

n = 14
if n & 1 == 0:
    print("Even")
else:
    print("Odd")
    
Output: Even
Q15. Swap two numbers using XOR (without third variable).

a, b = 5, 7
a = a ^ b
b = a ^ b
a = a ^ b
print(a, b)
    
Output: 7 5

📘 Operator Precedence (Bitwise)

PriorityOperatorMeaning
1~Bitwise NOT
2<<, >>Shift operators
3&AND
4^XOR
5|OR

🧠 Real-Life Applications

  • 🧮 Fast arithmetic (multiplication/division by powers of 2)
  • 💾 Data encryption / compression
  • ⚙️ Device control (bit flags, sensors)
  • 🧠 Memory-efficient programming

📈 Practice Corner

  • ✅ Write a program to count set bits (1s) in binary representation of a number.
  • ✅ Create a mask to turn on/off bits 0, 2, and 4.
  • ✅ Check if a number is power of two using bitwise AND.
  • ✅ Reverse bits of an integer using shifts and masks.

🧩 Summary

  • Bitwise operators work directly on bits (binary digits).
  • Useful for optimization and low-level hardware logic.
  • Shifts act like multiply/divide by powers of 2.
  • XOR is often used in cryptography and swapping values.
📘 Remember: Bitwise operations are Python के सबसे तेज़ गणनात्मक tools — इनसे logic समझने में आपकी binary सोच (computer logic) विकसित होती है।
7️⃣ Conditional Statements

💡 Introduction

Conditional Statements का प्रयोग किसी condition के आधार पर decision लेने के लिए किया जाता है। Python में यह control flow को manage करने का सबसे महत्वपूर्ण हिस्सा है। ये statements किसी condition के True या False होने पर अलग-अलग code block execute करते हैं।

📘 Definition: Conditional statements are used to execute a block of code only when a specific condition is True.

📊 Types of Conditional Statements in Python

  • if statement
  • if-else statement
  • if-elif-else ladder
  • nested if
  • short-hand if (single line)

🧩 Syntax


if condition:
    statement(s)
elif another_condition:
    statement(s)
else:
    statement(s)
  

🧭 Flowchart Logic

  1. Start
  2. Evaluate condition
  3. If True → execute body
  4. If False → skip or go to else
  5. End

⚙️ Q&A Based Examples

Q1. Check if a number is positive.

num = 10
if num > 0:
    print("Positive number")
    
Output: Positive number
Q2. Check if a number is positive or negative.

num = -5
if num >= 0:
    print("Positive")
else:
    print("Negative")
    
Output: Negative
Q3. Check if a number is even or odd.

n = 7
if n % 2 == 0:
    print("Even")
else:
    print("Odd")
    
Output: Odd
Q4. Find the largest of two numbers.

a, b = 10, 20
if a > b:
    print("A is greater")
else:
    print("B is greater")
    
Output: B is greater
Q5. Find the largest of three numbers (if-elif-else).

a, b, c = 30, 20, 10
if a > b and a > c:
    print("A is largest")
elif b > c:
    print("B is largest")
else:
    print("C is largest")
    
Output: A is largest
Q6. Check if a student passed or failed.

marks = 45
if marks >= 40:
    print("Pass")
else:
    print("Fail")
    
Output: Pass
Q7. Grading system (if-elif-else).

marks = 85
if marks >= 90:
    print("Grade A+")
elif marks >= 75:
    print("Grade A")
elif marks >= 60:
    print("Grade B")
elif marks >= 40:
    print("Grade C")
else:
    print("Fail")
    
Output: Grade A
Q8. Check eligibility for voting.

age = 17
if age >= 18:
    print("Eligible for voting")
else:
    print("Not eligible")
    
Output: Not eligible
Q9. Nested if – Check leap year.

year = 2024
if year % 4 == 0:
    if year % 100 == 0:
        if year % 400 == 0:
            print("Leap Year")
        else:
            print("Not Leap Year")
    else:
        print("Leap Year")
else:
    print("Not Leap Year")
    
Output: Leap Year
Q10. Check if number lies between 10 and 50.

n = 35
if 10 <= n <= 50:
    print("In range")
else:
    print("Out of range")
    
Output: In range
Q11. Check if entered character is vowel.

ch = 'e'
if ch.lower() in ['a', 'e', 'i', 'o', 'u']:
    print("Vowel")
else:
    print("Consonant")
    
Output: Vowel
Q12. Short-hand if statement.

a = 5
b = 10
print("A is greater") if a > b else print("B is greater")
    
Output: B is greater
Q13. Check if number is multiple of both 3 and 5.

num = 15
if num % 3 == 0 and num % 5 == 0:
    print("Multiple of 3 and 5")
else:
    print("Not multiple of both")
    
Output: Multiple of 3 and 5
Q14. Check if input is alphabet or digit.

ch = '7'
if ch.isdigit():
    print("Digit")
elif ch.isalpha():
    print("Alphabet")
else:
    print("Special Character")
    
Output: Digit
Q15. Login authentication (multiple conditions).

user = "admin"
pwd = "1234"
if user == "admin" and pwd == "1234":
    print("Access Granted")
else:
    print("Access Denied")
    
Output: Access Granted

📘 Operator Precedence in Conditions

  • Relational Operators (==, <, >) evaluated before Logical (and, or, not)
  • Parentheses () can override precedence

🧠 Real-Life Applications

  • 🎓 Grade calculation and pass/fail logic
  • 🔐 Login systems and access control
  • ⚙️ Automated decision-making systems
  • 🧮 Checking input values and validation

📈 Practice Corner

  • ✅ Write a program to check if number is divisible by 2, 3, or both.
  • ✅ Check if entered year is leap or not (using nested if).
  • ✅ Input marks and print grade using if-elif-else ladder.
  • ✅ Check whether character is uppercase, lowercase, digit, or special symbol.

🧩 Summary

  • Conditional statements decide which code block executes.
  • if executes only if condition is True.
  • if-elif-else handles multiple conditions.
  • Nested if allows checking within conditions.
  • Short-hand if used for compact one-line decisions.
📘 Remember: Conditional statements Python programs की logical thinking की नींव हैं — हर real-world problem का solution किसी ना किसी conditional logic से शुरू होता है।
8️⃣ Looping Statements

💡 Introduction

Looping statements का प्रयोग तब किया जाता है जब किसी code block को बार-बार दोहराना (repeat) हो। Python में मुख्य दो प्रकार के loops होते हैं — for loop और while loop। इसके अलावा loops को nested (एक loop के अंदर दूसरा loop) भी बनाया जा सकता है।

📘 Definition: A loop is used to execute a block of code multiple times until a specific condition is satisfied.

📊 Types of Loops in Python

  • for loop – sequence (list, tuple, string, range) पर iterate करता है
  • while loop – जब तक condition True है, code चलता रहता है
  • nested loop – एक loop के अंदर दूसरा loop

🧩 Syntax


# for loop
for variable in sequence:
    statement(s)

# while loop
while condition:
    statement(s)
  

🧭 Flowchart Logic

  1. Start
  2. Initialize counter variable
  3. Check condition
  4. If True → Execute body → Update counter
  5. If False → Exit loop
  6. Stop

⚙️ Q&A Based Examples

Q1. Print numbers from 1 to 5 using for loop.

for i in range(1, 6):
    print(i)
    
Output:
1
2
3
4
5
Q2. Print numbers from 1 to 5 using while loop.

i = 1
while i <= 5:
    print(i)
    i += 1
    
Output:
1
2
3
4
5
Q3. Print even numbers from 2 to 10.

for i in range(2, 11, 2):
    print(i)
    
Output: 2 4 6 8 10
Q4. Calculate sum of first 10 numbers.

sum = 0
for i in range(1, 11):
    sum += i
print("Sum =", sum)
    
Output: Sum = 55
Q5. Print multiplication table of 5.

for i in range(1, 11):
    print("5 x", i, "=", 5*i)
    
Output: 5×1=5 ... 5×10=50
Q6. Reverse a string using for loop.

s = "Python"
for ch in reversed(s):
    print(ch, end="")
    
Output: nohtyP
Q7. Print characters of a string using for loop.

for ch in "HELLO":
    print(ch)
    
Output:
H
E
L
L
O
Q8. Find factorial of a number using while loop.

n = 5
fact = 1
while n > 0:
    fact *= n
    n -= 1
print("Factorial =", fact)
    
Output: Factorial = 120
Q9. Print first 10 natural numbers using while loop.

i = 1
while i <= 10:
    print(i)
    i += 1
    
Output: 1 to 10
Q10. Print table of any user input number.

n = int(input("Enter number: "))
for i in range(1, 11):
    print(n, "x", i, "=", n*i)
    
Output: (depends on input)
Q11. Calculate sum of digits of a number.

num = 1234
sum = 0
while num > 0:
    digit = num % 10
    sum += digit
    num //= 10
print("Sum =", sum)
    
Output: Sum = 10
Q12. Print pattern of stars (triangle).

for i in range(1, 6):
    print("*" * i)
    
Output: * ** *** **** *****
Q13. Print reverse pattern of stars.

for i in range(5, 0, -1):
    print("*" * i)
    
Output: ***** **** *** ** *
Q14. Nested loop – multiplication table for 1 to 3.

for i in range(1, 4):
    for j in range(1, 6):
        print(i, "x", j, "=", i*j)
    print("-----------")
    
Output: tables of 1, 2, 3
Q15. Find numbers divisible by 3 and 5 between 1–50.

for i in range(1, 51):
    if i % 3 == 0 and i % 5 == 0:
        print(i)
    
Output: 15, 30, 45
Q16. Use break statement to stop loop.

for i in range(1, 11):
    if i == 6:
        break
    print(i)
    
Output: 1 2 3 4 5
Q17. Use continue to skip even numbers.

for i in range(1, 10):
    if i % 2 == 0:
        continue
    print(i)
    
Output: 1 3 5 7 9
Q18. Sum of squares of first 5 numbers.

s = 0
for i in range(1, 6):
    s += i*i
print("Sum of squares =", s)
    
Output: 55
Q19. Infinite loop example (use carefully).

# WARNING: Infinite Loop
while True:
    print("Hello")
    break  # prevents actual infinity
    
Output: Hello
Q20. Print Fibonacci series using loop.

a, b = 0, 1
for i in range(10):
    print(a, end=" ")
    a, b = b, a + b
    
Output: 0 1 1 2 3 5 8 13 21 34

📘 Loop Control Statements

  • break → stops loop immediately
  • continue → skips current iteration
  • pass → null statement (used as placeholder)

🧠 Real-Life Applications

  • 🧮 Table generation and number series
  • 🎓 Pattern printing and result analysis
  • 📊 Data iteration (lists, files, strings)
  • ⚙️ Automation and repetitive tasks

📈 Practice Corner

  • ✅ Print sum of all even numbers between 1 and 100.
  • ✅ Create a number pyramid using nested loops.
  • ✅ Find factorial of given number using for loop.
  • ✅ Reverse a number using while loop.

🧩 Summary

  • Loops help in repeating code efficiently.
  • for → sequence iteration, while → condition-based repetition.
  • Nested loops → patterns and tables.
  • break, continue, pass → control loop flow.
📘 Remember: Loops are the heartbeat of programming — ये repetition और automation को आसान बनाते हैं।
9️⃣ Loop Control Statements (break, continue, pass)

💡 Introduction

Python में Loop Control Statements का प्रयोग loop के normal flow को बदलने के लिए किया जाता है। इनका उपयोग loop को रोकने, किसी iteration को skip करने या future code के लिए placeholder के रूप में किया जाता है।

📘 Definition: Loop control statements alter the flow of execution inside loops based on specific conditions.

📊 Types of Loop Control Statements

StatementDescription
breakStops the loop immediately
continueSkips the current iteration and moves to next
passNull statement, does nothing (used as placeholder)

🧭 Flowchart Logic

  1. Start Loop
  2. Check condition
  3. If break → Exit loop
  4. If continue → Skip to next iteration
  5. If pass → Do nothing
  6. End

⚙️ Q&A Based Examples

🔹 Break Statement

Q1. Stop loop when number equals 5.

for i in range(1, 11):
    if i == 5:
        break
    print(i)
    
Output: 1 2 3 4 Explanation: जब i = 5 होता है, loop तुरंत रुक जाता है।
Q2. Find first negative number in a list.

nums = [12, 45, -8, 33, 90]
for n in nums:
    if n < 0:
        print("First negative =", n)
        break
    
Output: First negative = -8
Q3. Break while loop when count reaches 3.

count = 1
while count <= 5:
    print(count)
    if count == 3:
        break
    count += 1
    
Output: 1 2 3
Q4. Search an element and stop when found.

nums = [10, 20, 30, 40]
target = 30
for n in nums:
    if n == target:
        print("Found", n)
        break
    
Output: Found 30

🔹 Continue Statement

Q5. Skip even numbers.

for i in range(1, 10):
    if i % 2 == 0:
        continue
    print(i)
    
Output: 1 3 5 7 9
Q6. Skip printing number 5.

for i in range(1, 8):
    if i == 5:
        continue
    print(i)
    
Output: 1 2 3 4 6 7
Q7. Print only positive numbers from list.

nums = [12, -7, 8, 0, -2, 15]
for n in nums:
    if n <= 0:
        continue
    print(n)
    
Output: 12 8 15
Q8. Skip vowels in a string.

for ch in "PYTHON":
    if ch in "AEIOU":
        continue
    print(ch, end="")
    
Output: PYTHN
Q9. Skip marks below 40 (fail students).

marks = [75, 20, 55, 38, 90]
for m in marks:
    if m < 40:
        continue
    print("Passed with", m)
    
Output:
Passed with 75
Passed with 55
Passed with 90

🔹 Pass Statement

Q10. Use pass as a placeholder.

for i in range(5):
    pass  # future logic here
print("Loop executed successfully.")
    
Output: Loop executed successfully.
Q11. Check number is negative or not, ignore positive.

num = 5
if num > 0:
    pass
else:
    print("Negative number")
    
Output: (no output)
Q12. Define an empty function using pass.

def future_task():
    pass
print("Function created successfully.")
    
Output: Function created successfully.

🔹 Mixed Control Flow Examples

Q13. Print numbers 1 to 10 but stop at 7.

for i in range(1, 11):
    if i == 7:
        break
    print(i)
    
Output: 1 2 3 4 5 6
Q14. Print only odd numbers, skip even, and stop at 15.

for i in range(1, 21):
    if i == 15:
        break
    if i % 2 == 0:
        continue
    print(i)
    
Output: 1 3 5 7 9 11 13
Q15. Use pass in loop to skip undefined logic.

for i in range(1, 6):
    if i == 3:
        pass
    else:
        print("Processing:", i)
    
Output:
Processing: 1
Processing: 2
Processing: 4
Processing: 5

📘 Difference Summary Table

StatementActionUsed For
breakExits loopStop loop immediately
continueSkips iterationIgnore certain conditions
passNo operationPlaceholder / future code

🧠 Real-Life Applications

  • 🎯 Skipping invalid data entries (using continue)
  • 🚫 Exiting search loop when result found (using break)
  • 📋 Reserving structure for future logic (using pass)

📈 Practice Corner

  • ✅ Write a program to print 1–100 but stop when number = 73.
  • ✅ Skip all multiples of 3 and 5 between 1–50.
  • ✅ Use pass to create empty function templates for future code.

🧩 Summary

  • break → immediately exits loop.
  • continue → skips current iteration.
  • pass → does nothing (acts as a null statement).
  • All three make loops flexible and powerful.
📘 Remember: “Loop control statements are the gears of your program — वे तय करते हैं कि loop कब चले, कब रुके, और कब रुक कर कुछ न करे।” 🚀
🔟 Nested Loops & Pattern Programs

💡 Introduction

जब एक loop के अंदर दूसरा loop होता है, उसे Nested Loop कहा जाता है। Nested loops का प्रयोग patterns, matrices, tables और complex data traversal के लिए किया जाता है। हर outer loop के अंदर inner loop कई बार execute होता है।

📘 Definition: A nested loop is a loop inside another loop. The inner loop completes all its iterations for each iteration of the outer loop.

📊 Syntax


for i in range(outer_limit):
    for j in range(inner_limit):
        # inner loop statements
  

🧭 Flowchart Logic

  1. Start
  2. Outer loop initialization
  3. Inner loop runs completely
  4. Outer loop increments
  5. Repeat until condition False
  6. Stop

⭐ STAR PATTERN PROGRAMS

Q1. Print simple 5-row star pattern.

for i in range(1, 6):
    for j in range(1, i + 1):
        print("*", end="")
    print()
    
Output:
*
**
***
****
***** Explanation: Outer loop rows control करता है, inner loop stars print करता है।
Q2. Reverse star pattern.

for i in range(5, 0, -1):
    for j in range(i):
        print("*", end="")
    print()
    
Output:
*****
****
***
**
*
Q3. Right aligned star pattern.

for i in range(1, 6):
    print(" " * (5 - i) + "*" * i)
    
Output:
*
**
***
****
*****
Q4. Pyramid star pattern.

for i in range(1, 6):
    print(" " * (5 - i) + "*" * (2*i - 1))
    
Output:
*
***
*****
*******
*********
Q5. Diamond star pattern.

n = 5
for i in range(1, n + 1):
    print(" " * (n - i) + "*" * (2*i - 1))
for i in range(n - 1, 0, -1):
    print(" " * (n - i) + "*" * (2*i - 1))
    
Output:
*
***
*****
*******
*********
*******
*****
***
*

🔢 NUMBER PATTERN PROGRAMS

Q6. Print numbers in increasing pattern.

for i in range(1, 6):
    for j in range(1, i + 1):
        print(j, end="")
    print()
    
Output:
1
12
123
1234
12345
Q7. Print same number in each row.

for i in range(1, 6):
    for j in range(1, i + 1):
        print(i, end="")
    print()
    
Output:
1
22
333
4444
55555
Q8. Print reverse number pattern.

for i in range(5, 0, -1):
    for j in range(1, i + 1):
        print(j, end="")
    print()
    
Output:
12345
1234
123
12
1
Q9. Print pyramid of numbers.

for i in range(1, 6):
    print(" " * (5 - i), end="")
    for j in range(1, i + 1):
        print(j, end="")
    for j in range(i - 1, 0, -1):
        print(j, end="")
    print()
    
Output:
1
121
12321
1234321
123454321

🅰️ ALPHABET PATTERN PROGRAMS

Q10. Print A to E triangle.

for i in range(65, 70):  # ASCII A=65
    for j in range(65, i + 1):
        print(chr(j), end="")
    print()
    
Output:
A
AB
ABC
ABCD
ABCDE
Q11. Print alphabet pyramid.

for i in range(1, 6):
    print(" " * (5 - i), end="")
    for j in range(65, 65 + i):
        print(chr(j), end="")
    print()
    
Output:
A
AB
ABC
ABCD
ABCDE
Q12. Reverse alphabet pattern.

for i in range(69, 64, -1):
    for j in range(65, i + 1):
        print(chr(j), end="")
    print()
    
Output:
ABCDE
ABCD
ABC
AB
A

💠 SPECIAL PATTERNS

Q13. Hollow square star pattern.

n = 5
for i in range(n):
    for j in range(n):
        if i == 0 or i == n - 1 or j == 0 or j == n - 1:
            print("*", end="")
        else:
            print(" ", end="")
    print()
    
Output:
*****
* *
* *
* *
*****
Q14. Cross (X) pattern.

n = 5
for i in range(n):
    for j in range(n):
        if i == j or i + j == n - 1:
            print("*", end="")
        else:
            print(" ", end="")
    print()
    
Output:
* *
* *
*
* *
* *
Q15. 0-1 triangle pattern.

for i in range(1, 6):
    for j in range(1, i + 1):
        print((i + j) % 2, end="")
    print()
    
Output:
1
01
101
0101
10101

🧠 Real-Life Applications

  • 🎨 Creating visual patterns and animations
  • 🧮 Matrix and grid-based logic
  • 📊 Data representation in tabular form
  • 💡 Logical problem-solving in interviews

📈 Practice Corner

  • ✅ Create a hollow pyramid pattern of stars.
  • ✅ Print Pascal’s triangle using nested loops.
  • ✅ Print numbers in diamond shape.
  • ✅ Print checkerboard (chessboard) pattern using * and space.

🧩 Summary

  • Nested loops = loops inside another loop.
  • Used for printing patterns, grids, tables, etc.
  • Outer loop controls rows, inner loop controls columns.
  • Best topic for logical & pattern-based coding questions.
📘 Remember: “Nested loops are like coordinate grids — हर (i, j) पर logic decide करता है कि क्या print होगा।” 🚀
1️⃣1️⃣TOP TRENDING NESTED LOOP & PATTERN FAQs

ये FAQs Python के Nested Loops और Pattern Programs पर आधारित हैं — जो आजकल O Level, College Exams और Interviews में सबसे ज्यादा पूछे जाते हैं।

1️⃣ Nested Loop क्या है और इसे क्यों उपयोग करते हैं?

जब एक loop के अंदर दूसरा loop हो, तो उसे Nested Loop कहते हैं। इसका उपयोग तब किया जाता है जब हमें दो-स्तरीय iteration (जैसे rows और columns) की आवश्यकता होती है।

2️⃣ किससे पता चलेगा कि Nested Loop की जरूरत है?

जब हमें किसी 2D structure (जैसे matrix या grid) या pattern printing करनी हो, जहाँ rows और columns दोनों को अलग-अलग control करना हो।

3️⃣ Nested Loop की Time Complexity क्या होती है?

यदि outer loop n बार और inner loop भी n बार चलता है, तो उसकी time complexity O(n²) होगी।

4️⃣ Pattern Programs में Nested Loop कैसे काम करते हैं?

Outer loop rows को नियंत्रित करता है और Inner loop columns को। हर outer iteration में inner loop पूरा चलता है और pattern बनता है।

5️⃣ Nested Loop में break और continue कैसे काम करते हैं?

Inner loop में break लगाने से inner loop तुरंत रुक जाता है जबकि continue current iteration को छोड़कर अगली iteration पर चला जाता है।

6️⃣ Python में Nested Loop का syntax क्या है?


for i in range(outer_limit):
    for j in range(inner_limit):
        print(i, j)
    

7️⃣ Nested Loop के नुकसान क्या हैं?

बहुत अधिक nesting readability को घटा सकती है, performance धीमी हो सकती है और variable scope में confusion आ सकता है।

8️⃣ Pattern Problems में Nested Loop क्यों आसान रहता है?

क्योंकि हम rows और columns को अलग-अलग नियंत्रित कर सकते हैं — जिससे logic आसान और structured हो जाता है।

9️⃣ Nested Loop में for और while दोनों का मिश्रण कैसे किया जा सकता है?


for i in range(3):
    j = 0
    while j < 3:
        print(i, j)
        j += 1
    

🔟 Nested Loop के बजाय list comprehension क्यों उपयोग करते हैं?

क्योंकि list comprehension कोड को छोटा और तेज बनाती है — यह nested loops के समान काम को एक लाइन में कर सकती है।