Chapter 2 · Python Basics
Decisions and Loops
- Page 6 of 20
- 4 min read
So far every program has run from top to bottom, once. Real programs make decisions (is this review positive?) and repeat work (do this for each of 10,000 documents). These two ideas — conditions and loops — are where programming gets its power.
Making decisions: if, elif, else
score = 0.72
if score >= 0.8:
label = "positive"
elif score >= 0.4:
label = "neutral"
else:
label = "negative"
print(label)neutralPython checks the conditions from the top and runs the block under the first one that is True, then skips the rest. elif ("else if") and else are optional.
Indentation is the syntax
Python knows which lines belong to the if by their indentation — the 4 spaces at the start of the line. Other languages use braces { }; Python uses whitespace, and it is strict about it:
tokens = 1200
if tokens > 1000:
print("Too long")
print("Shortening the prompt...")
print("Done") # not indented: runs either wayToo long
Shortening the prompt...
DoneAlways indent with 4 spaces (your editor does it when you press Tab). Mixing tabs and spaces, or indenting by 3 in one place and 4 in another, gives an IndentationError.
Repeating: the for loop
A for loop runs its block once for each item in a collection. Three helpers make it much more useful:
range(n)gives the numbers 0 to n−1 — for "do this n times".enumerate()gives each item together with its position.zip()walks through two lists side by side.
documents = ["intro.txt", "pricing.txt", "faq.txt"]
for doc in documents:
print("Reading", doc)
for i in range(3): # 0, 1, 2
print("Attempt", i + 1)
for number, doc in enumerate(documents, start=1):
print(number, doc)Reading intro.txt
Reading pricing.txt
Reading faq.txt
Attempt 1
Attempt 2
Attempt 3
1 intro.txt
2 pricing.txt
3 faq.txtquestions = ["2 + 2?", "Capital of Bangladesh?"]
answers = ["4", "Dhaka"]
for q, a in zip(questions, answers):
print(f"Q: {q} A: {a}")Q: 2 + 2? A: 4
Q: Capital of Bangladesh? A: DhakaThe accumulator pattern
The most common loop in data work: start with an empty result, then build it up item by item. Here we compute an average and collect the scores that pass a threshold:
scores = [0.91, 0.45, 0.78, 0.12, 0.66]
total = 0
passed = []
for s in scores:
total += s # same as total = total + s
if s >= 0.5:
passed.append(s)
print("Average:", round(total / len(scores), 2))
print("Passed:", passed)Average: 0.58
Passed: [0.91, 0.78, 0.66]Repeating until something happens: while
A while loop repeats as long as its condition stays True. Use it when you do not know in advance how many rounds you need — like retrying an API call that sometimes fails:
attempt = 1
max_attempts = 3
success = False
while attempt <= max_attempts and not success:
print("Calling the API, attempt", attempt)
success = attempt == 3 # pretend the third call works
attempt += 1
print("Success!" if success else "Gave up.")Calling the API, attempt 1
Calling the API, attempt 2
Calling the API, attempt 3
Success!The last line uses a one-line conditional expression: A if condition else B.
Every
whileloop needs something inside it that eventually makes the condition False. Forgetattempt += 1and the loop runs forever — press Ctrl+C to stop it.
break and continue
words = ["hello", "world", "STOP", "ignored"]
for w in words:
if w == "STOP":
break # leave the loop now
print(w)
for n in range(1, 8):
if n % 2 == 0:
continue # skip the rest of this round
print(n, end=" ")
print()hello
world
1 3 5 7 break leaves the loop completely; continue jumps straight to the next round. (print(n, end=" ") prints a space instead of starting a new line.)
match: choosing between many options
When you compare one value against many possibilities, match (Python 3.10+) is cleaner than a long if/elif chain. | means "or", and case _ catches everything else:
command = "summarise"
match command:
case "translate":
print("Translating...")
case "summarise" | "summarize":
print("Summarising...")
case _:
print("Unknown command")Summarising...Try it yourself
- Ask the user for a number of tokens. Print "short", "medium" or "long" for under 500, under 2,000, and anything else.
- Given a list of review texts, count how many contain the word "bad" (hint:
"bad" in text.lower()). - Write a guessing game: the secret number is 7; keep asking until the user guesses it, then print how many tries it took.