Control Statements

Chapter 2 • Python
Chapter 2 • Python

Control Statements

Python mein program ka flow kaise control karte hain — if/else se decisions lo, loops se kaam repeat karo!

if / elif / else
while & for
break / continue
10 MCQs

Introduction to Control Statements

🔀 Control Statements woh commands hain jo Python ko batate hain ki code ko kis order mein chalana hai. Ye program ka "traffic police" hain — decide karte hain kaunsa code kab chalega!

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

✅ if statement check karta hai ki koi condition True hai ya nahi. Agar True hai, toh andar ka code chalega. Agar False hai, toh skip ho jaayega.

Syntax: if condition: ke baad indented code likho.

python
# 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 = False
💡 Python mein 0, "" (empty string), [] (empty list), None — ye sab False maane jaate hain. Baaki sab True hai!

if-else Statement

↔️ if-else mein do raaste hote hain — agar condition True hai toh ek kaam karo, agar False hai toh doosra kaam karo. Dono mein se ek zaroor chalega!
python
# 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
python
# 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

🔢 Jab do se zyada conditions check karni ho, tab elif (else if) use karte hain. Ye ek ke baad ek check karta hai — jo pehle True milti hai, uska code chalata hai!
python
# 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
python
# 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

🪆 Nested if matlab if ke andar if. Jab ek condition True ho, tab doosri condition bhi check karni ho — tab ye use karte hain.
python
# 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")
💡 Bahut zyada nesting avoid karo — code complex ho jaata hai. Uski jagah logical operators (and/or) use karo!

Logical Operators (and, or, not)

🧠 Logical operators multiple conditions ko ek saath check karte hain. and = dono True ho, or = koi ek True ho, not = ulta kar do.

AND — Dono conditions True honi chahiye

python
# 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

python
# 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

python
# 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}")
📝 Hamesha parentheses () use karo complex conditions mein — clarity badhti hai aur bugs kam hote hain!

Short-Circuit Evaluation

⚡ Short-circuit matlab Python aagya ki result pata lag gaya toh baaqi conditions check hi nahi karega — time bachata hai!

Simple samjho:

  • False and ___ → Result pehle se False hai, toh ___ check nahi hoga
  • True or ___ → Result pehle se True hai, toh ___ check nahi hoga
python
# 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}")         # True

while Loop

🔄 while loop tab tak code repeat karta hai jab tak condition True rahe. Jaise — "Jab tak bhookh lage, khana khao!"
python
# 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!
python
# 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}")
⚠️ While loop mein condition kabhi False na ho toh infinite loop ban jaayega! Hamesha condition update karo ya break use karo.

for Loop

🔢 for loop ek sequence (list, string, range) ke har ek item par ek-ek karke kaam karta hai. Jaise — "Class ke har student ka naam bolo".
python
# 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
python
# 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}")
python
# Total calculate karo
prices = [100, 250, 50, 300]
total = 0
for price in prices:
    total += price
print(f"Total bill: ₹{total}")  # ₹700

break Statement

🛑 break loop ko turant rok deta hai — baaki iterations skip ho jaate hain. Jaise chabi mil gayi toh dhundhna band!
python
# 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: 6

continue Statement

⏭️ continue current iteration skip karke next par chala jaata hai. Loop band nahi hota — sirf ek baar skip karta hai!
python
# 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
python
# 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.5

Loop with else

🔍 Python mein loop ke saath else bhi laga sakte ho! else tab chalega jab loop normally complete ho (bina break ke). Agar break laga toh else skip ho jaayega.
python
# 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! ✨
📝 Loop ka else bahut useful hai jab dhundhna ho — agar mil gaya toh break karo, agar nahi mila toh else mein batao.

Pattern Programs

🔺 Pattern programs loops ka best practice hain. Nested loops se alag-alag shapes bana sakte ho — interviews mein bhi poochhe jaate hain!
python
# Right Triangle Pattern
n = 5
for i in range(1, n+1):
    print("⭐ " * i)

# Output:
# ⭐
# ⭐ ⭐
# ⭐ ⭐ ⭐
# ⭐ ⭐ ⭐ ⭐
# ⭐ ⭐ ⭐ ⭐ ⭐
python
# 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 5

MCQ Quiz — Test Your Knowledge!

10 important MCQs — Control Statements ke concepts test karo! 🧠

1

What is the output of: if 0: print("Yes") else: print("No")

2

Which keyword is used to skip the current iteration of a loop?

3

What does break statement do inside a loop?

4

What is the output of: for i in range(3): print(i)

5

When does the else block of a for loop execute?

6

What is the output of: print(True and False)

7

What is the output of: print(False or True)

8

Which loop is best when you know how many times to iterate?

9

What happens if while loop condition is always True?

10

What is short-circuit evaluation?

Practice Questions — PDFs

Hi! 👋
KnoblyAI
Online

Hello! 👋

Your futuristic AI learning companion

KnoblyAI can make mistakes. Double-check important replies.