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 |
|---|---|---|---|
|
โI quit.โ |
Exits the loop entirely |
Stops looping |
|
โSkip this one.โ |
Moves to next iteration |
Skips current step |
|
โ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
passin empty functions, classes, or loops while designing code:def future_feature(): pass # TODO: Add logic later
๐ง Summary Table#
Keyword |
Purpose |
Example |
|---|---|---|
|
Run code when condition is True |
|
|
Extra condition |
|
|
Run when all conditions fail |
|
|
Loop a fixed number of times |
|
|
Loop until condition is False |
|
|
Exit the loop early |
|
|
Skip current iteration |
|
๐ 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#
Write a program to check if a number is positive, negative, or zero.
Write a program that prints all numbers from 1 to 10 using a
forloop.Write a program that prints only even numbers from 1 to 20.
Write a program that checks if a given year is a leap year.
Write a program that keeps asking for a password until the user enters
"python".Write a program that counts the number of vowels in a given word.
Write a program that prints the multiplication table for a given number.
Write a program to sum all numbers from 1 to 100 using a loop.
Write a program to find the largest number from a list of 5 numbers entered by the user.
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