Python uses indentation (4 spaces) to group code — there are no braces. if, elif and else choose between branches; combine conditions with and, or and not.
A for loop walks through any sequence: a list, a string, or range(start, stop). enumerate() gives you the position and the item together.
A while loop repeats until its condition becomes false. break leaves a loop early; continue skips to the next round.
def grade_for(score):
if score >= 75:
return "A"
elif score >= 65:
return "B"
elif score >= 45:
return "C"
elif score >= 30:
return "D"
else:
return "F"
scores = [82, 67, 49, 31, 18]
for i, score in enumerate(scores, start=1):
grade = grade_for(score)
status = "pass" if grade != "F" else "fail"
print(f"Student {i}: {score} -> {grade} ({status})")
for n in range(1, 16):
if n % 15 == 0:
print("FizzBuzz")
elif n % 3 == 0:
print("Fizz")
elif n % 5 == 0:
print("Buzz")
else:
print(n)
countdown = 3
while countdown > 0:
print(f"Starting in {countdown}...")
countdown -= 1Key points
- Indentation is syntax in Python — keep it consistent (4 spaces).
for item in sequenceis the normal loop;range()makes number sequences.x if condition else ypicks a value in one line.
Exercise
Print the multiplication table for a number from 1 to 12. Then write a guessing game: pick a secret number, keep asking the user with while until they guess it, and print "higher" or "lower" hints.
Show solution
Try the exercise yourself first — then compare your approach with this one.
The multiplication table is a for loop over range(1, 13). The guessing game keeps asking inside a while loop until the guess is right, giving a hint each time.
import random
number = int(input("Times table for: "))
for i in range(1, 13):
print(f"{i:>2} x {number} = {i * number}")
secret = random.randint(1, 100)
guesses = 0
guess = None
while guess != secret:
guess = int(input("Guess the number (1-100): "))
guesses += 1
if guess < secret:
print("Higher!")
elif guess > secret:
print("Lower!")
print(f"Correct! You needed {guesses} guesses.")