Just Enough Python I: the five fundamentals · Topic 5 Free
Functions
def, parameters, return values, defaults. Write a piece of logic once, use it everywhere. Plus lambda, the one-line function you see in pandas and Spark.
A function is a named block of code you can run again and again. Write the logic once, call it from ten places. This is how scripts turn into software.
def, parameters, return
def to_cad(usd, rate):
return round(usd * rate)
print(to_cad(95000, 1.35)) # 128250
defstarts the function. The name follows the same lowercase_underscore style as variables.usdandrateare parameters. The values you pass in are arguments.returnsends a value back. Without it, the function returnsNone.
Calling to_cad(95000, 1.35) does not print anything by itself. It gives you a value. You decide what to do with it: print it, store it, pass it on.
Default values
def to_cad(usd, rate=1.35):
return round(usd * rate)
to_cad(95000) # uses 1.35
to_cad(95000, 1.40) # overrides it
to_cad(usd=95000) # keyword argument, clearer at the call site
Real libraries lean on defaults heavily. pd.read_csv("file.csv", sep=";") is a function call with one required argument and dozens of optional ones.
Small functions, clear names
A good function does one thing and says what it does:
def clean_name(name):
return name.strip().lower()
def is_target_market(country):
return country in ["Canada", "Germany", "Poland"]
def average(numbers):
return sum(numbers) / len(numbers)
Three lines each. When a bug appears, you know exactly where to look. In an Airflow DAG, each task usually calls one such function.
Docstrings
A string right under def explains what the function does. Editors and AI assistants read it.
def to_cad(usd, rate=1.35):
"""Convert a USD amount to CAD, rounded to whole dollars."""
return round(usd * rate)
lambda: the one-line function
A lambda is a tiny anonymous function. You mostly see it passed into other functions:
offers = [("Shopify", 95000), ("Wealthsimple", 110000), ("Startup", 68000)]
sorted(offers, key=lambda o: o[1]) # sort by salary
lambda o: o[1] means “take o, return o[1]”. You will meet it in sorted(), map(), pandas .apply(), and Spark UDFs. Read it, write it when short. If it grows past one line, use def.
Scope
Variables created inside a function live only inside it. That is a feature: functions do not leak into each other. Pass data in through parameters, get it back through return.
Practice
Real Python 3 runs in your browser. Solve the tasks, or just experiment.