Python Notes
Master the Python for loop — iterate over sequences, ranges, strings, lists, and dictionaries. Learn loop patterns, nested loops, enumerate, zip, and real-world programs with Hindi explanations.
Introduction (परिचय)
for loop का उपयोग तब होता है जब हम एक sequence (list, string, range, etc.) के हर element पर कोई काम करना चाहते हैं।
Real-Life Analogy: `` "क्लास के हर विद्यार्थी का नाम पुकारो" "Bag के हर item की जाँच करो" "1 से 100 तक गिनती करो" ``Flow Diagram (प्रवाह आरेख)
For Loop with range() (range के साथ)
range() एक number sequence generate करता है।
range() Variations
range(stop) # 0 to stop-1
range(start, stop) # start to stop-1
range(start, stop, step) # start to stop-1, step by stepExamples
# range(5) — 0 to 4
for i in range(5):
print(i, end=" ")
print()Output: 0 1 2 3 4
# range(1, 6) — 1 to 5
for i in range(1, 6):
print(i, end=" ")
print()Output: 1 2 3 4 5
# range(1, 11, 2) — odd numbers
for i in range(1, 11, 2):
print(i, end=" ")
print()Output: 1 3 5 7 9
# range(10, 0, -1) — countdown
for i in range(10, 0, -1):
print(i, end=" ")
print("BLAST OFF! 🚀")Output: 10 9 8 7 6 5 4 3 2 1 BLAST OFF! 🚀
Iterating Over Sequences (Sequences पर Iteration)
Iterating a List
Output:
| Fruit | apple 🍎 |
| Fruit | banana 🍎 |
| Fruit | mango 🍎 |
| Fruit | grapes 🍎 |
| Fruit | orange 🍎 |
Iterating a String (String पर)
word = "PYTHON"
for letter in word:
print(letter, end=" — ")
print("Done!")Output: P — Y — T — H — O — N — Done!
# Count vowels in a string
sentence = "Python is awesome"
vowels = 0
for char in sentence:
if char.lower() in "aeiou":
vowels += 1
print(f"Number of vowels: {vowels}")Output: Number of vowels: 7
Iterating a Tuple
coordinates = (10, 20, 30, 40, 50)
for value in coordinates:
print(f"Value: {value}")Iterating a Dictionary
student = {
"name": "Rahul",
"age": 20,
"city": "Delhi",
"grade": "A"
}
# Keys only (default)
print("Keys:")
for key in student:
print(f" {key}")
# Values only
print("\nValues:")
for value in student.values():
print(f" {value}")
# Key-Value pairs
print("\nKey-Value:")
for key, value in student.items():
print(f" {key}: {value}")Output:
Keys
name
age
city
grade
Values
Rahul
20
Delhi
A
Key-Value
name: Rahul
age: 20
city: Delhi
grade: A
Useful Built-in Functions with For
enumerate() — Index + Value
Output:
# Custom start index
for i, name in enumerate(subjects, start=1):
print(f"Subject {i}: {name}")zip() — Two Sequences Together
Output:
| Rahul | 85 marks |
| Priya | 92 marks |
| Amit | 78 marks |
| Sita | 96 marks |
Practical Programs (व्यावहारिक कार्यक्रम)
Program 1: Multiplication Table
n = int(input("Enter a number for multiplication table: "))
print(f"\n=== Multiplication Table of {n} ===")
for i in range(1, 11):
result = n * i
print(f"{n} × {i:2d} = {result:3d}")Output (n=7):
Program 2: Sum of N Numbers
n = int(input("Enter N: "))
total = 0
for i in range(1, n + 1):
total += i
print(f"Sum of 1 to {n} = {total}")
print(f"Formula check: n*(n+1)/2 = {n*(n+1)//2}")Output (n=100):
Program 3: Factorial Calculator
n = int(input("Enter a number: "))
factorial = 1
for i in range(1, n + 1):
factorial *= i
print(f" Step {i}: {i}! = {factorial}")
print(f"\n{n}! = {factorial}")Output (n=5):
| Step 1 | 1! = 1 |
| Step 2 | 2! = 2 |
| Step 3 | 3! = 6 |
| Step 4 | 4! = 24 |
| Step 5 | 5! = 120 |
Program 4: Prime Number Check
n = int(input("Enter a number: "))
is_prime = True
if n < 2:
is_prime = False
else:
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
is_prime = False
print(f" {n} is divisible by {i}")
break
if is_prime:
print(f"{n} is a PRIME number 🔢")
print(f"{n} एक अभाज्य संख्या है")
else:
print(f"{n} is NOT a prime number")Program 5: List Operations
Output:
| Numbers | [3, 7, 2, 9, 1, 5, 8, 4, 6, 10] |
| Sum | 55 |
| Average | 5.50 |
| Maximum | 10 |
| Minimum | 1 |
| Even numbers | 4 |
| Odd numbers | 6 |
Nested For Loops (Nested For Loops)
# Multiplication table for 1-5
print("Multiplication Table (1-5)")
print("-" * 30)
for i in range(1, 6):
for j in range(1, 6):
print(f"{i*j:3d}", end="")
print()Output:
Nested Loop — Pattern
# Right triangle pattern
rows = 5
for i in range(1, rows + 1):
for j in range(i):
print("*", end=" ")
print()Output:
List Comprehension (Advanced — संक्षिप्त List बनाना)
Output:
Output: [2, 4, 6, 8, 10]
For-Else Construct (For के साथ Else)
Output: 5 not found in the list
Common Mistakes (सामान्य गलतियाँ)
❌ Mistake 1: Modifying list while iterating
❌ Mistake 2: Off-by-one with range
# Print 1 to 10
# WRONG
for i in range(10): # gives 0 to 9
print(i)
# CORRECT
for i in range(1, 11): # gives 1 to 10
print(i)❌ Mistake 3: Using loop variable after loop
for i in range(5):
pass
print(i) # i = 4 (last value) — works but bad practice
# Better: don't rely on loop variable after loop ends❌ Mistake 4: Unnecessary range(len())
Practice Exercises (अभ्यास प्रश्न)
Exercise 1 — Count Even/Odd
Count even and odd numbers from 1 to N.
Exercise 2 — Reverse a String
Reverse a string using for loop without using [::-1].
Exercise 3 — FizzBuzz
Print 1 to 50. For multiples of 3 print "Fizz", for 5 print "Buzz", for both print "FizzBuzz".
Exercise 4 — Fibonacci Series
Print first N Fibonacci numbers. *(0, 1, 1, 2, 3, 5, 8, 13, ...)*
Exercise 5 — Sum of Digits
Take a number, find sum of its digits using a loop. *(e.g., 1234 → 1+2+3+4 = 10)*
Exercise 6 — Palindrome Check
Check if a word is a palindrome using a for loop.
Solutions (हल)
Solution 1
n = int(input("Enter N: "))
even = odd = 0
for i in range(1, n + 1):
if i % 2 == 0:
even += 1
else:
odd += 1
print(f"Even: {even}, Odd: {odd}")Solution 3 — FizzBuzz
for i in range(1, 51):
if i % 3 == 0 and i % 5 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)Solution 4 — Fibonacci
n = int(input("How many Fibonacci numbers? "))
a, b = 0, 1
for i in range(n):
print(a, end=" ")
a, b = b, a + b
print()Solution 5 — Sum of Digits
num = input("Enter a number: ")
digit_sum = 0
for digit in num:
if digit.isdigit():
digit_sum += int(digit)
print(f"Sum of digits: {digit_sum}")Summary (सारांश)
| Feature | Syntax | Use |
|---|---|---|
| Range loop | for i in range(n) | Count n times |
| List loop | for item in list | Each list item |
| String loop | for ch in string | Each character |
| Enumerate | for i, v in enumerate(seq) | Index + value |
| Zip | for a, b in zip(s1, s2) | Two sequences |
| Nested | for i in r: for j in r: | 2D problems |
Next Topic (अगला विषय)
➡️ While Loop — जब तक condition True हो, चलता रहे
✅ Key Takeaways
- 🔁
forloop Python में definite iteration के लिए use होता है — जब हमें पता हो कि कितनी बार loop चलेगा - 📋
forloop किसी भी iterable (list, string, tuple, dict, range, set, file) पर काम करता है - 🔢
range(start, stop, step)function numbers की sequence generate करता है — stop value include नहीं होती - 🏷️
enumerate()से index और value दोनों एक साथ मिलते हैं — manual counter बनाने की जरूरत नहीं - 🔗
zip()से दो या अधिक sequences को parallel iterate कर सकते हैं - 📦 List comprehension for loop का short और fast version है — simple transformations के लिए best है
- 🔄 Nested loops 2D problems (patterns, matrices, tables) के लिए use होते हैं — Time Complexity O(n²) होती है
- ⚠️ Loop चलते समय list को modify करना dangerous है — हमेशा copy पर iterate करें या comprehension use करें
- 🎯
for-elseconstruct:elseblock तब execute होता है जब loop बिना break के पूरा होता है - 💡 Pythonic code में
range(len(list))की जगह direct iteration याenumerate()prefer करें
❓ FAQ
Q1: for loop और while loop में क्या difference है?
Answer: for loop definite iteration के लिए है — जब हमें पता हो कितनी बार loop चलेगा (sequence पर iterate करना)। while loop indefinite iteration के लिए है — जब condition True हो तब तक चलता रहे, end पहले से पता नहीं।
# for — known iterations
for i in range(5):
print(i)
# while — unknown iterations (until user says stop)
while input("Continue? (y/n): ") == "y":
print("Running...")Q2: range() में stop value include क्यों नहीं होती?
Answer: यह Python की zero-indexed philosophy के कारण है। range(5) gives 0,1,2,3,4 — exactly 5 elements। यह list indexing (list[0] to list[n-1]) के साथ consistent रहता है। Formula: range(n) always gives n elements।
Q3: क्या for loop में multiple variables use कर सकते हैं?
Answer: हाँ! Tuple unpacking से multiple variables use कर सकते हैं:
Q4: for-else actually कब use होता है?
Answer: for-else mostly search operations में useful है — जब loop में item मिल जाए तो break करो, अगर पूरा loop चलने के बाद भी नहीं मिला तो else block execute होगा। यह "not found" case handle करता है cleanly।
for num in numbers:
if num == target:
print("Found!")
break
else:
print("Not found — loop completed without break")Q5: List comprehension हमेशा for loop से better है?
Answer: नहीं! List comprehension simple transformations और filtering के लिए great है, but complex logic (multiple statements, try-except, side effects like printing) के लिए regular for loop ही better है। Readability > Cleverness!
Q6: Nested loops को optimize कैसे करें?
Answer: Nested loops O(n²) time लेते हैं। Optimization tips:
- Inner loop को minimize करें — अगर possible हो तो dictionary/set lookup (O(1)) use करें
- Break early — जैसे ही answer मिले, inner loop से break करें
- itertools.product() use करें cleaner code के लिए
- Large data के लिए NumPy vectorization consider करें
Q7: _ (underscore) loop variable कब use करते हैं?
Answer: जब हमें loop variable की value use नहीं करनी — बस कुछ बार repeat करना है, तब _ convention है:
# We don't need the variable, just want to repeat 5 times
for _ in range(5):
print("Hello!")Q8: reversed() और negative step (range(n, 0, -1)) में क्या difference है?
Answer: reversed() किसी भी sequence को reverse iterate करता है (list, string, etc.), जबकि negative step range() specific है:
# reversed() — works on any sequence
for ch in reversed("PYTHON"):
print(ch, end=" ") # N O H T Y P
# Negative step — only for numeric ranges
for i in range(5, 0, -1):
print(i, end=" ") # 5 4 3 2 1🎯 Interview Questions
Q1: Python में for loop internally कैसे काम करता है?
Answer: Python का for loop iterator protocol use करता है। Internally यह steps follow करता है:
iter()call होता है sequence पर — एक iterator object मिलता है- हर iteration में
next()call होता है — अगला element मिलता है - जब elements खत्म हो जाते हैं,
StopIterationexception raise होता है - Python यह exception catch करके loop terminate कर देता है
Q2: range() object memory efficient क्यों है?
Answer: range() एक lazy sequence है — यह सभी numbers एक साथ memory में store नहीं करता। यह सिर्फ start, stop, step store करता है और demand पर numbers generate करता है। इसीलिए range(109) भी minimal memory लेता है, जबकि list(range(109)) GB memory लेगा।
Q3: List comprehension vs map() + lambda — कौन better है?
Answer: List comprehension ज़्यादातर cases में readable और fast है:
Performance: दोनों similar हैं, लेकिन comprehension slightly faster है क्योंकि lambda function call overhead नहीं होता।
Q4: Nested loop में break सिर्फ inner loop तोड़ता है — outer loop कैसे तोड़ें?
Answer: Python में nested break के लिए multiple approaches हैं:
# Approach 1: Flag variable
found = False
for i in range(10):
for j in range(10):
if i * j == 42:
found = True
break
if found:
break
# Approach 2: Function + return (cleanest)
def find_pair():
for i in range(10):
for j in range(10):
if i * j == 42:
return (i, j)
return None
# Approach 3: itertools.product
from itertools import product
for i, j in product(range(10), range(10)):
if i * j == 42:
print(f"Found: {i}, {j}")
breakQ5: enumerate() का start parameter कब useful होता है?
Answer: जब numbering 0 से नहीं, custom number से शुरू करनी हो — जैसे line numbers, serial numbers, question numbers:
Q6: for loop variable का scope क्या है Python में?
Answer: Python में for loop variable loop के बाद भी accessible रहता है (last assigned value hold करता है)। यह C/Java से different है जहाँ loop variable loop के बाहर exist नहीं करता:
for i in range(5):
pass
print(i) # Output: 4 — variable still exists!
# ⚠️ But if loop doesn't execute (empty sequence):
# for i in range(0):
# pass
# print(i) # NameError — i never assigned!Q7: Generator expression vs List comprehension — कब क्या use करें?
Answer: Generator expression lazy evaluation करता है (memory efficient), list comprehension eager है (सब एक बार बनाता है):
Q8: itertools module से for loop को कैसे supercharge करें?
Answer: itertools provides powerful loop utilities:
Q9: Performance — for loop vs vectorized operations (NumPy)?
Answer: Pure Python for loop large data पर slow है compared to NumPy:
Rule: Data processing/math operations → NumPy। Logic/control flow → for loop।
Q10: Real interview coding question — Find duplicates in a list using for loop?
Answer:
Duplicates: [1, 3, 5]
Time Complexity: O(n) — set lookup O(1) है, single pass loop। Space Complexity: O(n) — worst case सभी elements store।
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for For Loop in Python.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Python Master Course topic.
Search Terms
python-master-course, python master course, python, master, course, control, flow, for
Related Python Master Course Topics