Just Enough Python I: the five fundamentals · Topic 4 Free
Control flow: if, for, while
Make decisions with if/elif/else, repeat with for and while, and the two patterns you will write a thousand times: filter a list, sum a total.
Control flow is the logic of your program. Decide, repeat, stop. Without it you cannot automate anything.
Indentation is the syntax
Python has no braces. A block is the lines indented under a colon. Use 4 spaces. Mixing tabs and spaces is an error.
if salary >= 100000:
print("senior") # inside the if
print("done") # outside the if
if / elif / else
if salary >= 100000:
level = "senior"
elif salary >= 70000:
level = "middle"
else:
level = "junior"
Conditions are checked from the top. The first true one wins. Comparison operators: ==, !=, <, <=, >, >=. Combine with and, or, not:
if remote and salary > 90000:
print("apply")
if country == "Canada" or country == "Germany":
print("target market")
if not is_deleted:
print("active")
Check membership with in: if country in ["Canada", "Germany", "Poland"]:.
for loops
for walks through every item of a list, a dict, a string, a file:
for city in ["Berlin", "Toronto", "Seattle"]:
print(city)
for i in range(3): # 0, 1, 2
print(i)
offer = {"company": "Shopify", "salary_usd": 95000}
for key, value in offer.items():
print(key, value)
for company, salary in [("Shopify", 95000), ("Startup", 68000)]:
print(f"{company}: {salary}") # unpack tuples as you go
Need the position too? for i, city in enumerate(cities):.
The two loop patterns of data work
You will write these two shapes more than anything else. Learn them by heart.
Filter: keep some rows
high = []
for offer in offers:
if offer["salary_usd"] > 90000:
high.append(offer)
Accumulate: sum or count
total = 0
count = 0
for offer in offers:
total += offer["salary_usd"]
count += 1
print(total / count)
Later you will see sum(), len(), and list comprehensions do this in one line. Understand the loop first.
while loops
Repeat while a condition holds. Less common in data code, but you meet it in API pagination: “keep fetching pages until there is no next page”.
page = 1
while page <= 3:
print(f"fetching page {page}")
page += 1
break exits a loop early. continue skips to the next item.
Infinite loops
A while loop whose condition never becomes false runs forever. Always make sure something inside the loop changes the condition. In the playground, a runaway loop freezes the page until you reload it.
Practice
Real Python 3 runs in your browser. Solve the tasks, or just experiment.