Control Statements
Python mein program ka flow kaise control karte hain — if/else se decisions lo, loops se kaam repeat karo!
Introduction to Control Statements
3 types ke control statements hote hain:
🔀 Decision Making
if, elif, else — condition ke basis par decide karo ki kya karna hai
🔄 Loops
while, for — code ko baar baar repeat karo jab tak zaroorat ho
⚡ Jump
break, continue — loop ke flow ko control karo
Real life example: Jaise traffic signal par — 🟢 Green = Jao, 🔴 Red = Ruko, 🟡 Yellow = Dhire. Python mein bhi aisi decisions if-else se lete hain!
Simple if Statement
Syntax: if condition: ke baad indented code likho.
# Example 1: Positive number check
number = 10
if number > 0:
print(f"{number} positive hai!") # ✅ Ye chalega
# Example 2: Age check
age = 20
if age >= 18:
print("Aap adult ho!") # ✅ Ye bhi chalega
# Example 3: Empty string check
text = ""
if not text:
print("String khaali hai!") # ✅ Empty string = False0, "" (empty string), [] (empty list), None — ye sab False maane jaate hain. Baaki sab True hai!if-else Statement
# Even ya Odd check karo
number = 15
if number % 2 == 0: # Kya remainder 0 hai?
print(f"{number} Even hai") # ← Nahi chalega
else:
print(f"{number} Odd hai") # ← Ye chalega! ✅
# Output: 15 Odd hai# Pass ya Fail
marks = 35
if marks >= 33:
print("🎉 Congratulations! Pass ho gaye!")
else:
print("😢 Fail ho gaye, mehnat karo!")
# Output: 🎉 Congratulations! Pass ho gaye!if-elif-else Statement
elif (else if) use karte hain. Ye ek ke baad ek check karta hai — jo pehle True milti hai, uska code chalata hai!# Grade Calculator — Bahut useful example!
score = 85
if score >= 90:
grade = "A" # 90-100
elif score >= 80:
grade = "B" # 80-89 ← Ye match hoga!
elif score >= 70:
grade = "C" # 70-79
elif score >= 60:
grade = "D" # 60-69
else:
grade = "F" # 0-59
print(f"Score: {score}, Grade: {grade}")
# Output: Score: 85, Grade: B# Mausam (Weather) ke basis par kya pehne?
temperature = 35
if temperature > 40:
print("🥵 Bahut garmi! Ghar pe raho!")
elif temperature > 30:
print("☀️ Garmi hai, cotton ke kapde pehno")
elif temperature > 20:
print("🌤️ Accha mausam hai!")
elif temperature > 10:
print("🧥 Thandi hai, jacket pehno")
else:
print("🥶 Bahut thandi! Sweater + jacket dono!")Nested if Statements
# Online Shopping — Purchase Approve karo
age = 25
has_id = True
has_money = True
if age >= 18: # Pehle age check
print("✅ Age OK!")
if has_id: # Phir ID check
print("✅ ID Verified!")
if has_money: # Phir paisa check
print("🎉 Purchase Approved!")
else:
print("❌ Insufficient funds")
else:
print("❌ ID verification required")
else:
print("❌ Must be 18 or older")Logical Operators (and, or, not)
and = dono True ho, or = koi ek True ho, not = ulta kar do.AND — Dono conditions True honi chahiye
# Same shopping example — but simpler!
age = 25
has_id = True
has_money = True
# Nested if ki jagah ek hi line mein!
if age >= 18 and has_id and has_money:
print("🎉 Purchase Approved!") # ✅ Sab True hai!
else:
print("❌ Cannot purchase")
# and Truth Table:
# True and True = True ✅
# True and False = False ❌
# False and True = False ❌
# False and False = False ❌OR — Koi ek condition True honi chahiye
# Discount milega ya nahi?
is_student = False
is_senior = True
is_member = False
if is_student or is_senior or is_member:
print("🎁 Discount applied!") # ✅ Senior hai!
else:
print("❌ No discount")
# or Truth Table:
# True or True = True ✅
# True or False = True ✅
# False or True = True ✅
# False or False = False ❌AND + OR Combined
# Ticket Pricing System
age = 65
is_weekend = True
if age < 5:
price = 0 # Free for babies
elif (age < 18 or age >= 60) and not is_weekend:
price = 8 # Discount on weekdays
else:
price = 12 # Full price
print(f"Ticket: ₹{price}")() use karo complex conditions mein — clarity badhti hai aur bugs kam hote hain!Short-Circuit Evaluation
Simple samjho:
False and ___→ Result pehle se False hai, toh___check nahi hogaTrue or ___→ Result pehle se True hai, toh___check nahi hoga
# Short-circuit demonstration
def check_a():
print("A check ho raha...")
return False
def check_b():
print("B check ho raha...")
return True
# AND: pehla False hai, toh doosra check nahi hoga
print("AND:")
result = check_a() and check_b() # Sirf "A check ho raha..." print hoga
print(f"Result: {result}") # False
# OR: pehla True hai, toh doosra check nahi hoga
print("\nOR:")
result = check_b() or check_a() # Sirf "B check ho raha..." print hoga
print(f"Result: {result}") # Truewhile Loop
# Countdown Timer — 5 se 1 tak!
countdown = 5
while countdown > 0:
print(f"⏰ {countdown}...")
countdown -= 1 # Har baar 1 kam karo
print("🚀 Blast off!")
# Output:
# ⏰ 5...
# ⏰ 4...
# ⏰ 3...
# ⏰ 2...
# ⏰ 1...
# 🚀 Blast off!# User se tab tak input lo jab tak "quit" na likhe
while True:
command = input("Command likho (quit to exit): ")
if command == "quit":
print("Bye! 👋")
break # Loop se bahar aao!
print(f"Aapne likha: {command}")break use karo.for Loop
# List ke har item par loop
fruits = ["🍎 Apple", "🍌 Banana", "🥭 Mango"]
for fruit in fruits:
print(f"Mujhe pasand hai: {fruit}")
# Output:
# Mujhe pasand hai: 🍎 Apple
# Mujhe pasand hai: 🍌 Banana
# Mujhe pasand hai: 🥭 Mango# range() — Numbers ka sequence banao
# range(5) = 0, 1, 2, 3, 4
# range(1, 6) = 1, 2, 3, 4, 5
# range(0, 10, 2) = 0, 2, 4, 6, 8
# Multiplication Table
number = 5
print(f"--- {number} ka Table ---")
for i in range(1, 11):
print(f"{number} × {i} = {number * i}")# Total calculate karo
prices = [100, 250, 50, 300]
total = 0
for price in prices:
total += price
print(f"Total bill: ₹{total}") # ₹700break Statement
# Pahla even number dhundho
numbers = [1, 3, 5, 6, 7, 8, 9]
for num in numbers:
if num % 2 == 0:
print(f"✅ Pehla even number mila: {num}")
break # Mil gaya, ab aur dhundhne ki zaroorat nahi!
print(f"❌ {num} odd hai, agle ko dekho...")
# Output:
# ❌ 1 odd hai, agle ko dekho...
# ❌ 3 odd hai, agle ko dekho...
# ❌ 5 odd hai, agle ko dekho...
# ✅ Pehla even number mila: 6continue Statement
# Sirf odd numbers print karo, even skip karo
for i in range(1, 11):
if i % 2 == 0: # Agar even hai...
continue # Skip karo! ⏭️
print(f"Odd: {i}") # Sirf odd wale yahan aayenge
# Output: 1, 3, 5, 7, 9# Negative marks skip karo, sirf positive count karo
marks = [85, -1, 90, -5, 75, 88]
total = 0
count = 0
for m in marks:
if m < 0:
continue # Negative skip!
total += m
count += 1
print(f"Average: {total/count:.1f}") # 84.5Loop with else
else bhi laga sakte ho! else tab chalega jab loop normally complete ho (bina break ke). Agar break laga toh else skip ho jaayega.# Prime Number Check karo
number = 13
for i in range(2, number):
if number % i == 0:
print(f"{number} prime nahi hai")
break # Divisor mila, break!
else:
# Ye tab chalega jab break NAHI laga
print(f"{number} prime hai! ✨")
# Output: 13 prime hai! ✨else bahut useful hai jab dhundhna ho — agar mil gaya toh break karo, agar nahi mila toh else mein batao.Pattern Programs
# Right Triangle Pattern
n = 5
for i in range(1, n+1):
print("⭐ " * i)
# Output:
# ⭐
# ⭐ ⭐
# ⭐ ⭐ ⭐
# ⭐ ⭐ ⭐ ⭐
# ⭐ ⭐ ⭐ ⭐ ⭐# Number Pyramid
n = 5
for i in range(1, n+1):
print(" " * (n-i), end="")
for j in range(1, i+1):
print(j, end=" ")
print()
# Output:
# 1
# 1 2
# 1 2 3
# 1 2 3 4
# 1 2 3 4 5MCQ Quiz — Test Your Knowledge!
10 important MCQs — Control Statements ke concepts test karo! 🧠
What is the output of: if 0: print("Yes") else: print("No")
Which keyword is used to skip the current iteration of a loop?
What does break statement do inside a loop?
What is the output of: for i in range(3): print(i)
When does the else block of a for loop execute?
What is the output of: print(True and False)
What is the output of: print(False or True)
Which loop is best when you know how many times to iterate?
What happens if while loop condition is always True?
What is short-circuit evaluation?
Practice Questions — PDFs
In practice sets se aur practice karo — Google Drive se download kar sakte ho! 📥