Python Notes
Learn Python while loop — condition-based iteration, infinite loops, loop counters, do-while simulation, and real-world programs. Complete guide with Hindi explanations, flow diagrams, and practice exercises.
Introduction (परिचय)
while loop उस समय use होता है जब हमें जब तक condition True हो, तब तक code को repeat करना हो।
Real-Life Analogy: `` "जब तक भूख लगी है — खाते रहो" 🍽️ "जब तक fuel है — गाड़ी चलती रहेगी" 🚗 "जब तक game over नहीं — खेलते रहो" 🎮 ``Flow Diagram (प्रवाह आरेख)
Basic Examples (बुनियादी उदाहरण)
Example 1: Counting (गिनती)
count = 1
while count <= 5:
print(f"Count: {count}")
count += 1 # count को update करना जरूरी है
print("Done!")Output:
| Count | 1 |
| Count | 2 |
| Count | 3 |
| Count | 4 |
| Count | 5 |
Example 2: Sum of N Numbers
n = int(input("Enter N: "))
i = 1
total = 0
while i <= n:
total += i
i += 1
print(f"Sum of 1 to {n} = {total}")Output (n=10):
Example 3: Reverse Counting
i = 10
while i >= 1:
print(i, end=" ")
i -= 1
print("\nBlast Off! 🚀")Output: 10 9 8 7 6 5 4 3 2 1 Blast Off! 🚀
Example 4: Multiplication Table
n = int(input("Enter number: "))
i = 1
print(f"\n=== Table of {n} ===")
while i <= 10:
print(f"{n} × {i:2d} = {n*i:3d}")
i += 1Output (n=5):
While vs For Loop (तुलना)
# Same task — two ways
# FOR loop
for i in range(1, 6):
print(i)
# WHILE loop
i = 1
while i <= 5:
print(i)
i += 1Practical Programs (व्यावहारिक कार्यक्रम)
Program 1: Number Guessing Game 🎮
import random
secret = random.randint(1, 100)
attempts = 0
max_attempts = 7
print("=== Number Guessing Game ===")
print(f"Guess a number between 1 and 100")
print(f"You have {max_attempts} attempts!")
while attempts < max_attempts:
guess = int(input(f"\nAttempt {attempts + 1}: Enter your guess: "))
attempts += 1
if guess == secret:
print(f"\n🎉 Correct! You won in {attempts} attempt(s)!")
print(f"बधाई! आपने {attempts} प्रयास में सही अनुमान लगाया!")
break
elif guess < secret:
remaining = max_attempts - attempts
print(f"📈 Too low! Try higher. ({remaining} attempts left)")
else:
remaining = max_attempts - attempts
print(f"📉 Too high! Try lower. ({remaining} attempts left)")
else:
print(f"\n💀 Game Over! The number was {secret}")
print(f"Game over! सही संख्या {secret} थी।")Program 2: ATM Machine Simulation 🏧
balance = 10000
pin = "1234"
attempts = 0
max_pin_attempts = 3
print("=== ATM Machine ===")
# PIN verification
while attempts < max_pin_attempts:
entered_pin = input("Enter PIN: ")
attempts += 1
if entered_pin == pin:
print("✓ PIN Correct\n")
break
else:
remaining = max_pin_attempts - attempts
if remaining > 0:
print(f"✗ Wrong PIN. {remaining} attempts remaining.")
else:
print("❌ Card Blocked! 3 wrong PIN attempts.")
print("आपका कार्ड ब्लॉक हो गया है!")
exit()
# Main ATM menu
while True:
print(f"\nBalance: ₹{balance}")
print("1. Withdraw")
print("2. Deposit")
print("3. Check Balance")
print("4. Exit")
choice = input("Enter choice: ")
if choice == "1":
amount = int(input("Enter amount to withdraw: ₹"))
if amount <= 0:
print("Invalid amount!")
elif amount > balance:
print("Insufficient balance!")
print("अपर्याप्त राशि!")
elif amount % 100 != 0:
print("Amount must be in multiples of 100")
else:
balance -= amount
print(f"✓ ₹{amount} dispensed. New balance: ₹{balance}")
elif choice == "2":
amount = int(input("Enter amount to deposit: ₹"))
if amount <= 0:
print("Invalid amount!")
else:
balance += amount
print(f"✓ ₹{amount} deposited. New balance: ₹{balance}")
elif choice == "3":
print(f"Current Balance: ₹{balance}")
elif choice == "4":
print("Thank you for using ATM! 🙏")
print("ATM का उपयोग करने के लिए धन्यवाद!")
break
else:
print("Invalid choice! Please enter 1-4")Program 3: Password Validator
import re
print("=== Create Strong Password ===")
print("Requirements:")
print(" • Minimum 8 characters")
print(" • At least 1 uppercase letter")
print(" • At least 1 digit")
print(" • At least 1 special character (@#$!%)")
while True:
password = input("\nEnter password: ")
errors = []
if len(password) < 8:
errors.append("❌ Too short (min 8 chars)")
if not any(c.isupper() for c in password):
errors.append("❌ Need at least 1 uppercase letter")
if not any(c.isdigit() for c in password):
errors.append("❌ Need at least 1 digit")
if not any(c in "@#$!%" for c in password):
errors.append("❌ Need at least 1 special char (@#$!%)")
if errors:
print("Password is WEAK:")
for err in errors:
print(f" {err}")
print("Please try again...")
else:
print("✅ Strong Password! Password set successfully.")
print("✅ मजबूत पासवर्ड! सफलतापूर्वक सेट हो गया।")
breakProgram 4: Digital Scoreboard (Cricket)
print("=== Cricket Score Tracker ===")
team = input("Enter team name: ")
overs = int(input("How many overs? "))
total_runs = 0
total_wickets = 0
current_over = 1
while current_over <= overs and total_wickets < 10:
print(f"\n--- Over {current_over} ---")
over_runs = 0
for ball in range(1, 7):
if total_wickets >= 10:
break
delivery = input(f" Ball {ball}: (runs 0-6, W for wicket): ").upper()
if delivery == "W":
total_wickets += 1
print(f" Wicket! Total wickets: {total_wickets}")
elif delivery.isdigit() and 0 <= int(delivery) <= 6:
runs = int(delivery)
over_runs += runs
total_runs += runs
else:
print(" Invalid input, counted as dot ball")
print(f" Over {current_over} runs: {over_runs}")
print(f" Score: {total_runs}/{total_wickets}")
current_over += 1
print(f"\n=== Final Score ===")
print(f"{team}: {total_runs}/{total_wickets}")
print(f"Overs played: {current_over - 1}")While with break and continue
Using break
print("Find first multiple of 7 after 50:")
n = 51
while n < 200:
if n % 7 == 0:
print(f"Found: {n}")
break
n += 1Output: Found: 56
Using continue
print("Numbers from 1-20, skipping multiples of 3:")
i = 0
while i < 20:
i += 1
if i % 3 == 0:
continue # skip multiples of 3
print(i, end=" ")
print()Output: 1 2 4 5 7 8 10 11 13 14 16 17 19 20
Infinite Loop — Controlled (अनंत लूप — नियंत्रित)
# Intentional infinite loop with break condition
print("Type 'quit' to exit")
while True: # Always true — runs forever until break
user_input = input("You: ")
if user_input.lower() == "quit":
print("Goodbye! 👋")
break
elif user_input.lower() == "hello":
print("Bot: Hello! How are you?")
else:
print(f"Bot: You said '{user_input}'")Do-While Simulation in Python (do-while जैसा)
Python में do-while नहीं है, लेकिन simulate कर सकते हैं:
# Do-While pattern — runs at least once
while True:
number = int(input("Enter a positive number: "))
if number > 0:
break # condition met — exit
print("Please enter a positive number!")
print(f"You entered: {number}")While-Else Construct
# else runs when while condition becomes False (no break)
n = 2
while n < 10:
if n % 7 == 0:
print(f"{n} is divisible by 7!")
break
n += 1
else:
print("No number divisible by 7 found in range")Output: 7 is divisible by 7!
Common Mistakes (सामान्य गलतियाँ)
❌ Mistake 1: Infinite Loop (अनंत लूप)
# WRONG — counter never changes → infinite loop!
count = 1
while count <= 5:
print(count)
# FORGOT: count += 1
# CORRECT
count = 1
while count <= 5:
print(count)
count += 1 # Always update the counter!❌ Mistake 2: Wrong Initial Value
# WRONG — starts at 0, goes up to 4, prints 0-4
i = 0
while i < 5:
print(i)
i += 1
# Output: 0 1 2 3 4
# If you want 1-5:
i = 1
while i <= 5:
print(i)
i += 1❌ Mistake 3: Off-by-One Error
# Print 1 to 10
# WRONG — only prints 1 to 9
i = 1
while i < 10: # should be <= 10
print(i)
i += 1
# CORRECT
i = 1
while i <= 10:
print(i)
i += 1❌ Mistake 4: Updating Wrong Variable
x = 10
y = 1
# WRONG — updating y, but condition checks x!
while x > 0:
print(x)
y -= 1 # This doesn't affect x → infinite loop!
# CORRECT
while x > 0:
print(x)
x -= 1 # Must update xPractice Exercises (अभ्यास प्रश्न)
Exercise 1 — Reverse Digits
Reverse the digits of a number using while loop. *(e.g., 1234 → 4321)*
Exercise 2 — GCD Calculator
Find GCD of two numbers using Euclidean algorithm. *(Hint: while b != 0: a, b = b, a % b)*
Exercise 3 — Digital Root
Keep summing digits until single digit. *(e.g., 9875 → 9+8+7+5=29 → 2+9=11 → 1+1=2)*
Exercise 4 — Collatz Conjecture
Start with any positive integer:
- If even: divide by 2
- If odd: multiply by 3 and add 1
- Repeat until you reach 1
Exercise 5 — Simple Interest Calculator
Take principal, rate, and target amount. Calculate how many years to reach target.
Solutions (हल)
Solution 1 — Reverse Digits
num = int(input("Enter a number: "))
original = num
reversed_num = 0
while num > 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num //= 10
print(f"Reversed: {reversed_num}")Solution 2 — GCD
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
original_a, original_b = a, b
while b != 0:
a, b = b, a % b
print(f"GCD of {original_a} and {original_b} = {a}")Solution 4 — Collatz
n = int(input("Enter a positive integer: "))
steps = 0
print(n, end=" → ")
while n != 1:
if n % 2 == 0:
n //= 2
else:
n = 3 * n + 1
print(n, end=" → " if n != 1 else "")
steps += 1
print(f"\nReached 1 in {steps} steps!")Summary (सारांश)
| Aspect | Details |
|---|---|
| Syntax | while condition: |
| Runs when | Condition is True |
| Stops when | Condition is False or break |
| Must have | Counter/condition update |
| Infinite loop | while True: with break |
| While-else | else runs if no break |
WHILE LOOP CHECKLIST:
□ Initial value set?
□ Condition correct?
□ Counter/variable updated inside loop?
□ No infinite loop risk?
□ Break condition present (if infinite loop pattern)?Next Topic (अगला विषय)
➡️ Break, Continue & Pass — Loop control statements
✅ Key Takeaways
- 🔁
whileloop condition-based loop है — जब तक conditionTrueहै, loop चलता रहेगा - 🔢 Loop body में counter/variable को update करना अनिवार्य है, वरना infinite loop बन जाएगा
- 🎯
while True:+breakpattern का use करो जब exact iterations पता ना हो (menu-driven programs, input validation) - 🚫
forloop fixed iterations के लिए best है,whileloop dynamic/unknown iterations के लिए — सही loop choose करो - 🔀
breakloop तुरंत terminate करता है,continuecurrent iteration skip करके next पर जाता है - 📦
while-elseconstruct मेंelseblock तभी execute होता है जब loop normally end हो (बिनाbreakके) - ⚠️ Off-by-one errors सबसे common mistake है —
<vs<=carefully check करो - 🧪 Python में
do-whileनहीं है, लेकिनwhile True:+breakसे simulate कर सकते हो — कम से कम एक बार execute guaranteed - 🛡️ Infinite loop intentional हो तो ठीक है (servers, games), लेकिन accidental infinite loop program crash करवा सकता है
- 💡 Real-world applications: ATM machines, login systems, game loops, data validation — सभी
whileloop पर based हैं
❓ FAQ
Q1: while loop और for loop में क्या difference है? कब कौन सा use करें?
Answer: for loop तब use करते हैं जब iterations की संख्या पहले से पता हो (जैसे list iterate करना, range(10))। while loop तब use करते हैं जब condition-based repetition चाहिए और iterations unknown हों (जैसे user जब तक "quit" ना type करे)। Rule of thumb: अगर range() या sequence है तो for, अगर condition check करनी है तो while। 🎯
Q2: Infinite loop accidentally बन जाए तो कैसे रोकें?
Answer: Program run हो रहा हो तो Ctrl + C (KeyboardInterrupt) press करो — loop तुरंत terminate हो जाएगा। Prevention के लिए: हमेशा loop body में condition variable update करो, और safety limit (max iterations) रखो। Example:
max_iterations = 1000
count = 0
while condition and count < max_iterations:
# logic
count += 1Q3: while True: dangerous है क्या? कब use करना safe है?
Answer: while True: itself dangerous नहीं है — बिना break condition के dangerous है! ✅ Safe use cases: menu-driven programs, servers, game loops, input validation — जहाँ explicit break condition define की हो। ❌ Dangerous: जब break condition unreachable हो या गलत logic से कभी True ना बने।
Q4: while-else का practical use क्या है?
Answer: while-else में else block तब execute होता है जब loop normally terminate हो (condition False हो)। अगर break से exit हुआ तो else skip हो जाता है। Practical use: searching algorithms — अगर element मिल गया (break), तो else skip; अगर पूरा loop चला और नहीं मिला, तो else में "not found" print करो। 🔍
Q5: Python में do-while loop क्यों नहीं है?
Answer: Python की philosophy है "There should be one obvious way to do it." do-while को while True: + break pattern से easily simulate कर सकते हैं, इसलिए separate keyword की जरूरत नहीं। यह pattern equally readable और more flexible है। Python simplicity पसंद करता है! 🐍
Q6: Nested while loops कैसे काम करते हैं?
Answer: Nested while loop मतलब एक while loop के अंदर दूसरा while loop। Outer loop की हर iteration में inner loop पूरा चलता है। Example:
i = 1
while i <= 3:
j = 1
while j <= 3:
print(f"({i},{j})", end=" ")
j += 1
print()
i += 1(1,1) (1,2) (1,3) (2,1) (2,2) (2,3) (3,1) (3,2) (3,3)
⚠️ ध्यान रखो: nested loops में दोनों counters properly update हों!
Q7: while loop में pass statement का क्या role है?
Answer: pass एक placeholder statement है — कुछ नहीं करता। जब आपको loop structure बनानी हो लेकिन body अभी खाली रखनी हो (TODO), तो pass use करो। बिना pass के empty loop syntax error देगा:
while condition:
pass # TODO: implement laterQ8: while loop की performance for loop से कम क्यों होती है?
Answer: Python में for loop internally optimized है — range() object C-level iteration use करता है। while loop में हर iteration पर condition evaluation + manual counter increment होता है जो slightly slower है। लेकिन practical difference negligible है — readability और correctness ज़्यादा important है performance से! ⚡
🎯 Interview Questions
Q1: What is the difference between while loop and for loop in Python?
Answer: for loop iterates over a sequence (list, range, string) with a known number of iterations. while loop runs based on a condition and is used when iterations are unknown or dynamic. for is preferred for definite iteration, while for indefinite iteration. Both can achieve the same result, but choosing the right one improves readability.
Q2: How do you avoid an infinite loop in Python?
Answer: To avoid infinite loops: (1) Always update the loop control variable inside the body, (2) Ensure the condition will eventually become False, (3) Add a safety counter as a fallback (max_iterations), (4) Use break with a clear exit condition in while True: patterns. Debugging tip: add print() statements to track variable values during development.
Q3: Explain the while-else construct with an example.
Answer: In while-else, the else block executes only when the while condition becomes False naturally — NOT when the loop is terminated by break. Use case: searching for an element — if found, break (else skips); if not found, loop completes normally and else executes with "not found" message. This eliminates the need for a separate flag variable.
n = 10
while n > 0:
if n == 5:
print("Found 5!")
break
n -= 1
else:
print("5 not found") # Won't execute because break was hitQ4: How would you simulate a do-while loop in Python?
Answer: Python doesn't have a native do-while loop. Simulate it using while True: with a break at the end based on the exit condition. This guarantees the body executes at least once before checking the condition:
while True:
data = input("Enter value: ")
if validate(data):
break # Exit only when validQ5: What happens if you use continue in a while loop without updating the counter before it?
Answer: This creates an infinite loop! When continue is hit, it jumps back to the condition check without executing the remaining body (including the counter update). Always place the counter increment before the continue statement:
# WRONG — infinite loop when i=3
i = 0
while i < 10:
if i == 3:
continue # i never increments past 3!
print(i)
i += 1
# CORRECT
i = 0
while i < 10:
i += 1 # Update BEFORE continue
if i == 3:
continue
print(i)Q6: Can a while loop have multiple conditions? How?
Answer: Yes! Use logical operators (and, or, not) to combine multiple conditions:
attempts = 0
logged_in = False
while attempts < 3 and not logged_in:
# login logic
attempts += 1The loop continues only when all and conditions are True or any or condition is True. Order matters for short-circuit evaluation.
Q7: What is the time complexity of a while loop?
Answer: The time complexity depends on how many times the loop executes. A simple counter loop while i < n is O(n). Nested while loops can be O(n²). A loop that halves a value each iteration (n //= 2) is O(log n). The key factor is: how does the loop control variable change relative to the termination condition?
Q8: How do while loops work with mutable data structures?
Answer: while loops are useful for processing data structures that change size during iteration (e.g., stacks, queues) — something for loops can't safely do:
This is preferred over for because the list size changes each iteration. while handles dynamic collections elegantly.
Q9: What is a sentinel-controlled while loop?
Answer: A sentinel-controlled loop uses a special value (sentinel) to signal termination, rather than a counter. Common in input processing:
total = 0
num = int(input("Enter number (-1 to stop): "))
while num != -1: # -1 is the sentinel value
total += num
num = int(input("Enter number (-1 to stop): "))
print(f"Total: {total}")The sentinel value (-1 here) is never processed — it only signals the end of input.
Q10: Compare the memory usage of while vs for with range().
Answer: Both are memory-efficient for iteration. range() in Python 3 is a lazy generator — it doesn't create all numbers in memory. Similarly, while with a counter uses constant O(1) extra memory. The difference is negligible. However, if you convert range to a list (list(range(n))), it uses O(n) memory. For pure iteration, both while and for range() are O(1) space.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for While 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, while
Related Python Master Course Topics