Python Basics · Lesson 10 of 12

Functions

A function is a named block of code that you can run whenever you need it. You have used several: print, len, input. Now you will write your own.

def greet(name):
    print(f"Hello, {name}!")

greet("Noor")
greet("Luca")
  • def greet(name): defines the function. The indented block is its body. Nothing runs yet.
  • name is a parameter: a variable that receives a value each time the function is used.
  • greet("Noor") calls the function. "Noor" is the argument that goes into name.

A function must be defined above the place where you call it.

Returning a value

Most functions calculate something and hand it back with return:

def area(width, height):
    return width * height

room = area(4, 5)
print(room)          # 20
print(area(2, 3))    # 6

The call is replaced by the value the function returns, so you can store it, print it or use it in a bigger calculation. return also ends the function at once.

Printing and returning are different. print shows a value to a person. return gives a value back to the code that called the function. A function without return gives back the special value None.

Default values

A parameter can have a default, used when the caller leaves it out:

def power(base, exponent=2):
    return base ** exponent

print(power(5))      # 25
print(power(2, 10))  # 1024

Why functions matter

Functions let you write a piece of logic once and use it everywhere. They also give a name to an idea, which makes programs much easier to read.

Your Task

  1. Write a function double that takes one number and returns that number times 2.
  2. Write a function is_even that takes a number and returns True when it is even and False when it is odd. (Remember the remainder operator %.)
  3. Print the result of double(21).
  • double returns twice its input
  • is_even returns True for even numbers and False for odd ones
  • Both functions use return
  • 42 is printed by calling double(21)