Lesson 8
25 min
def, parameters, return and variable scope: organize and reuse your code.
Definition
A function is a named andreusable block of code that performs a specific task. It can receive information as input (the parameters) and return a result as output (withreturn). You create it with thedefkeyword and run it by writing its name followed by parentheses, for examplecalculate(5).
A function is a named block of code that you can call as many times as needed. It avoids copy-pasting the same code, and makes the program more readable and easier to fix. You already use some:print(),input()andlen()are functions provided by Python.
Writing your own functions means breaking a big problem down into small, simple steps, each with a clear name. If an error is hiding in a calculation, you fix it in a single place instead of hunting for it throughout the whole program.
You define a function with thedefkeyword, followed by its name, parentheses and a colon. The body of the function is indented. Defining a function doesn’t run it: the code only runs when you call it by name.
def say_hello():
print("Hello!")
print("Welcome to this program.")
say_hello()
say_hello()
Parameters are variables placed between the parentheses: they let you pass information to the function when you call it. The values you pass are called arguments.
def greet(first_name, city):
print(f"Hello {first_name}, welcome to {city}!")
greet("Léa", "Lyon")
greet("Tom", "Lille")By default, arguments are matched to parameters in order. You can also name them when calling, which makes the code more readable and lets you give them in any order.
def introduce(first_name, age):
print(f"{first_name} is {age} years old.")
introduce("Léa", 25) # positional arguments
introduce(age=30, first_name="Tom") # named arguments, any orderA function can return a result withreturn. You can then store this result in a variable. As soon as Python encountersreturn, the function stops: any lines written after it are never run.
def add(a, b):
return a + b
result = add(4, 7)
print(result) # 11
print(add(10, 5) * 2) # 30A function can even return several values at once, by separating them with commas (Python actually returns them grouped in a tuple). You then retrieve them in as many variables.
def min_and_max(a, b):
if a < b:
return a, b
return b, a
smaller, larger = min_and_max(9, 3)
print(smaller, larger) # 3 9print() or return?
print()displays a value on the screen but doesn’t make it reusable.returnhands the value back to the code that called the function. As a general rule, a function calculates and returns, and it’s the main program that displays.
A parameter can have a default value, used when no argument is provided. Parameters with a default value always go after those without one.
def price_with_tax(price_before_tax, tax=0.20):
return price_before_tax * (1 + tax)
print(price_with_tax(100)) # 120.0
print(price_with_tax(100, 0.055)) # 105.5A variable created inside a function is local: it only exists while that function is running. It is invisible outside. Conversely, a variable created outside any function is global: it can be read from within a function, but it’s better to pass values through parameters.
def calculate():
result = 42
print(result)
calculate()
print(result) # NameError: result doesn't exist hereYou can describe what a function does with a docstring: a text between triple quotation marks placed right below thedefline. It serves as an instruction manual for other developers, and for you in a few weeks.
def rectangle_area(length, width):
"""Returns the area of a rectangle from its two sides."""
return length * width
print(rectangle_area(5, 3)) # 15calculate_total,is_even).
say_hellowithout()doesn’t run the function.add(4)when the function expects two values causes aTypeError.return, the function returnsNoneand the result is lost.Exercise
is_even(number)that returnsTrueif the number is even andFalseotherwise, then test it with several values. Add a docstring that explains what it does.Going further
convert(celsius)that returns the temperature in Fahrenheit (formula: C x 9/5 + 32), then use it in a loop to display the conversion from 0 to 100 degrees in steps of 10. Add a parameter with a default value to choose the number of decimals displayed.