Chapter 3 — Python Flow Control
📚 Chapter Overview
A script that just runs top-to-bottom is limited. In this chapter, you will learn how to make your Python scripts intelligent using if-elif-else logic and how to handle repetitive tasks using for and while loops.
Learning Objectives:
- Master Indentation-based Logic.
- Use
range()for controlled loops. - Implement nested conditionals for complex decisions.
3.1 The If-Elif-Else Ladder
Part 1 — Definition
Conditional statements in Python rely on Indentation instead of curly braces. The elif (short for else-if) allows you to check multiple conditions in a sequence. If the first condition is false, it moves to the next elif, and finally to else if nothing matches.
Part 2 — Syntax
if condition:
# Code
elif another_condition:
# Code
else:
# Code
Part 3 — Example
Problem: Categorize a student based on their score.
score = 85
if score >= 90:
print("Grade A")
elif score >= 75:
print("Grade B")
else:
print("Grade C")
Output: Grade B
Part 4 — Video
Video: Coming Soon
3.2 Loops (For & While)
Part 1 — Definition
Loops repeat a block of code. Python's for loop is mostly used to iterate over a sequence (like a list or a range of numbers). The while loop continues as long as a condition is met.
Part 2 — Syntax
for i in range(5):
# Runs 5 times
while condition:
# Runs till false
Part 3 — Example
Problem: Sum all numbers from 1 to user-input.
limit = int(input("Enter limit: "))
total = 0
for i in range(1, limit + 1):
total += i
print(f"Total Sum: {total}")
Part 4 — Video
Video: Coming Soon
🏆 Chapter Challenge
Challenge Objective
Create a "Password Strength Checker" that uses logic and loop controls.
Requirements
- Take a password as input.
- Check if it is at least 8 characters long.
- Check if it contains a digit (use
isdigit()in a loop).
Step-by-Step Process
- Use
len(password)to check length. - Use a
forloop to inspect each character. - Print a status: "Strong", "Weak", or "Invalid".
Expected Deliverables
password_check.pysource code.