BBampaa

Lessons › Python

Python lesson

Functions, step 1

Defining the function doesn't run it. It runs each time you call greet(...), with name set to whatever is in the brackets.

Try this lesson free →
About 5–10 minutes · no sign-up needed

Example

def creates a function: a block of code with a name. Calling the name runs it:

def greet(name):
    print(f"Hi {name}")

greet("Ada")
greet("Tunde")

Output:

Hi Ada
Hi Tunde

Key points

def greet(name):Define a function called greet that takes one input, name.
print(...)The indented lines are the function's steps.
greet("Ada")Call it to run those steps, with name set to Ada.

Write the steps once, then call the function as often as you like.

Practice

Try each one in your head first, then open the answer.

1. Build the first line of a function called hello that takes a name.
def hello(name):
2. Build the line that calls report for the store Lagos.
report("Lagos")
3. Write a function shout(word) that prints the word in capitals. Then call shout("sale").
def shout(word):
    print(word.upper())
shout("sale")
4. Write a function line(store) that prints something like Store: Lagos. Call it for Lagos, then Abuja.
def line(store):
    print(f"Store: {store}")
line("Lagos")
line("Abuja")
5. Write a function double_print(n) that prints n times 2. Call double_print(21).
def double_print(n):
    print(n * 2)
double_print(21)

Learn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.

Try this lesson free →
About 5–10 minutes · no sign-up needed