Python

Lesson 8 of 10

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:

  • def starts the definition.
  • add is the name.
  • a and b are parameters. They are names for the values that the function receives.
  • The indented lines are the body.
  • return sends a value back to the code that called the function. The function stops at return.

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

  1. Task 1, not checked yet. Write a function named double that takes a number n and returns n multiplied by 2.

  2. Task 2, not checked yet. Write a function named greet that takes a name and returns the text Hello, followed by the name and an exclamation mark. greet('Sam') returns 'Hello, Sam!'. Use an f-string.

  3. Task 3, not checked yet. Write a function named average that takes two numbers, a and b, and returns their average.

  4. Task 4, not checked yet. Write a function named is_even that takes a number n. It returns True when n is even and False when it is odd.

  5. Task 5, not checked yet. Write a function named power with two parameters, base and exponent. The default value of exponent is 2. It returns base to the power of exponent. power(3) is 9, and power(2, 3) is 8.

Task 1 of 5

Write a function named double that takes a number n and returns n multiplied by 2.

All tasks

main.py

Ctrl+Enter runs your code. Ctrl+Shift+Enter checks it. Press Esc, then Tab, to leave the editor.

Output

Press Run to see your result

Your output shows here. Press Run to try your code.