main
No variables
def.def statement.This chapter introduces the syntax to write functions. The mechanics are small. The conceptual idea — what is different between defining a function and calling one — is more important.
defTo create a function in Python, use the def keyword followed by a name, parentheses, and a colon. The body of the function is the indented block underneath:
def greet(): print("Hello!") print("Good to see you.")This piece of code does not greet anyone. It only defines a function named greet. The body — the two print lines — has not run yet. Python has simply remembered that there is a thing called greet, and when something asks for it to run, the body is what should happen.
To actually greet, you need to call the function:
def greet(): print("Hello!") print("Good to see you.")
greet()That last line, greet(), is the call. Now the body runs, and the program prints two lines.
Two pieces of syntax are worth noticing. The def line ends with a colon, the same as if and for did in the last part. The body is indented by four spaces, consistently. Python is just as strict about function indentation as it was about conditional and loop indentation: if your indentation drifts, Python reports an IndentationError and refuses to run the program.
0 / 5 points
Arrange the lines into a valid program that defines a function and then calls it.
When Python encounters a def statement, it does not run the function body. It just creates a function object and gives it the name in the def. Once the function object has been created, it is available for the program to use.
Defining a function is like writing a recipe. After you have written the recipe, the recipe exists, but nothing is being cooked.
The body only runs when you call the function — that is, when you write its name followed by parentheses. The call is what triggers the body. You can call the same function many times, and each call runs the body fresh from the top.
Consider this program:
print("before def")
def greet(): print("inside greet")
print("after def, before call")
greet()
print("after call")When you run this, the output is:
before defafter def, before callinside greetafter callRead the output and the program side by side. The def greet(): line is between before def and after def, before call, but its body — inside greet — does not print until after the call on the line below.
Function definitions are typically placed at the top of a program, before the main script logic. This way, by the time the main script runs, all the functions are already defined and available to call.
0 / 5 points
Arrange the output lines in the order this program prints them.
print("start")
def note(): print("inside")
print("ready")note()print("done")A function with no parameters always does exactly the same thing. That is fine for a fixed greeting, but many useful functions take some information from the caller and do something with it.
A function takes inputs by listing parameters inside its parentheses:
def greet(name): print(f"Hello, {name}!")
greet("Ada")greet("Bob")This program prints:
Hello, Ada!Hello, Bob!The name name inside the parentheses on the def line is the parameter. When the function is called, the value provided in the parentheses — "Ada" the first time, "Bob" the second — is the argument. The argument is what comes in; the parameter is the variable inside the function that holds it.
Many people use “parameter” and “argument” interchangeably. Most of the time it does not matter. The distinction comes up when you read more formal documentation, so it is worth knowing the difference.
Inside the function, the parameter behaves like any other variable. It can be used in expressions, passed to other functions, compared, printed. It is a normal variable that just happens to have its value provided by the caller.
A function can take more than one parameter. List them in order, separated by commas:
def print_session(subject, minutes): print(f" {subject}: {minutes} minutes")
print_session("Math", 45)print_session("Physics", 90)When calling a function with multiple parameters, the order of the arguments matters. print_session("Math", 45) passes "Math" to subject and 45 to minutes. Writing print_session(45, "Math") would compile and run, but the printed line would be nonsense.
0 / 10 points
Define a function named print_goal(name, minutes).
The function must:
name as the first parameter,minutes as the second parameter,{name} plans {minutes} minutes.After defining the function, call it once with "Ada" and 25.
No user input is needed. The program should produce this output when it is run:
Required output:
Ada plans 25 minutes.Here is a small but important fact: each call to a function runs the body from scratch, with new parameter values. Local work done in one call does not carry over to the next.
def greet(name): message = f"Hello, {name}!" print(message)
greet("Ada")greet("Bob")The variable message is created freshly on each call. The first call creates message = "Hello, Ada!", prints it, and then message goes away. The second call creates message = "Hello, Bob!" from scratch — it has no memory of the first call’s message.
Step through the program below and watch the state panel. The first call and the second call get separate function frames, and each frame creates its own name and message variables.
Code
Step 1 of 12
State
No variables
Output
No output yet
This is closely related to the idea of scope, which we look into in more detail in Local and Global Scope. For now, the takeaway is simple: a function call is a self-contained event. It begins, it runs the body, and it ends.
0 / 5 points
A function creates message = f"Hi, {name}" inside its body. What happens to message after each call finishes?
Python runs programs from top to bottom. By the time it reaches a call, the function being called must already be defined. If the call comes first, Python does not yet know what the name means, and the program crashes with NameError:
greet("Ada") # NameError: name 'greet' is not defined
def greet(name): print(f"Hello, {name}!")The fix is to put def above any call to the function. The usual convention in Python is to put all the function definitions at the top of the program, and the main script logic at the bottom. This way, by the time anything runs, all the functions are already known.
0 / 5 points
Arrange the lines so Python knows the function before it is called.
To make this concrete, here is one of the functions you will write for the study log refactor later: a function that prints a single session in a consistent format.
def print_session(subject, minutes): print(f" {subject}: {minutes} minutes")
print_session("Math", 45)print_session("Physics", 90)print_session("Linear Algebra", 30)This function does one thing — print a session in a fixed format. The study log program had three different versions of “print something about a session” scattered through it (one for the per-session response inside the loop, one in the response logic, one in the summary). With a function, you write the format once, give it a name, and call it from wherever you need it.
This is not the only function the study log will get. By the end of the part, the study log will have several: one for the input prompt, one for the classification, one for the summary, one for each of the small aggregations. Each is small. Each does one thing. The main script becomes a sequence of calls to these named pieces.
0 / 10 points
Define a function named print_task(subject, minutes).
The function must print exactly one line in this format:
Task: {subject} for {minutes} minutesUse an f-string. After defining the function, call it with "Reading" and 30.
No user input is needed. The program should produce this output when it is run:
Required output:
Task: Reading for 30 minutesA short list of mistakes that come up often when learning function syntax:
greet without parentheses does not call the function. It refers to the function object itself, which is rarely what you want. The call needs parentheses: greet().def. Same syntax mistake as forgetting the colon after if or for. Python reports a SyntaxError.if and for: the body lines must all be indented the same amount. Inconsistent indentation gives IndentationError.NameError. Put your defs above your main script.TypeError: greet() takes 1 positional argument but 2 were given.When something fails, read the error message before assuming the worst. Python is specific about what it could not do.
0 / 10 points
Define a function named print_formatted_sum(first, second).
The function must:
first as the first parameter,second as the second parameter,{first} + {second} = {sum}.You may call the function to test it. For example, calling print_formatted_sum(3, 4) should print:
3 + 4 = 7def statement, does the body of the function run? If not, when does it run?def print_session(subject, minutes):, what are the parameters? In the call print_session("Math", 45), what are the arguments?NameError, and what is the fix?greet("Ada")
def greet(name): print(f"Hello, {name}!")greet and greet() when written as a complete line?AI Study Aid
We're looking into to what extent AI-generated diagrams could help with studying.
Use this study aid to generate an AI-generated visual summary of the material you just studied.
Each diagram style emphasizes the content in a different way, so you can choose the focus
that feels most useful.
Using the diagram generator is voluntary and does not affect your course progress. We encourage
you to try it out and see if it helps, but it's totally up to you! Your answers help us understand
how to make better study aids in the future.