SkarpSkarp

Chapter 7 of 11

Packaging Logic: Functions and Reusable Code

As your programs grow, repeating the same logic becomes messy and error-prone. Functions let you name chunks of work, reuse them anywhere, and write cleaner, more professional-looking code from the very beginning.

15 min readen

Why We Need Functions

The Problem

As programs get bigger, you often need the same logic in several places. Copy‑pasting code makes programs hard to read, easy to break, and tiring to write.

What Is a Function?

A function is a named chunk of code that does one job. You define it once, then call it whenever you need that job done, instead of repeating the same code.

Built‑in vs Your Own

You already use functions like `print()`, `len()`, and `input()`. These are built‑in. In this lesson, you will learn to define your own functions using `def`.

What You Will Learn

You will define functions with `def`, use parameters and return values, and see how variables inside a function are separate from variables outside it (scope).

Defining and Calling Your First Function

Here is the basic pattern for a function in Python:

```python

def say_hello():

print("Hello!")

calling the function

say_hello()

say_hello()

```

Line by line:

  • `def sayhello():` tells Python: "I am defining a function named `sayhello`."
  • The indented line under it is the body: the code that runs when you call the function.
  • `say_hello()` at the bottom calls the function. You can call it as many times as you like.

Think of `def` as teaching Python a new command, and calling the function as using that new command.

Avoiding Repetition With Functions

Repeated Code

In a text game, you might show the same welcome message at the start of each level. Without a function, you repeat the same three `print` lines every time.

Without a Function

```python

print("=== Welcome to the Dungeon ===")

print("You have 3 lives.")

print("Good luck, hero!\n")

later in the game

print("=== Welcome to the Dungeon ===")

print("You have 3 lives.")

print("Good luck, hero!\n")

```

With a Function

```python

def show_intro():

print("=== Welcome to the Dungeon ===")

print("You have 3 lives.")

print("Good luck, hero!\n")

later in the game

show_intro()

```

Why This Helps

Now the message lives in one place. To change it, you only edit `showintro`. Every call to `showintro()` automatically uses the updated message.

Spot Where a Function Would Help

Look at this code and think:

```python

print("Loading...")

print("Please wait")

some work here

print("Loading...")

print("Please wait")

some more work here

print("Loading...")

print("Please wait")

```

  1. What short, clear name could you give to a function that replaces the repeated `print` lines?
  2. In your head or on paper, write what the function definition might look like using `def`.
  3. Mark (mentally) the places where you would call that function.

Pause and actually do this before moving on. Saying the function name out loud can help. For example: `showloading()` or `displayloading_message()`.

Parameters: Giving Functions Input

Why Parameters?

Sometimes you want a function to do the same kind of job, but with different data each time. Parameters let you give input to a function when you call it.

Parameters vs Arguments

A parameter is the name in the function definition. An argument is the actual value you pass when calling the function. Example: `def greet(name):` then `greet("Mia")`.

Single Parameter Example

```python

def greet(name):

print("Hello, " + name + "!")

greet("Mia")

greet("Alex")

```

Multiple Parameters Example

```python

def describepet(petname, animal_type):

print("I have a " + animaltype + " named " + petname + ".")

describe_pet("Luna", "cat")

describe_pet("Rex", "dog")

```

Check: Parameters and Arguments

Look at this function and call:

```python

def announce(score, level):

print("Level", level, "finished with score", score)

announce(1200, 3)

```

Which statement is correct?

In the code shown, which statement is correct?

  1. `score` and `level` are parameters; `1200` and `3` are arguments.
  2. `1200` and `3` are parameters; `score` and `level` are arguments.
  3. There are no parameters, only arguments.
Show Answer

Answer: A) `score` and `level` are parameters; `1200` and `3` are arguments.

`score` and `level` are the names in the function definition, so they are parameters. `1200` and `3` are the actual values passed in when calling `announce`, so they are arguments.

Return Values: Getting Results Back

Doing vs Calculating

Some functions just do something (like printing). Others calculate a result and give it back using `return`. Return values make functions more reusable.

Print Only

```python

def addandprint(a, b):

print(a + b)

addandprint(3, 4) # prints 7, but we cannot reuse the result

```

Using return

```python

def add(a, b):

return a + b

result = add(3, 4)

print(result) # 7

print(result * 2) # 14

```

Vending Machine Analogy

A function with a return value is like a vending machine: you give input and get something back. `return` is how the function hands the result back to you.

Check: Using return

Look at this code:

```python

def square(x):

return x * x

value = square(5)

print(value)

```

What does this program print?

What does the code print?

  1. 5
  2. 10
  3. 25
  4. It prints nothing
Show Answer

Answer: C) 25

`square(5)` returns `5 * 5`, which is 25. That value is stored in `value`, and `print(value)` prints 25.

Variable Scope: Local vs Global

What Is Scope?

Scope is about where a variable can be seen and used. Global variables live outside functions. Local variables live inside functions.

Global vs Local

  • Global: created outside any function; can be read from anywhere.
  • Local: created inside a function; only exists while the function runs.

Scope Example

```python

message = "Hello from the outside" # global

def show_messages():

inside = "Hello from inside" # local

print(message)

print(inside)

```

After the Call

```python

show_messages()

print(message) # OK

print(inside) # ERROR: inside is not defined here

```

Predict the Output: Scope Practice

Try to predict what this code does before you run it:

```python

count = 10

def show_count():

count = 5

print("Inside:", count)

show_count()

print("Outside:", count)

```

Questions:

  1. What will it print for `Inside:`?
  2. What will it print for `Outside:`?
  3. Why are they different?

Think it through, then check by running it in a Python shell or notebook.

Review: Functions and Reuse

Flip through these cards to review the key ideas from this module.

Function
A named block of code that does one job. You define it once with `def` and call it whenever you need that job done.
Function definition
The part of the code where you create a function, starting with `def name():` and followed by an indented body.
Function call
Using a function by writing its name followed by parentheses, for example `greet("Mia")`.
Parameter
A variable name in the function definition that receives a value when the function is called.
Argument
The actual value you pass into a function when you call it, for example `"Mia"` in `greet("Mia")`.
Return value
The result that a function sends back using `return`. You can store it in a variable or use it in expressions.
Local variable
A variable created inside a function. It can only be used while that function is running.
Global variable
A variable created outside any function. It can be read from anywhere in the file, though changing it inside functions is usually avoided in beginner code.
Why use functions?
To avoid repeating code, make programs easier to read, update, and test, and to give clear names to chunks of logic.

Key Terms

scope
The part of the program where a variable can be seen and used, such as inside a function (local) or in the whole file (global).
argument
A value passed into a function when it is called, which is assigned to the function's parameters.
function
A named block of code that performs a specific task and can be reused by calling it.
parameter
A variable name listed in a function's parentheses that receives a value when the function is called.
return value
The result that a function sends back to the caller using the `return` statement.
function call
The act of using a function by writing its name followed by parentheses, optionally with arguments inside.
local variable
A variable created inside a function, accessible only within that function.
global variable
A variable created outside any function, accessible from the whole file.
built-in function
A function that is provided by Python itself, such as `print()`, `len()`, or `input()`.
function definition
The code that creates a function, starting with `def`, the function name, parentheses, and a colon, followed by an indented body.

Finished reading?

Test your understanding with a custom practice exam on this chapter.

Test yourself