Python Notes
Master Python loop control statements — break, continue, and pass. Learn how to exit loops early, skip iterations, and use placeholder statements with real examples, flow diagrams, and Hindi explanations.
Introduction (परिचय)
Python में तीन loop control statements हैं:
| Statement | काम | उपयोग |
|---|---|---|
break | Loop को तुरंत बंद करता है | जब target मिल जाए |
continue | Current iteration skip करता है | जब कोई step छोड़नी हो |
pass | कुछ नहीं करता (placeholder) | Empty block के लिए |
Break in For Loop
Output:
Break in While Loop
# Ask until correct answer
secret = "python"
attempts = 0
while True:
guess = input("Guess the word: ").lower()
attempts += 1
if guess == secret:
print(f"✓ Correct in {attempts} attempts!")
break
else:
print(f"✗ Wrong! Try again.")
if attempts >= 3:
print(f"Answer was: {secret}")
breakBreak with Search
Output: Found 29 at index 4 ✓
Break in Nested Loops
# Break only exits the INNERMOST loop
for i in range(1, 4):
print(f"Outer loop i={i}")
for j in range(1, 4):
if j == 2:
print(f" Breaking inner loop at j={j}")
break # Only breaks inner loop
print(f" Inner loop j={j}")
print(f" (Inner loop ended, outer continues)")Output:
Note: break केवल उस loop को बंद करता है जिसके अंदर वह है।Break — For-Else Pattern
# else runs ONLY if break was NOT triggered
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
break # Not prime
else:
return True # No break happened → prime
return False
for num in range(2, 20):
if is_prime(num):
print(f"{num} is prime", end=" ")
print()Output: 2 is prime 3 is prime 5 is prime 7 is prime 11 is prime 13 is prime 17 is prime 19 is prime
2. CONTINUE Statement
क्या करता है?
continue current iteration को skip करता है और अगली iteration पर चला जाता है।
Flow Diagram
Syntax
for/while ...:
if condition:
continue # skip rest, go to next iteration
# this part is skipped when continue executes
rest_of_codeContinue in For Loop
# Print only odd numbers (skip even)
for i in range(1, 11):
if i % 2 == 0:
continue # skip even numbers
print(i, end=" ")
print()Output: 1 3 5 7 9
Continue — Skip Specific Values
# Print numbers but skip multiples of 3
for i in range(1, 16):
if i % 3 == 0:
print(f" (skipping {i})")
continue
print(f" → {i}")Output:
Continue in While Loop
Output:
| Added 10, running total | 10 |
| Skipping invalid | -5 |
| Skipping invalid | 0 |
| Added 7, running total | 17 |
| Skipping invalid | -3 |
| Added 15, running total | 32 |
| Added 2, running total | 34 |
| Skipping invalid | -1 |
| Added 8, running total | 42 |
| Sum of positive numbers | 42 |
| Count | 5 |
| Average | 8.40 |
Continue — Real World: Grade Filter
Output:
| Rahul: 85 | Grade A |
| Priya: 28 | FAIL (skipped) |
| Amit: 72 | Grade B |
| Neha: 15 | FAIL (skipped) |
| Sita: 91 | Grade A |
| Ravi: 45 | Grade C |
| Total passed | 4/6 |
3. PASS Statement
क्या करता है?
pass कुछ नहीं करता! यह एक placeholder है। Python में empty blocks allowed नहीं हैं, इसलिए pass use होता है।
When to Use (कब उपयोग करें?)
- Empty function body
- Empty class body
- Empty if/elif/else block
- Future code placeholder
Syntax
if condition:
pass # do nothing for nowPass in If Statement
x = 15
if x > 10:
pass # TODO: add code later
else:
print("x is 10 or less")
print("Program continues...")Output: Program continues...
Pass in Functions (placeholder)
# Write function signature first, fill later
def calculate_tax():
pass # TODO: implement tax calculation
def send_email():
pass # TODO: implement email sending
def generate_report():
pass # TODO: implement report generation
# These don't crash — pass keeps them valid
print("All functions defined (but empty)")
calculate_tax() # No error, no output
send_email() # No error, no outputPass in Loops
# Count items but do nothing with even numbers
for i in range(1, 6):
if i % 2 == 0:
pass # even numbers — do nothing
else:
print(f"Odd: {i}")Output:
| Odd | 1 |
| Odd | 3 |
| Odd | 5 |
Pass in Class (OOP placeholder)
class Animal:
pass # Empty class — add attributes later
class Vehicle:
pass # Placeholder class
# Valid class objects
dog = Animal()
car = Vehicle()
print(type(dog)) # <class '__main__.Animal'>Comparing All Three (तीनों की तुलना)
print("=== Loop with 1 to 10 ===\n")
print("BREAK — stops at 5:")
for i in range(1, 11):
if i == 5:
break
print(i, end=" ")
print()
print("\nCONTINUE — skips 5:")
for i in range(1, 11):
if i == 5:
continue
print(i, end=" ")
print()
print("\nPASS — does nothing at 5:")
for i in range(1, 11):
if i == 5:
pass
print(i, end=" ")
print()Output:
Real-World Application Programs
Program 1: Shopping Cart Filter
Program 2: Smart Input Validator
valid_numbers = []
max_count = 5
print(f"Enter {max_count} positive integers (type 'stop' to quit early):\n")
while len(valid_numbers) < max_count:
user_input = input(f"Enter number {len(valid_numbers)+1}: ")
if user_input.lower() == "stop":
print("Early exit!")
break
if not user_input.isdigit():
print(" ✗ Not a valid number. Try again.")
continue
num = int(user_input)
if num <= 0:
print(" ✗ Must be positive. Try again.")
continue
valid_numbers.append(num)
print(f" ✓ Added {num}")
print(f"\nValid numbers: {valid_numbers}")
if valid_numbers:
print(f"Sum: {sum(valid_numbers)}")
print(f"Average: {sum(valid_numbers)/len(valid_numbers):.2f}")Program 3: Menu-Driven Program
data = []
while True:
print("\n=== Data Manager ===")
print("1. Add item")
print("2. View items")
print("3. Remove item")
print("4. Clear all")
print("5. Exit")
choice = input("Choice: ").strip()
if not choice.isdigit():
print("Invalid input!")
continue
choice = int(choice)
if choice == 1:
item = input("Enter item: ").strip()
if not item:
print("Empty item not allowed!")
continue
data.append(item)
print(f"'{item}' added.")
elif choice == 2:
if not data:
print("List is empty!")
pass
else:
for i, item in enumerate(data, 1):
print(f" {i}. {item}")
elif choice == 3:
if not data:
print("Nothing to remove!")
continue
for i, item in enumerate(data, 1):
print(f" {i}. {item}")
idx = int(input("Remove item number: ")) - 1
if 0 <= idx < len(data):
removed = data.pop(idx)
print(f"Removed: '{removed}'")
else:
print("Invalid number!")
elif choice == 4:
data.clear()
print("All items cleared!")
elif choice == 5:
print("Goodbye! 👋")
break
else:
print("Invalid choice! Enter 1-5")Common Mistakes (सामान्य गलतियाँ)
❌ Mistake 1: break/continue outside loop
# WRONG — break/continue only work inside loops
x = 5
if x > 3:
break # SyntaxError!
# CORRECT — use inside a loop
for i in range(10):
if i > 3:
break❌ Mistake 2: Using pass when something needed
# BAD — silently doing nothing
try:
result = 10 / 0
except ZeroDivisionError:
pass # Hiding the error! Bad practice
# BETTER — log or handle
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
result = None❌ Mistake 3: break in wrong loop
# WRONG expectation — break only exits inner loop
found = False
for i in range(5):
for j in range(5):
if i == 2 and j == 2:
found = True
break # Only breaks inner loop, outer continues!
# Need to also break outer loop!
if found:
break
# BETTER — use flag❌ Mistake 4: Continue logic error
Practice Exercises (अभ्यास प्रश्न)
Exercise 1
Print numbers 1 to 50. Skip multiples of both 3 and 5.
Exercise 2
Take numbers from user until they enter 0. Print the sum.
Exercise 3
Search for a name in a list. Stop as soon as found.
Exercise 4
Print prime numbers between 1 and 100. *(Use continue to skip non-primes)*
Exercise 5
Write a guessing game. Stop after 5 wrong guesses (break).
Solutions (हल)
Solution 1
for i in range(1, 51):
if i % 3 == 0 and i % 5 == 0:
continue
print(i, end=" ")
print()Solution 2
total = 0
while True:
n = int(input("Enter number (0 to stop): "))
if n == 0:
break
total += n
print(f"Sum: {total}")Solution 4 — Primes with continue
for n in range(2, 101):
is_prime = True
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
is_prime = False
break
if not is_prime:
continue
print(n, end=" ")
print()Quick Reference Card (त्वरित संदर्भ)
Next Topic (अगला विषय)
➡️ Pattern Programs — Loops का जादू: Star, Number & Diamond Patterns
⚠️ Common Mistakes (Advanced)
यहाँ कुछ और common mistakes हैं जो beginners अक्सर करते हैं:
❌ Mistake 5: Infinite loop with continue
# WRONG — continue prevents counter update, infinite loop!
i = 0
while i < 10:
if i == 5:
continue # i never becomes 6, loop runs forever!
print(i)
i += 10 1 2 3 4 ... (infinite loop — program hangs!)
# CORRECT — increment BEFORE continue
i = 0
while i < 10:
if i == 5:
i += 1 # increment first!
continue
print(i)
i += 10 1 2 3 4 6 7 8 9
❌ Mistake 6: Using pass instead of continue
# WRONG — pass does nothing, code below still runs!
for i in range(5):
if i == 3:
pass # This does NOT skip — next line still prints!
print(i)0 1 2 3 4
# CORRECT — use continue to actually skip
for i in range(5):
if i == 3:
continue # This SKIPS to next iteration
print(i)0 1 2 4
❌ Mistake 7: Forgetting that for-else runs when break is NOT triggered
# CONFUSING — else runs when loop completes WITHOUT break
for i in range(5):
if i == 10: # Never true
break
else:
print("Loop completed without break!") # This WILL run
# Many beginners think else runs when break happens — opposite है!Loop completed without break!
✅ Key Takeaways
- 🔴
breakloop को तुरंत बंद कर देता है — बाकी iterations execute नहीं होतीं - 🟡
continuecurrent iteration skip करके अगली iteration पर jump करता है - ⚪
passएक placeholder है — कुछ नहीं करता, syntax error से बचाता है - 🎯
breakसिर्फ innermost loop को बंद करता है, outer loops चलते रहते हैं - 🔄
for-elsepattern:elseblock तभी run होता है जबbreaktrigger नहीं हुआ - ⚠️
whileloop मेंcontinueuse करते समय counter increment break से पहले करो, वरना infinite loop! - 🧠
passऔरcontinuesame नहीं हैं —passcode flow रोकता नहीं,continueskip करता है - 💡
break+ flag variable = nested loops से safely बाहर निकलने का तरीका - 📌
break/continueसिर्फ loops के अंदर काम करते हैं — if block में अकेले use करने पर SyntaxError! - 🚀 Real-world में:
breakfor search,continuefor filtering,passfor scaffolding
❓ FAQ
Q1: break और return में क्या difference है?
Answer: break सिर्फ loop को बंद करता है और loop के बाद का code run होता है। return पूरी function से बाहर निकल जाता है — function में loop के बाद कोई code run नहीं होता।
Q2: क्या हम break को loop के बाहर use कर सकते हैं?
Answer: नहीं! ❌ break और continue सिर्फ loops (for/while) के अंदर valid हैं। बाहर use करने पर SyntaxError: 'break' outside loop मिलता है।
Q3: pass और continue में क्या difference है?
Answer: pass literally कुछ नहीं करता — अगली line normally execute होती है। continue current iteration skip करता है और directly अगली iteration पर jump करता है। Example: loop body में pass के बाद print statement run होगा, लेकिन continue के बाद नहीं।
Q4: Nested loops में outer loop को कैसे break करें?
Answer: Python में directly outer loop break नहीं कर सकते। Flag variable use करें:
found = False
for i in range(5):
for j in range(5):
if i == 2 and j == 3:
found = True
break
if found:
breakया फिर पूरे nested loop को function में wrap करके return use करें।
Q5: for-else में else कब execute होता है?
Answer: else block तब execute होता है जब loop normally complete होता है — यानी break trigger नहीं हुआ। अगर break execute हुआ तो else skip हो जाता है। यह searching pattern में बहुत useful है।
Q6: क्या pass को production code में use करना चाहिए?
Answer: pass primarily development phase में placeholder के रूप में use होता है। Production code में इसे proper implementation से replace करना चाहिए। Exception handling में pass use करना (error silently ignore करना) generally bad practice है।
Q7: while True + break pattern safe है?
Answer: हाँ! यह एक common और accepted pattern है — menu-driven programs, input validation, और game loops में widely use होता है। बस ensure करें कि break condition ज़रूर reach हो, वरना infinite loop बन जाएगा।
Q8: continue while loop में काम करता है for loop से differently?
Answer: Logic same है — दोनों में current iteration skip होती है। लेकिन while loop में counter manually increment करना पड़ता है continue से पहले, वरना infinite loop बन सकती है। for loop में iterator automatically next value लेता है।
🎯 Interview Questions
Q1: break, continue, और pass में क्या difference है? Example दो।
Answer:
break— Loop immediately terminate करता है। Loop के बाद का code execute होता है।continue— Current iteration skip करता है, अगली iteration शुरू होती है।pass— No operation (NOP)। कुछ नहीं करता, placeholder है।
for i in range(1, 6):
if i == 3: break # Output: 1 2
for i in range(1, 6):
if i == 3: continue # Output: 1 2 4 5
for i in range(1, 6):
if i == 3: pass # Output: 1 2 3 4 5Q2: Nested loop में break कैसे behave करता है?
Answer: break सिर्फ innermost loop को terminate करता है जिसके अंदर वह है। Outer loop unaffected रहता है। अगर outer loop भी break करना है, तो flag variable या function + return approach use करें।
Q3: for-else construct को explain करो। यह कब useful है?
Answer: Python में for-else में else block तब execute होता है जब loop बिना break complete हो। यह search operations में useful है — अगर item मिल गया तो break, नहीं मिला तो else block "not found" handle करता है।
for item in data:
if item == target:
print("Found!")
break
else:
print("Not found!") # Only if break never executedQ4: while True infinite loop + break pattern कब use करते हैं?
Answer: जब loop exit condition loop body के बीच में आती है (न शुरू में, न अंत में)। Common uses: user input validation, menu-driven programs, server listening loops, और retry mechanisms।
Q5: continue while loop में infinite loop कैसे cause कर सकता है?
Answer: अगर continue counter increment statement से पहले execute हो, तो counter कभी update नहीं होता और condition हमेशा True रहती है:
i = 0
while i < 5:
if i == 3:
continue # i stays 3 forever!
i += 1Fix: Counter increment continue से पहले करें।
Q6: pass statement कब necessary है? बिना pass के क्या होता है?
Answer: Python empty blocks allow नहीं करता। अगर if, for, while, def, या class body empty छोड़ दें तो IndentationError आता है। pass एक valid statement है जो syntactically block को complete करता है:
def future_function():
pass # Without this: IndentationErrorQ7: break को try-except-finally block में use करें तो क्या होता है?
Answer: अगर break try block के अंदर loop में है, तो finally block पहले execute होता है, फिर loop break होता है। finally हमेशा run होता है, चाहे break हो या न हो।
for i in range(5):
try:
if i == 3:
break
finally:
print(f"Finally: {i}") # Prints for i=0,1,2,3Q8: break vs sys.exit() vs return — तीनों में difference बताओ।
Answer:
| Statement | Scope | Effect |
|---|---|---|
break | Current loop only | Loop exit, code after loop continues |
return | Current function | Function exit, returns value to caller |
sys.exit() | Entire program | Program terminate (raises SystemExit) |
Q9: Real project में continue का best use case क्या है?
Answer: Data filtering/validation — जब large dataset process कर रहे हों और invalid entries skip करनी हों। यह code readability improve करता है क्योंकि "early rejection" pattern nested if-else से cleaner है:
for record in database_records:
if not record.is_valid():
continue
if record.is_duplicate():
continue
# Process only valid, unique records
process(record)Q10: Python में labeled break (like Java) क्यों नहीं है? Alternative क्या है?
Answer: Python's philosophy "There should be one obvious way to do it" — labeled breaks add complexity। Alternatives:
- Flag variable — boolean set करके outer loop check करे
- Function + return — nested loops को function में wrap करो
- itertools.product() — nested loops flatten करो
- Exception (rare) — custom exception raise करके both loops exit
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Break, Continue and Pass 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, break
Related Python Master Course Topics