Give a block of code a name with def, run it whenever you need it by calling it, and choose good function names.
About 25 minFirst steps4 exercisesFree
You will be able to
Explain what a function is and why programs use them
Define a function with def, a name, parentheses, a colon and an indented body
Call a function and predict when its body runs
Choose clear, verb-based snake_case names for functions
Imagine a bakery's till program that prints the same three-line header at the top of every receipt, every daily report and every price list. If the header is copied into five places and the phone number changes, you have to find and fix all five copies, and you will probably miss one.
A function solves this. It is a block of code with a name. You write the code once, and then call the function by name every time you want that code to run. Change the function and every place that calls it gets the change. You have already used functions that Python provides, such as print(), len() and input(). In this track you write your own.
Try it: Change the street name inside the function and run it again. Both headers change, because both calls run the same code.
The parts of a definition
defprint_header():
print("SAFA BAKERY")
def is the keyword that starts a function definition.
print_header is the function's name. The same naming rules as variables apply.
() holds the function's parameters (inputs). This one has none; the next lesson adds them.
The colon: ends the header line, as with if and for.
The indented lines below are the body: the code that runs when the function is called.
Defining a function does not run its body. Python only remembers "there is a function called print_header, and this is its code". The body runs when you call the function by writing its name followed by parentheses: print_header().
Predict the output
print("Opening the till")defgreet_customer():
print("Welcome to Safa Bakery")print("Ready for customers")
greet_customer()
greet_customer()
Calling needs parentheses
Writing the name without parentheses refers to the function but does not run it. greet_customer is the function itself; greet_customer() is a call. Forgetting the parentheses is a silent mistake: Python raises no error, the body never runs.
A function must also be defined before the line that calls it runs. Python reads the file from top to bottom, so calling greet_customer() above its def raises a NameError.
Calling before defining raises NameError
show_menu()defshow_menu():
print("Bread, Croissant, Date cake")
Try it: Move the call below the function definition and run it again.
Functions can call other functions
The body of a function can contain any code, including calls to other functions you wrote. This lets you build bigger tasks from smaller named steps:
defprint_divider():
print("="*24)defprint_closing_message():
print_divider()print("Thank you for shopping!")
print_divider()
Naming functions
A function does something, so its name usually starts with a verb: print_header, show_menu, calculate_total, send_reminder. Use lowercase words joined by underscores (called snake_case). Avoid vague names such as do_it or function1, and never reuse a built-in name such as print, list or sum for your own function: you would hide the built-in.
Building a task from smaller functions
defprint_divider():
print("="*24)defprint_closing_message():
print_divider()print("Thank you for shopping!")print("Open daily 6:00 - 23:00")
print_divider()print("Total: 37.50 SAR")
print_closing_message()
Try it: Change the divider to use "-" instead of "=". Both divider lines change, because there is only one place that defines them.
Guided practice · ●difficulty 1 of 5 · about 3 min
Print a store banner
Define a function print_banner() with no parameters. When it is called it should print exactly these two lines:
*** NAKHLA DATES ***
Premium dates since 1998
The grader calls print_banner() itself, so you don't need to call it (calling it once at the bottom to try it out is fine).
Python code editor. Tab indents. Press Escape then Tab to leave the editor. Control or Command plus Enter runs the code; Shift plus Enter checks your answer.
Ctrl+Enter run · Shift+Enter check · your code is saved in this browser as you type
Output
Run your code to see its output, or Check to test it against the requirements.
The solution becomes available after you pass, or after all three hints and two checks.
Challenge · ●●difficulty 2 of 5 · about 5 min
A report header built from two functions
The warehouse team at Rawabi Logistics prints a header on every stock report. Write two functions:
print_rule() prints a line of 30 # characters.
print_report_header() prints the rule, then the line RAWABI LOGISTICS - STOCK REPORT, then the rule again. It must callprint_rule() rather than repeating the # line itself.
Python code editor. Tab indents. Press Escape then Tab to leave the editor. Control or Command plus Enter runs the code; Shift plus Enter checks your answer.
Ctrl+Enter run · Shift+Enter check · your code is saved in this browser as you type
Output
Run your code to see its output, or Check to test it against the requirements.
The solution becomes available after you pass, or after all three hints and two checks.
Debugging · ●●difficulty 2 of 5 · about 4 min
The opening hours never appear
A café's sign program should print its opening hours twice: once for the front window and once for the door. When the owner runs it, it prints the first heading and then crashes. After a first attempt at fixing the crash, the hours still appear only once.
Fix the program so that running it prints:
Front window:
Open 7:00 - 23:00, Fri 13:00 - 23:00
Door:
Open 7:00 - 23:00, Fri 13:00 - 23:00
Keep the show_hours() function and call it twice.
Python code editor. Tab indents. Press Escape then Tab to leave the editor. Control or Command plus Enter runs the code; Shift plus Enter checks your answer.
Ctrl+Enter run · Shift+Enter check · your code is saved in this browser as you type
Output
Run your code to see its output, or Check to test it against the requirements.
The solution becomes available after you pass, or after all three hints and two checks.
Edge cases · ●●difficulty 2 of 5 · about 4 min
A countdown function with a loop inside
A function body can contain loops. Define print_countdown() with no parameters. Each call prints the numbers from 3 down to 1, one per line, followed by Doors open!:
3
2
1
Doors open!
The grader calls the function several times in a row; every call must print the full countdown again.
Python code editor. Tab indents. Press Escape then Tab to leave the editor. Control or Command plus Enter runs the code; Shift plus Enter checks your answer.
Ctrl+Enter run · Shift+Enter check · your code is saved in this browser as you type
Output
Run your code to see its output, or Check to test it against the requirements.
The solution becomes available after you pass, or after all three hints and two checks.
Summary
A function is a named block of code: write it once, call it as many times as you need.
def name(): followed by an indented body defines a function; the body runs only when the function is called.
A call needs parentheses, and the function must be defined before the call runs.
Functions can call other functions, so a big task can be built from small named steps.
Name functions with verbs in snake_case, such as print_header or calculate_total.