Not sure which lesson to do first? Find your level and get a plan →

CS Thinking · Programming Fundamentals · Grade 6-8

Function

A named, reusable block of code that performs a specific task and can optionally accept inputs (parameters) and return a result.

def function_name(parameters): → body → return value

Quick Answer

A named, reusable block of code that performs a specific task and can optionally accept inputs (parameters) and return a result. Use a function whenever you would otherwise copy the same steps to several places: converting temperatures, checking a password, drawing a star. You write the steps once with def, give them a name, and call that name with different inputs, so square(3) gives 9 and square(5) gives 25 from the same code. Fix a bug inside the function and every call is fixed at once.

Why This Matters

Functions let you build a program from pieces you can name, test and trust one at a time. A game might have move_player, check_collision and update_score, each a few lines long, instead of one 500-line tangle. Without them the same steps get copied around, and a bug fixed in one copy survives in all the others.

Intuitive Explanation

A recipe card lists the ingredients and steps for pancakes once. Whenever you want pancakes you follow the card, and for a bigger batch you change the amounts, not the steps. A function is that card for a program. def to_fahrenheit(c): return c * 9 / 5 + 32 writes the steps once. to_fahrenheit(100) runs them with c = 100 and gives 212.0; to_fahrenheit(0) gives 32.0. The name c on the card is the parameter; 100 and 0 are the arguments handed over at each call.

Writing the card does not cook anything. The def lines only store the function under its name, and nothing happens until a line calls it with parentheses. When a call happens, the program jumps into the function, fills the parameters with the arguments, runs the body, and jumps back to the calling line carrying the return value.

Not every repeated piece of code needs a function. A loop is the tool when the same steps repeat many times in a row in one place, such as printing 10 lines. A function is the tool when the same steps are needed in different places or with different inputs, such as converting a temperature on the weather screen and again on the settings screen. Often you use both: a loop that calls a function on each item.

Think of it like this. A vending machine with a name on the front works like a function. You press a button with your choice (the argument), the same machinery inside does the work every time, and an item drops out (the return value); you never need to see inside to use it. The comparison stops at functions that only do a job, such as drawing a shape, and hand back nothing useful.

Core idea. Functions break programs into manageable pieces, enable reuse, and reduce repetition.


When to Use

Write a function when the same steps appear, or will appear, in more than one place, when a task has a clear name like calculate_tax or draw_star, or when a long program should be split into pieces you can test separately. Signals include the word reuse and phrases like 'do this for any input' or 'the same calculation again'. If the steps repeat many times in a row in one spot, a loop is enough. If code should run only when a user acts, attach a function as an event handler.

Tip. Ask: Are the same steps needed in more than one place or with different inputs, so they should be written once under a name?

How to Recognize It

Look for steps that repeat or that form one clear job, and check how values go in and come back out.

  1. Are the same few lines copied, with only a number or a name changed between the copies?

    Yes means turn them into one function, with a parameter for the part that changes. Short lines that appear only once may not need a function yet.

  2. Is the task one clear job you could name with a verb, like convert_to_celsius or check_password?

    Yes means it fits a function. A plan that describes the steps in words, before any code exists, is an Algorithm instead.

  3. Does the code that calls it need a result back?

    Yes means the function needs a return statement, the topic of Return Values. A function that draws or prints can finish its job without returning anything.

  4. Is the question about the names in the definition versus the values in the call?

    Yes means it is really about Parameters: in def area(w, h), w and h are parameters, and in area(3, 4), 3 and 4 are the arguments.

Function vs Modular Design vs Event Handler vs Function as Mapping

Functions live inside modules, an event handler is a function with a different caller, and math uses the same word. Ask how big the unit of code is, what decides when it runs, and whether it can do more than turn an input into an output.

Function

Meaning
A function is a named block of code that you define once and run by calling its name, often with inputs.
Key test
One named block that runs when a line of your code calls it.
Example
def to_celsius(f): return (f - 32) * 5 / 9, so to_celsius(212) gives 100.0.

