Jump to the topic you need: conditionals, loops, and list comprehensions.
Conditional statements drive decision-making. They execute code only when a boolean expression is true.
temperature = 30
if temperature > 25:
print("It's a hot day!")
temperature = 20
if temperature > 25:
print("Hot")
else:
print("Cool")
temperature = 15
if temperature > 25:
print("Hot")
elif temperature > 15:
print("Warm")
else:
print("Cold")
Practice with relational (>, >=, <, <=) and logical (and, or, not) operators for richer conditions.
Write a grading system using if/elif/else:
score = 83
if score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 70:
print("C")
elif score >= 60:
print("D")
else:
print("F")
Tip: Order matters—first matching branch wins.
Run and modify the code below:
Adjust score and rerun:
Experiment with and/or/not:
In Python, there are three forms of the if...else statement:
# Basic if
temperature = 30
if temperature > 25:
print("It's a hot day!")
# if...else
temperature = 20
if temperature > 25:
print("It's a hot day!")
else:
print("It's a cool day!")
# if...elif...else
temperature = 15
if temperature > 25:
print("It's a hot day!")
elif temperature > 15:
print("It's a warm day!")
else:
print("It's a cold day!")
đź”— More Resources:
Concise, expressive syntax for generating and transforming lists.
[expression for item in iterable if condition]
Optional condition filters items.
# Traditional loop
squares = []
for x in range(5):
squares.append(x**2)
# List comprehension
squares = [x**2 for x in range(5)]
print(squares)
even = [x for x in range(10) if x % 2 == 0]
print(even)
matrix = [[i*j for j in range(1,4)] for i in range(1,4)]
print(matrix)
names = ["Alice","Bob","Charlie"]
upper = [n.upper() for n in names]
print(upper)
nested = [[1,2],[3,4],[5,6]]
flat = [item for group in nested for item in group]
print(flat)
# Hard to read comprehension
result = [x*y for x in range(10) for y in range(5) if x + y > 5]
# Clearer loop
result = []
for x in range(10):
for y in range(5):
if x + y > 5:
result.append(x*y)
Tip: Prefer clarity over cleverness—readability scales.
Basic squares vs comprehension:
Filtering even numbers:
Flatten & condition in one go:
Loops repeat a block of code. Two primary forms: for (definite) and while (indefinite).
fruits = ["apple","banana","cherry"]
for f in fruits:
print(f"I love {f}!")
for n in range(1, 6):
print("Number:", n)
count = 1
while count <= 5:
print("Count:", count)
count += 1
for n in range(1, 10):
if n == 5:
print("Break at 5")
break
elif n % 2 == 0:
continue
print("Process", n)
for i in range(1,4):
for j in range(1,4):
print(i, j)
Use break to exit, continue to skip, and nest loops carefully—they scale multiplicatively.
Sum numbers with for:
Countdown with while:
Break / continue demo: