Lesson ยท 12 min
Functions
A recipe with a name
A function is a block of code with a name. You write it once, and you can use it as many times as you like. You use a function by writing its name with parentheses. This is called a call.
def add(a, b):
return a + b
print(add(2, 3)) # 5
print(add(10, 5)) # 15
The parts of a function:
defstarts the definition.addis the name.aandbare parameters. They are names for the values that the function receives.- The indented lines are the body.
returnsends a value back to the code that called the function. The function stops atreturn.
The values that you give when you call a function, such as 2 and 3, are arguments.
Return and print are different
print shows a value to a person. return gives a value back to the program. A function that only prints gives back None, so you cannot use its result in a calculation. Use return when a function calculates something.
Default values
A parameter can have a default value. If the caller does not give an argument for it, Python uses the default.
def welcome(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(welcome("Sam")) # Hello, Sam!
print(welcome("Sam", "Welcome")) # Welcome, Sam!
Parameters with defaults go after the parameters without defaults.
Your turn
Write five functions. The checker calls each function with several values. It does not read your code to find the answer, so write the general rule, not a single answer.
Tasks
5 to do
Task 1, not checked yet. Write a function named
doublethat takes a numbernand returnsnmultiplied by2.Task 2, not checked yet. Write a function named
greetthat takes anameand returns the textHello,followed by the name and an exclamation mark.greet('Sam')returns'Hello, Sam!'. Use an f-string.Task 3, not checked yet. Write a function named
averagethat takes two numbers,aandb, and returns their average.Task 4, not checked yet. Write a function named
is_eventhat takes a numbern. It returnsTruewhennis even andFalsewhen it is odd.Task 5, not checked yet. Write a function named
powerwith two parameters,baseandexponent. The default value ofexponentis2. It returnsbaseto the power ofexponent.power(3)is9, andpower(2, 3)is8.
Task 1 of 5
Write a function named double that takes a number n and returns n multiplied by 2.