Modular Design

Meaning
Modular design splits a whole program into separate modules, and each module may hold several functions.
Key test
About dividing the whole program into parts, not one named block.
Example
A game whose graphics module holds draw_board(), draw_piece() and clear_screen().

Event Handler

Meaning
An event handler is a function that the computer calls when an event happens, instead of your own code calling it.
Key test
Same kind of block, but a click or key press decides when it runs.
Example
button.onclick = save_game runs save_game on every click; save_game() on a line runs it once, right then.

Function as Mapping

Meaning
In math, a function pairs every input with exactly one output and does nothing else.
Key test
The same input always gives the same output, and nothing is printed or changed.
Formula
f(x)=x2
Example
For f(x)=x2, f(3) is 9 every time, while roll_die() in code can return a different number on each call.

Formula & Notation

def function_name(parameters): → body → return value
A function f is defined by its signature f(p1,p2,…,pn)→R, its body (a sequence of statements), and its return value. A function call f(a1,a2,…,an) binds arguments to parameters and evaluates the body.

Worked Examples

Example 1 — Define once, call twice

Easy

def to_fahrenheit(c): return c * 9 / 5 + 32. A weather app runs high = to_fahrenheit(30) and low = to_fahrenheit(-10). Trace both calls and give high and low.
Show the steps and the answer
  1. Call to_fahrenheit(30): the parameter c takes the argument 30.

    Each call fills the parameter with the value written in its parentheses.

  2. Run the body: 30 × 9 / 5 + 32 = 270 / 5 + 32 = 54 + 32 = 86.0, which is returned and stored in high.

    Multiplication and division are done left to right before the addition, and / gives a decimal result in Python.

  3. Call to_fahrenheit(-10): now c = -10, so -10 × 9 / 5 + 32 = -90 / 5 + 32 = -18 + 32 = 14.0, stored in low.

    The same steps run again with a new argument; nothing from the first call carries over.

Answer: high = 86.0 and low = 14.0.

Takeaway: One definition, many calls: each call fills the parameters afresh and returns its own result.

Example 2 — A function tied to the keyboard

Standard

A function room_area() asks the user to type a width and a height, then returns width × height. A floor-planning program already has three rooms stored: 3 m × 4 m, 5 m × 2 m and 6 m × 6 m. Why is room_area awkward here, and what is the total floor area once it is fixed?
Show the steps and the answer
  1. Look at where room_area gets its inputs: it stops and waits for someone to type them.

    Inputs read inside the body tie the function to the keyboard, so the stored sizes cannot be handed to it.

  2. Move the inputs into parameters: def room_area(w, h): return w * h.

    Parameters let each call bring its own values.

  3. Call it three times: room_area(3, 4) = 12, room_area(5, 2) = 10, room_area(6, 6) = 36.

    One definition serves all three rooms with different arguments.

  4. Add the returned values: 12 + 10 + 36 = 58.

    Because each call returns a number, the results can be combined directly.

Answer: Rewritten as room_area(w, h), it gives 12, 10 and 36, a total floor area of 58 m².

Takeaway: A function is reusable when its inputs arrive as parameters and its result leaves through return, not through the keyboard and the screen.

Example 3 — Find the mistake: defined but never called

Application

Eli writes def welcome(name): print('Welcome, ' + name) and runs the program. Nothing appears. He says: "The function must be broken." Find the mistake and correct it.
Show the steps and the answer
  1. Read what the program contains: the def block and no line that uses the name welcome.

    def stores the function under its name; it does not run the body.

  2. Because nothing calls welcome, its print line never runs, so the screen stays empty.

    A function body runs only when a call reaches it, which never happens here.

  3. Add a call after the definition: welcome('Eli').

    The call jumps into the function with name = 'Eli'.

  4. Trace: 'Welcome, ' + 'Eli' gives 'Welcome, Eli', which is printed. A second call, welcome('Mara'), prints 'Welcome, Mara' from the same code.

    Each call reuses the stored steps with its own argument.

