Loops, conditions and functions
By the end: You can write functions with clear inputs and outputs, and control the flow of a program.
- if, elif, else
- for and while loops, break and continue
- Defining functions and returning values
- Default arguments and keyword arguments
- Scope: what a function can see
New to python? A programming language is the set of written instructions a computer will follow, and Python is the one this field settled on. It reads close to English: a line that filters a list of records looks roughly like a sentence describing that filter. Every model provider ships a Python library, and nearly every machine learning tool is written in it. Why it matters
So far a program runs from top to bottom and does the same thing every time. This section is about the three ways that changes: doing something only when a condition holds, doing something repeatedly, and packaging a piece of work under a name so it can be called from anywhere with different inputs. Functions are the larger half — nearly all the code you will read is organised into them.
Conditions#
Python uses indentation instead of braces. Everything indented under the if belongs to it. Four spaces is the convention.
score = 72
if score >= 90:
grade = "A"
elif score >= 70:
grade = "B"
else:
grade = "C"# Comparisons
== != < > <= >=
# Combining them
if age > 18 and has_id:
...
if role == "admin" or role == "owner":
...
if not is_blocked:
...
# Python lets you chain comparisons
if 0 < score < 100:
...Loops#
A for loop walks through anything you can iterate: a list, a string, a dictionary, a range.
for topic in topics:
print(topic)
for i in range(5): # 0, 1, 2, 3, 4
print(i)
for i in range(1, 6): # 1 to 5
print(i)
# When you need the position as well as the item
for index, topic in enumerate(topics):
print(index, topic)
# When you need to walk two lists together
for name, score in zip(names, scores):
print(name, score)break leaves the loop entirely. continue skips to the next iteration.
for n in numbers:
if n < 0:
continue # skip negatives
if n > 100:
break # stop completely
process(n)A while loop runs until its condition becomes false. Use it when you do not know how many times you will loop, such as retrying until something succeeds.
attempts = 0
while attempts < 3:
if try_once():
break
attempts += 1Functions#
A function is a named block of code that takes inputs and gives back a result. def defines it, return sends a value back.
def greet(name):
return f"Hello {name}"
message = greet("Jack") # 'Hello Jack'A function without a return statement gives back None. That is fine for functions that only print or save something.
Arguments can have defaults, which makes them optional when calling.
def call_model(prompt, model="fast", temperature=0.0):
...
call_model("hello")
call_model("hello", model="strong")
call_model("hello", temperature=0.7)Never use a list or dict as a default
def add(item, items=[]) creates that list once, when the function is defined, and every call shares it. Items pile up across calls and it looks like data leaking between requests. Use None as the default and create the list inside the function.
# Wrong
def add(item, items=[]):
items.append(item)
return items
# Right
def add(item, items=None):
if items is None:
items = []
items.append(item)
return itemsScope#
A variable created inside a function only exists inside it. The function can read variables from outside, but assigning to one creates a new local variable rather than changing the outer one.
count = 0
def increment():
count = count + 1 # UnboundLocalError
def increment():
global count # works, but avoid this
count = count + 1
def increment(count): # better: pass it in, return it out
return count + 1Prefer the last version. Functions that take what they need and return a result are easier to test and easier to reason about than ones that reach out and change things elsewhere.
Lambda#
A lambda is a small function written in one line, with no name. You will mostly see it as the key argument to sorted.
sorted(people, key=lambda p: p["age"])
# The same thing written normally
def get_age(p):
return p["age"]
sorted(people, key=get_age)Where people go wrong
Mixing tabs and spaces for indentation. Python treats them differently and the error message is confusing. Configure your editor to insert four spaces when you press Tab and never think about it again.
If this comes up in an interview
What is wrong with def f(items=[])?
The default list is created once when the function is defined, not on each call, so every call shares the same list. Values accumulate across calls. Use None as the default and create the list inside the function.
What is the difference between break and continue?
break exits the loop completely. continue skips the rest of the current iteration and moves to the next one.
What does a function return if there is no return statement?
None. This is why assigning the result of a method like list.sort() gives you None, because it changes the list in place and returns nothing.
What is the difference between arguments and parameters?
Parameters are the names in the function definition. Arguments are the actual values you pass when calling it. Interviewers ask this to check you can be precise about terminology.
Build this: Write a function that takes a list of numbers and returns a dictionary with the minimum, maximum, average and count. Handle the empty list case sensibly rather than crashing.
Watch it explained
This is one section of Python, 33 hours across 9 sections. Read it in full to get the whole topic in order.
Stop 1 of 50 on the AI Engineer route
0 of 50 topics done · 0h behind you, 603h to go
What you have marked done is stored in this browser only. It does not reach a server, and clearing site data will clear it.