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. ๐ŸŽต


๐ŸŒ€ 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).


๐Ÿงฎ 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!


๐Ÿ”„ 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.


Excellent catch โ€” youโ€™re absolutely right ๐Ÿ‘

Many beginners confuse pass, break, and continue, and the difference really โ€œclicksโ€ only after seeing clear examples side-by-side.

Hereโ€™s an improved section you can insert right after the continue explanation in your control_flow.md. It keeps the tone light and clear โ€” ideal for students.


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

Keyword

Meaning

What It Does

Example Behavior

break

โ€œI quit.โ€

Exits the loop entirely

Stops looping

continue

โ€œSkip this one.โ€

Moves to next iteration

Skips current step

pass

โ€œDo nothing.โ€

Placeholder for future code

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

Keyword

Purpose

Example

if

Run code when condition is True

if age > 18:

elif

Extra condition

elif age == 18:

else

Run when all conditions fail

else:

for

Loop a fixed number of times

for i in range(5):

while

Loop until condition is False

while x < 10:

break

Exit the loop early

if x == 5: break

continue

Skip current iteration

if 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