Answer: The function was never called. Add welcome('Eli') after the definition, and the program prints Welcome, Eli.

Takeaway: Defining a function only stores it; nothing happens until a line calls it by name with parentheses.

Where You'll See It

  • A recipe card

    Write the steps for 'make a smoothie' once, then follow that card whenever you want one — a function is a named set of steps you write once and call many times.

  • A 'send' button you reuse

    A send_message(text) function holds all the sending logic in one place, so every send button in the app just calls it instead of repeating the same code.

  • Splitting group homework

    A team can assign different functions to different people — one writes calculate_total, another writes format_receipt — and the pieces snap together because each function has a clear job.

Common Mistakes

  1. The slip: Defining a function makes its code run.

    Why it's tempting: You wrote out all the steps, so it feels like the program would carry them out.

    Instead: Defining a function only stores it; nothing happens until you call it by name with (), e.g. greet().

  2. The slip: Parameters and arguments are just two words for the same thing.

    Why it's tempting: They both refer to the function's inputs, so the distinction seems like nitpicking.

    Instead: A parameter is the placeholder name in the definition; an argument is the actual value you pass at the call site. greet(name) has parameter name; greet('Ana') passes argument 'Ana'.

  3. The slip: One big function that does everything is fine as long as it works.

    Why it's tempting: It runs correctly today, so splitting it up feels like extra busywork.

    Instead: Long do-everything functions are hard to test, reuse, and debug; each function should do one clear task so pieces can be checked and reused independently.


Mini Practice

Try these on your own. Tap Reveal when you want to check.

  1. def greet(name): return 'Hi ' + name. What does greet('Sam') return?

    Hint: Replace name with the argument.

  2. def perimeter(w, h): return 2 * (w + h). What is perimeter(3, 5) + perimeter(1, 1)?

    Hint: Work out each call separately, then add.

  3. def f(x): return x * x + 1. What is f(f(2))?

    Hint: Find the inner call first.

  4. def area(length, width): return length * width is called as area(6, 4). Name the parameters and the arguments, and give the value of length inside the function.

    Hint: Parameters appear in the definition; arguments appear in the call.

  5. You wrote the same 4 lines that compute a discount in three places in one file. Do you need a new function or a whole new module?

    Hint: How big is the repeated piece of work?

  6. A file contains only def say_hello(): print('Hello'). The student runs it, nothing prints, and they say: 'Python is broken.' What is missing?

    Hint: Defining a function and running it are different steps.

Want the full set?

50 practice questions for this concept — free to try, every one with a complete worked solution showing the why, not just the answer.

Frequently Asked Questions

What is a function with no name?

Many languages let you write a tiny function without naming it, called an anonymous function or a lambda. In Python, lambda x: x * 2 doubles its input, which is handy when another function needs a small rule, as in sorted(words, key=lambda w: len(w)), which sorts words by length. JavaScript writes the same idea as x => x * 2. For anything longer than one line, a named def is clearer.

Does a function have to be written above the line that calls it?

In Python, the def must have run before the call runs. A call at the top of a file, above the def, fails with NameError, but a function body may call another function defined further down, as long as both definitions have run before the first call happens. JavaScript is more forgiving: function declarations are moved to the top automatically, which is called hoisting.

What happens inside the computer when a function is called?

The program jumps. It notes where it was, copies the arguments into the parameters, and runs the function's body from the top. When the function returns, the program jumps back to the exact spot of the call, carrying the result. These return addresses are kept on a call stack, so a function can call a second one, which calls a third, and each still knows where to go back to.

Learning Path

You should know the basics from Function (Programming), defining and calling a function, plus Return Values, which send results back, and Modular Design, which splits a program into parts with one job each. This lesson adds designing your own functions: choosing parameters, keeping each one to a single task, and testing it alone. Next, Recursion has a function call itself, and Event Handler attaches a function to a click or key press.

See Also