Defining functions (def)
`def` gives a name to a block of code so you can run it whenever you want, passing it values.
Used in 124 lessons of the course, from 00.01.
A function is named code. You write it once and call it many times.
Read it like this: def announces the function, then comes the name, the parameters in parentheses, and a colon. The body is indented below. Python knows where the function ends because the indentation steps back.
In lesson 00.01 you'll see:
def define(term: str) -> None:
term is the parameter: the name that receives the value you pass when calling. : str and -> None are type hints: they say it expects a string and returns nothing useful. Python doesn't enforce them, but they help you and your editor.
Defining runs nothing. The body runs only when you write define("chain"), with parentheses. That's why the course wraps each step in functions: you can reuse and test them separately.
Reach for it when: you'll repeat the same work, or when you want to give a clear name to a step of your program.
Examples
Common mistake
def greet():
print("Hi!")
greet
print("done")Why: Without parentheses you only name the function; you don't call it. That's why "Hi!" never prints.
How to write it: Write greet() with parentheses to run it.
Common mistake
def double(x):
print(x * 2)
result = double(4)
print(result + 1)Why: The function prints but returns nothing, so `result` is `None`, and `None + 1` fails.
How to write it: Use return x * 2 when you need to use the value later.
