Lesson 1 · Unit 03
Defining functions
def, parameters, arguments and return
What you practise
def, parameters and arguments,returnagainstprint,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?
def greet():
print("Hello!")
greet()
greet()Correct answer
Hello! twice
Why
The indented line is stored under the name greet. Each greet() after that runs the stored line, so the greeting appears twice. Write the code once, use it as often as you like.
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.
def greet(): # define
print("Hello!")
greet() # callConcept
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.
def area(width, height):
print(width * height)
area(3, 5) # width is 3, height is 5
# shows 15Concept
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".
def square(n):
return n * n
print(square(3) + square(4)) # 259 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.