Python Tutorial
Conditions and Loops
Control program flow with if/elif/else, for loops, while loops, range, break and continue.
Concept
Conditional statements choose which block runs based on a boolean expression. Use if for the first condition, elif for alternatives and else for the fallback branch.
Loops repeat work. A for loop iterates over an iterable, while a while loop repeats until its condition becomes false. Keep loop conditions easy to reason about to avoid accidental infinite loops.
Example
score = 78
if score >= 80:
print("Excellent")
elif score >= 60:
print("Good progress")
else:
print("Keep practicing")
for n in range(1, 6):
print(n)
Type the example yourself and change at least one value. Small experiments reveal syntax and behavior faster than passive reading.
Practice Tasks
- Print even numbers from 1 to 50.
- Write a grade classifier using if/elif/else.
- Use a while loop to count down from 5.
Key Takeaways
- Conditions select a path.
- for is ideal for iterable data.
- while is useful when repetition depends on a condition.