Defining & Calling Functions
Intermediate · 18 min read · ▶ live playground · ✦ checkpoint
Copy-paste feels harmless until the third place you need to fix it. A function is a named block of code you can run again and again, and Python functions let you turn repeated steps into reusable actions with inputs and results.
Name a reusable action
The DRY principle means "Don't Repeat Yourself": keep one idea in one place so you can change it once. Without functions, repeated code starts small and then quietly becomes a maintenance problem.
player = "Mina"
score = 42
print(f"{player}: {score} points")
player = "Ravi"
score = 35
print(f"{player}: {score} points")Mina: 42 pointsRavi: 35 points
That code works, but the pattern is hiding in plain sight: show a player's name, then show a score. Python lets you give that pattern a name.
def show_score(player, score):
print(f"{player}: {score} points")
show_score("Mina", 42)
show_score("Ravi", 35)Mina: 42 pointsRavi: 35 points
The def statement is Python's way to define, or create, a function. The indented lines under it are the function body, the code Python runs when the function is used. A function call is a line like show_score("Mina", 42) that asks the function to run now.
Defining a function does not run its body. It creates the reusable action and binds the function name, much like assignment binds a value to a name tag. The body runs only when you call the function.
Parameters and arguments
A parameter is a name in the def line that waits for a value. An argument is the actual value you pass during a function call.
Think of a function like a recipe card. The parameters are blanks on the card - player and mood. The arguments are the real ingredients you use this time - "Noor" and "focused".
def cheer_player(player, mood):
print(f"{player} looks {mood}.")
print(f"Go, {player}!")
cheer_player("Noor", "focused")
cheer_player("Ira", "calm")Noor looks focused.Go, Noor!Ira looks calm.Go, Ira!
For now, Python matches these arguments by position: the first argument goes into the first parameter, the second argument goes into the second parameter. Other call styles are useful, but they belong in lesson 7.2, where arguments get their own full treatment.
Good parameter names make the function read clearly from the inside. player and mood tell you what the body expects. Names like a and b force the reader to guess.
Return a result
Printing is useful when you want to show something to the user. But many functions need to hand a value back so the rest of the program can keep working with it.
A return value is the value a function gives back to the code that called it. The return statement is a line that sends that value back.
def add_bonus(score):
return score + 10
mina_total = add_bonus(42)
ravi_total = add_bonus(35)
print(mina_total)
print(ravi_total)
print(add_bonus(5) * 2)524530
add_bonus(42) becomes the value 52, so you can store it, print it, compare it, put it in a list, or use it in another expression. This is the big difference between "show this" and "give me a result."
Functions often do both in small beginner programs, but clear functions usually choose one main job. A function that calculates a value should usually return it. A function that displays a message may only print.
The implicit None
None is still the reserved empty seat from lesson 2.2. An implicit value is one Python supplies even though you did not write it. If a function finishes without a return statement, Python returns None implicitly.
def announce_badge(player):
print(f"{player} earned a helper badge")
result = announce_badge("Mina")
print(result)Mina earned a helper badgeNone
This surprises beginners because the function clearly did something: it printed a line. But printing is not returning. announce_badge("Mina") shows text on the screen, then hands back None.
That is not bad. It is just a signal about the function's job. If you want a function's answer to travel into the next line of code, use return.
Try it - turn cart math into functions
Run this cart report, then change the cart data. The def blocks stay the same while the arguments change.
The small line_total function returns a number. The show_line function prints a display line. Splitting those jobs makes the program easier to change: if tax or a discount arrives later, the math has one obvious home.
Write docstrings
A docstring is a string literal as the first statement inside a function to document what the function does. Use triple quotes, then say the function's purpose in one short sentence.
def score_message(player, score):
"""Return one scoreboard message for a player."""
return f"{player}: {score} points"
print(score_message("Noor", 48))Noor: 48 points
The docstring is not a comment for one tricky line. It is a label for the whole function. A good docstring says what the function promises from the outside:
- "Return one scoreboard message for a player."
- "Print one receipt line for an item."
- "Return the total price for a quantity."
Avoid docstrings that narrate the code line by line. The code already says how the work happens. The docstring should help someone decide whether this function is the tool they need.
Checkpoint
Answer all three to mark this lesson complete
You can now wrap repeated steps into named actions, feed them values, and get results back. Next, you get more control over how calls work: positional arguments, keyword arguments, defaults, and the first argument trap worth learning by name.