Functions: Reusable Superpowers
Functions: Reusable Superpowers 🦸
You've already been using functions like len(...) and print(...) this whole time — those are built into Python. Now let's learn to write your own.
def greet(name):
return "Hello, " + name + "!"
message = greet("Sam")
print(message) # Hello, Sam!
def starts a new function, followed by a name and, in parentheses, any inputs it needs (called parameters). Whatever comes after return gets sent back to wherever the function was called — like an answer being handed back.
Default parameter values
You can give a parameter a default value, so callers can leave it out if they want:
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
greet("Sam") # "Hello, Sam!"
greet("Sam", "Hi") # "Hi, Sam!"
Calling functions from other functions
Functions can call other functions — this is called composition, and it's a great way to reuse code instead of repeating yourself:
def double(n):
return n * 2
def quadruple(n):
return double(double(n))
Functions that answer yes/no questions
Functions that return True or False are often named starting with is_ — they're called predicates, and they're great building blocks for if statements elsewhere in your code.
A sneak peek at recursion
A function can even call itself! This is called recursion. It always needs a base case that stops it, or it would call itself forever:
def countdown_sum(n):
if n <= 0:
return 0
else:
return n + countdown_sum(n - 1)
Let's put all of this into practice!