Bitpath

Lesson 1 · Unit 03

Defining functions

def, parameters, arguments and return

13 exercisesabout 3 min

What you practise

  • def, parameters and arguments, return against print, None, one function calling another, reading a call from the inside out

Try a question from this lesson

Pick one

The first two lines teach Python a new instruction with a name of its own. The last two lines use it. What does this show?

Python
def greet():
    print("Hello!")

greet()
greet()

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Functions

A function is a named block of code.

def defines it: Python remembers the indented block but does not run it yet.

Writing the name followed by brackets calls the function: the block runs now, and then the program carries on from where the call was.

Python
def greet():         # define
    print("Hello!")

greet()              # call

Concept

Parameters and arguments

A parameter is a name in the def line. An argument is a value in the call.

When the function is called, the arguments fill the parameters by position: first to first, second to second.

Python
def area(width, height):
    print(width * height)

area(3, 5)   # width is 3, height is 5
# shows 15

Concept

return

return ends the function and sends a value back. The call then stands for that value, so you can store it, print it or use it in a calculation.

print is different: it only shows something to a person. The program cannot use it afterwards.

A function that ends without a return hands back the special value None, which means "nothing".

Python
def square(n):
    return n * n

print(square(3) + square(4))   # 25

9 more exercises in the app

  • 1× true or false
  • 3× multiple choice
  • 3× type the answer
  • 1× fill the blanks
  • 1× order the lines

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy