Python Functions
In this post
Wrapping work in a name, with arguments that read at the call site.
Wrapping work in a name, with arguments that read at the call site.
Defining and calling
A function is a block with a name and a result. Naming arguments at the call site keeps the meaning visible without opening the definition.
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Grace"))
print(greet("Alan", greeting="Hi"))
Output:
Hello, Grace!
Hi, Alan!
Returning several things
A function returns one object; a tuple makes that one object several values, unpacked by the caller.
def split_name(full):
first, _, last = full.partition(" ")
return first, last
first, last = split_name("Ada Lovelace")
print(first, "|", last)
Output:
Ada | Lovelace
Next
Carry on to the next tutorial in the rail — it picks up where this one leaves off.
PythonFunctions