Name a block of code
A function packages code you want to reuse. def defines it and you choose the inputs, called parameters.
def greet(name):
return "Hello, " + name + "!"
print(greet("Ada")) # Hello, Ada!
Nothing runs when you define a function — it runs when you call it.
return vs print
print shows a value to a human. return hands the value back to the code that called the function, so it can be stored or reused. A function without a return gives back None.
def double(number):
return number * 2
total = double(21)
print(total) # 42
Being able to store the result is the whole point: double(21) can be part of a bigger calculation, while a printed line cannot.
Defaults and imports
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Grace")) # Hello, Grace!
print(greet("Ada", greeting="Hey")) # Hey, Ada!
Functions are also how you use other people's code: import random then random.randint(1, 6), or from math import sqrt then sqrt(16).