Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Iteration and Pattern Problems time and space complexity of loops visualizing loops with flowcharts (open and collapse html diagrams for every iteration)

Control Flow (If, Else, and Loops)

In Python, control flow means controlling which part of the code runs depending on certain conditions.

Think of your code as a movie — control flow is the director, deciding which scene comes next!


🎬 The if Statement

The if statement checks whether a condition is True. If it is, Python executes the code under it.

age = 20

if age >= 18:
    print("You are an adult!")

Output:

You are an adult!

If the condition is False, the code inside if will be skipped.


🧠 if-else — The Choice Maker

Sometimes you want either this or that — not both.

marks = 45

if marks >= 50:
    print("You passed!")
else:
    print("You failed. Study harder next time!")

Output:

You failed. Study harder next time!

😅 Python doesn’t judge, it just executes.


🪜 elif — Multiple Conditions

When you have several conditions, use elif (short for “else if”).

temperature = 30

if temperature > 35:
    print("It's too hot! Stay indoors.")
elif temperature > 25:
    print("Nice and warm!")
elif temperature > 15:
    print("Pleasant weather!")
else:
    print("Brr... It's cold!")

🧩 Nested Conditions

You can also put an if inside another if — like layers of a samosa 😋

user = "admin"
password = "1234"

if user == "admin":
    if password == "1234":
        print("Access granted!")
    else:
        print("Wrong password!")
else:
    print("Unknown user!")

🔁 Loops — When You Want Repetition

Loops let your code repeat itself — like that one song you keep replaying. 🎵


🧮 Looping Through Lists

fruits = ["apple", "banana", "cherry"]

for f in fruits:
    print("I like", f)

Output:

I like apple
I like banana
I like cherry

🍌 Notice how Python loops through each fruit without peeling errors!


🌀 for Loop

Used when you know how many times to repeat something.

for i in range(5):
    print("Hello!", i)

Output:

Hello! 0
Hello! 1
Hello! 2
Hello! 3
Hello! 4

The range(5) means numbers from 0 to 4 (5 is excluded).


🔄 while Loop

Use a while loop when you don’t know how many times to repeat — it keeps looping as long as a condition is true.

count = 1
while count <= 3:
    print("Attempt", count)
    count += 1

Output:

Attempt 1
Attempt 2
Attempt 3

Be careful! If you forget to update count, this loop will never stop. And your CPU will start sweating 💦


⚙️ else with Loops

Python allows an else block with loops — it runs only if the loop wasn’t stopped by break.

for i in range(3):
    print("Running:", i)
else:
    print("Loop completed successfully!")

Output:

Running: 0
Running: 1
Running: 2
Loop completed successfully!

If you break out early, the else part won’t run.


Loop Modifiers

🛑 break — The Leaver

“I’m done. I’m leaving this meeting (loop) right now!”

When Python hits break, it stops the loop completely and exits.

for i in range(5):
    if i == 3:
        break
    print("Number:", i)
print("Loop ended!")

Output:

Number: 0
Number: 1
Number: 2
Loop ended!

As soon as i == 3, Python breaks out — no more looping.


⏭️ continue — The Skipper

“I’m still in the meeting, but I’ll skip this boring part.”

continue skips the current iteration and moves to the next one.

for i in range(5):
    if i == 3:
        continue
    print("Number:", i)

Output:

Number: 0
Number: 1
Number: 2
Number: 4

Python skips printing when i == 3, but keeps looping afterward.


😶 pass — The Silent One

“I’m here… but I don’t have anything to say yet.”

pass does nothing. It’s a placeholder — useful when you haven’t written code yet, but Python still expects something inside.

for i in range(5):
    if i == 3:
        pass  # I’ll deal with this later
    print("Number:", i)

Output:

Number: 0
Number: 1
Number: 2
Number: 3
Number: 4

Even though i == 3 triggers pass, Python just ignores it and continues normally.


🎭 In Short:

KeywordMeaningWhat It DoesExample Behavior
break“I quit.”Exits the loop entirelyStops looping
continue“Skip this one.”Moves to next iterationSkips current step
pass“Do nothing.”Placeholder for future codeJust sits quietly

👀 Real-World Analogy

Imagine you’re watching a Netflix series:

  • break → You stop watching and close the laptop 🎬

  • continue → You skip an episode but keep watching the rest ▶️

  • pass → You sit there doing nothing… maybe buffering? 😅


💡 Pro Tip: Use pass in empty functions, classes, or loops while designing code:

def future_feature():
    pass  # TODO: Add logic later

🧠 Summary Table

KeywordPurposeExample
ifRun code when condition is Trueif age > 18:
elifExtra conditionelif age == 18:
elseRun when all conditions failelse:
forLoop a fixed number of timesfor i in range(5):
whileLoop until condition is Falsewhile x < 10:
breakExit the loop earlyif x == 5: break
continueSkip current iterationif x == 2: continue

😂 A Tiny Comedy Moment

Student: “Sir, why do we need loops?”

Professor: “So you don’t have to copy-paste print("Hello") 100 times.”

Student: “But I already did that…”

Professor: “Then congratulations, you are the loop.”


💪 Practice Questions

  1. Write a program to check if a number is positive, negative, or zero.

  2. Write a program that prints all numbers from 1 to 10 using a for loop.

  3. Write a program that prints only even numbers from 1 to 20.

  4. Write a program that checks if a given year is a leap year.

  5. Write a program that keeps asking for a password until the user enters "python".

  6. Write a program that counts the number of vowels in a given word.

  7. Write a program that prints the multiplication table for a given number.

  8. Write a program to sum all numbers from 1 to 100 using a loop.

  9. Write a program to find the largest number from a list of 5 numbers entered by the user.

  10. Bonus Fun One 🎭: Ask the user’s mood — if "happy", print "Keep smiling!"; if "sad", print "Cheer up, Python believes in you!"; else, print "Processing emotions... try again."

# Your code here