Phase 1 · Programming Fundamentals
Loops & Conditionals
Make decisions with if/elif/else, then repeat work with for and while loops.
On this page
Comparisons & boolean logic
Conditionals start with expressions that evaluate to True or False. Compare with ==, !=, <, >, <=, and >=.
Combine conditions with and, or, and not. Parentheses help keep complex checks readable.
score = 85
print(score >= 70) # True
print(score == 100) # False
print(score != 0) # True
age = 19
has_id = True
print(age >= 18 and has_id) # True
print(age < 13 or age > 65) # False
print(not has_id) # FalseUse == for equality. A single = is assignment and will cause a syntax error inside an if condition.
if / elif / else
An if block runs only when its condition is True. Use elif for more branches and else as the fallback.
Indentation (usually 4 spaces) defines which lines belong to the block. Python has no braces.
score = int(input("Score (0-100): "))
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "Needs work"
print(f"Grade: {grade}")temp = 32
raining = True
if temp < 0:
print("Freezing")
else:
if raining:
print("Cold and wet—bring a jacket")
else:
print("Cold but dry")Prefer elif chains over deep nesting when you are picking one outcome from many ranges.
for loops
A for loop walks through each item in a sequence—strings, lists, or a range of numbers.
range(n) gives 0..n-1. range(start, stop) and range(start, stop, step) give finer control.
for i in range(5):
print(i)
for n in range(1, 6):
print(f"Square of {n} is {n * n}")languages = ["Python", "JavaScript", "Go"]
for lang in languages:
print(f"I am learning {lang}")
# enumerate gives index + value
for index, lang in enumerate(languages, start=1):
print(f"{index}. {lang}")Choose for when you know how many times to repeat, or when you are iterating a known collection.
while loops
A while loop keeps running as long as its condition stays True. You must update something inside the loop or it can run forever.
Use break to exit early and continue to skip to the next iteration.
count = 3
while count > 0:
print(count)
count -= 1
print("Go!")for n in range(1, 10):
if n == 3:
continue # skip 3
if n == 7:
break # stop before printing 7+
print(n)If a while loop never ends in Try It, check that the condition eventually becomes False—or add a break.
Practice
Mini challenge: number guessing helper
Ask the user for a secret target (1–10) and a guess. Print "too low", "too high", or "correct" using if/elif/else. Then use a for loop to print all numbers from 1 to the target.
target = int(input("Secret number (1-10): "))
guess = int(input("Your guess: "))
# TODO: compare guess to target with if/elif/else
# TODO: for loop printing 1..target
Interactive
Try It in the browser
Powered by Pyodide
Ask for an age as an integer. Print "child" if under 13, "teen" if 13–19, otherwise "adult".
Output
—
Errors
—
Check understanding
Lesson quiz
Score 4/5 or higher to mark this day complete.