Python • Functions and Program Structure

Defining Functions — Define functions with def and return values

Learn to package reusable logic into functions using Python's def keyword and return statement.

Code braces with terminal and markup symbols representing Python programming.
Inside this lesson 10 sections 5 questions 6 figures

SECTION 1

Historical Context & Motivation

Imagine you are writing a program that needs to calculate the area of a circle in five different places. Without functions, you would copy and paste the same formula five times. If you later found a bug, you would have to fix it in every single copy. This exact frustration is what led computer scientists to invent the concept of a function — a named, reusable block of code that performs a specific task.

The idea of breaking programs into smaller, self-contained pieces has deep roots in mathematics and early computing. Mathematicians have used function notation like f(x) = x² for centuries, and programming languages adopted this same philosophy. As programs grew larger and more complex, the ability to define and call functions became one of the most important tools in a programmer's toolkit.

1940s • Subroutines in Early Machines

Pioneers like Ada Lovelace and Alan Turing recognized the need for reusable instruction sequences. Early computers used "subroutines" — blocks of machine code that could be jumped to and executed repeatedly.

1958 • LISP and First-Class Functions

John McCarthy's LISP language treated functions as fundamental building blocks, allowing programmers to define, pass, and combine them freely — a concept that shaped all future languages.

1972 • C Language Standardizes Functions

The C programming language popularized the pattern of defining functions with a name, parameters, and a return type. This syntax influenced nearly every modern language, including Python.

1991 • Python Is Born

Guido van Rossum released Python with a clean, readable syntax for defining functions using the def keyword. Python's design philosophy emphasized simplicity, making functions approachable for beginners.

The central question this lesson addresses is straightforward but powerful: How do you define your own reusable pieces of code in Python, and how do you send results back from them? By mastering the def keyword and the return statement, you will unlock the ability to write cleaner, more organized, and more powerful programs.

SECTION 2

Core Principles & Definitions

A function in Python is a self-contained block of code that you define once and can run (or "call") as many times as you need. Every function definition follows the same basic structure: a header line that names the function and lists its inputs, followed by an indented body that contains the instructions. Let's break down the essential building blocks.

1

The def Keyword

Every function definition starts with def, followed by the function name, parentheses for parameters, and a colon. This header line tells Python you are creating a new function.
2

Parameters & Arguments

Parameters are the variable names listed inside the parentheses when you define a function. Arguments are the actual values you pass in when you call the function.
3

The Function Body

The indented lines below the header form the function body. Python uses indentation (typically four spaces) to determine which lines belong to the function.
4

The return Statement

The return statement sends a value back to wherever the function was called. Once Python hits a return, it immediately exits the function. Without a return, the function returns None by default.
5

Calling a Function

To execute a function, write its name followed by parentheses containing any arguments. The call expression evaluates to whatever value the function returns, so you can store it in a variable or use it in other expressions.
✦

KEY TAKEAWAY

Think of a function like a vending machine. You define the machine once (deciding what it does inside). You feed in arguments (like inserting coins and pressing a button). The machine processes your input and returns a product (the output). You can use the same machine over and over with different inputs to get different outputs.

SECTION 3

Visual Explanation — Anatomy of a Function

ANATOMY OF A PYTHON FUNCTIONdefcircle_area(radius):def keyword(starts definition)Function nameParameter(input variable)│ indent"""Return the area of a circle."""area = 3.14159 * radius ** 2Function body(indented code)return areareturn statement(sends value back)CALLING THE FUNCTIONresult = circle_area(5)Argument(actual value passed)result → 78.53975The returned value is stored in the variable "result"
This diagram shows the complete anatomy of a Python function. The def keyword begins the definition, followed by the function name and parameters. The indented body contains the logic, and the return statement sends the result back to the caller.

Notice how the diagram highlights two distinct phases. First, you define the function — this is like writing a recipe. Python reads the definition and remembers it, but nothing actually runs yet. Second, you call the function by writing its name with parentheses. That's when Python actually executes the code inside the body, substitutes the argument value for the parameter, and sends the result back through return.

SECTION 4

How Functions Work — The Execution Flow

Understanding what happens behind the scenes when Python encounters a function definition and a function call is crucial for debugging and writing effective code. Let's walk through the exact sequence of events that Python follows.

Step-by-Step Execution Model

When Python reaches a def statement, it does not run the function body immediately. Instead, it creates a function object in memory and associates it with the function name. Think of this as Python filing away the recipe for later use. The code inside the body is stored but not executed.

When Python reaches a function call — for example, circle_area(5) — it pauses the current line of code, jumps into the function body, assigns the argument value 5 to the parameter radius, and executes each line in order. When it hits return area, Python takes the value of area and sends it back to the calling location, replacing the function call expression with the returned value.

The General Syntax Pattern

FUNCTION DEFINITION SYNTAX

deffunctionname(param1,param2,…):bodyreturnvaluedef function_name(param₁, param₂, …): body return value

function_name — a descriptive name following Python naming rules (lowercase, underscores). param₁, param₂ — input variables (zero or more). body — indented statements. return value — optional; sends a result back to the caller.

FUNCTION CALL SYNTAX

variable=functionname(arg1,arg2,…)variable = function_name(arg₁, arg₂, …)

arg₁, arg₂ — the actual values passed to the function. The return value can be stored in a variable, printed, or used in another expression.

What Happens Without return?

If you omit the return statement entirely, or write return with no value, the function automatically returns the special value None. This is Python's way of saying "nothing meaningful was produced." Functions that perform an action (like printing to the screen) without returning a value are sometimes called void functions or functions with side effects. Understanding the difference between a function that returns a value and one that merely prints a value is one of the most common sources of confusion for new programmers.

⚠

print() vs return

print() displays text on the screen for humans to read, but the function still returns None. return sends a value back to the program for further use by other code. If you need to use a function's result in a calculation, you must use return, not print().

SECTION 5

Common Function Patterns

Functions come in a variety of shapes depending on how many parameters they accept and what they return. Recognizing these common patterns will help you decide how to structure your own functions. The diagram below shows four fundamental patterns you will encounter regularly.

FOUR COMMON FUNCTION PATTERNS1. NO PARAMETERS, NO RETURNdef greet():print("Hello!")Call: greet()Output: Hello!Returns: None (no return statement)2. PARAMETERS, WITH RETURNdef add(a, b):return a + bCall: result = add(3, 7)result → 10Returns: the sum of a and b3. DEFAULT PARAMETER VALUEdef power(base, exp=2):return base ** expCall: power(5) → 25Call: power(5, 3) → 125exp defaults to 2 if not provided4. MULTIPLE RETURN VALUESdef divide(a, b):q = a // br = a % breturn q, rCall: quot, rem = divide(17, 5)Returns: (3, 2) as a tuple
Four common function patterns: (1) a simple action with no inputs or outputs, (2) the most typical pattern with parameters and a return value, (3) a function with a default parameter, and (4) a function that returns multiple values as a tuple.

Pattern 2 — a function that takes parameters and returns a value — is the most common and most useful pattern you will write. It transforms inputs into outputs, much like a mathematical function. Pattern 3 introduces default parameter values, which let you make some arguments optional. When calling power(5), the parameter exp automatically receives the value 2 because of the exp=2 in the definition.

Pattern 4 shows that Python functions can return multiple values at once by separating them with commas after return. Python automatically wraps these into a tuple, and you can unpack them into separate variables on the calling side. This is a convenient Python feature that many other languages do not offer as easily.

SECTION 6

Worked Example — Building a Grade Calculator

Let's put everything together by writing a function that calculates a student's letter grade based on their numerical score. This example demonstrates defining a function with one parameter, using conditional logic in the body, and returning a meaningful result.

Building a Letter Grade Function

  1. 1

    Step 1 — Define the Function Header

    Start by choosing a clear, descriptive name. We will call it get_letter_grade. It takes one parameter — the student's numerical score. Write the header line:
    def get_letter_grade(score):
  2. 2

    Step 2 — Write the Conditional Logic

    Inside the function body (indented), use if/elif/else to check the score range. Each branch returns the corresponding letter grade immediately. Notice that each return exits the function as soon as a match is found.
    if score >= 90: return "A" elif score >= 80: return "B" elif score >= 70: return "C" elif score >= 60: return "D" else: return "F"
  3. 3

    Step 3 — Call the Function and Use the Result

    Now call the function with a specific score. The returned string is stored in a variable, which we then use in a print statement. This demonstrates the key advantage of return — the result can be saved, compared, or passed to other functions.
    my_grade = get_letter_grade(85) print("Your grade is:", my_grade)
  4. 4

    Step 4 — Trace the Execution

    When Python runs get_letter_grade(85), it assigns score = 85. It checks 85 >= 90 → False. Then 85 >= 80 → True, so it executes return "B". Python exits the function and replaces the call with "B".
    Output: Your grade is: B
  5. 5

    Step 5 — Reuse with Different Inputs

    The power of the function is reusability. You can call it with any score:
    print(get_letter_grade(92)) # A print(get_letter_grade(73)) # C print(get_letter_grade(55)) # F

SECTION 7

return vs print — Strengths & Limitations

One of the most common mistakes beginners make is confusing return with print(). Both can seem to "produce" a value, but they serve very different purposes. The table below clarifies the distinction.

Featurereturnprint()
PurposeSends a value back to the calling codeDisplays text on the screen
Can the value be stored in a variable?Yes — x = func()No — the variable would hold None
Can the value be used in expressions?Yes — func() + 10No — would cause an error
Visible to the user?Not unless you also print the resultYes — always appears in the console
Effect on function executionImmediately exits the functionFunction continues running

Comparison of return vs print() in Python functions

✦

KEY TAKEAWAY

Think of return as handing a finished report to your boss — they can read it, file it, or pass it along. Think of print() as shouting the answer out loud in a room — everyone hears it, but no one has a copy to work with later. In most cases, you want your functions to return values so other parts of your program can use them.

SECTION 8

Connection to Advanced Concepts

Defining functions with def and return is the foundation that unlocks many advanced programming techniques. As you progress in your Python journey, you will encounter more sophisticated ways to structure and use functions. The table below previews some of these advanced topics and shows how they build on what you learned today.

What You Learned TodayAdvanced ConceptHow It Builds On This
Defining functions with defLambda functionsShort, anonymous one-line functions using lambda instead of def
Passing parameters*args and **kwargsAccept a variable number of positional or keyword arguments
Returning valuesGenerators and yieldProduce a sequence of values lazily, one at a time, instead of all at once
Calling functionsRecursionA function that calls itself to solve smaller versions of the same problem
Organizing code into functionsClasses and methodsGrouping related functions and data together using object-oriented programming

How today's concepts connect to advanced Python topics

Don't worry about mastering these advanced topics right now. The key point is that everything in Python's function system — from one-line lambdas to complex class methods — is built on the same core ideas you learned today: naming a block of code, accepting inputs through parameters, and producing outputs through return. Master these fundamentals and the advanced concepts will feel like natural extensions.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

What is the difference between a parameter and an argument? In the code below, identify which is which: def double(n): return n * 2 result = double(7)
Show answer
A parameter is the variable name in the function definition — in this case, n is the parameter. An argument is the actual value passed when the function is called — here, 7 is the argument. When double(7) is called, Python assigns the argument 7 to the parameter n, so inside the function body, n * 2 evaluates to 14, which is returned and stored in result.

Question 2: BASIC CALCULATION

Write a function called fahrenheit_to_celsius that takes a temperature in Fahrenheit as a parameter and returns the equivalent temperature in Celsius. The formula is: C = (F − 32) × 5 ÷ 9. Test it with fahrenheit_to_celsius(212).
Show answer
The function definition is: def fahrenheit_to_celsius(f): return (f - 32) * 5 / 9 When called with fahrenheit_to_celsius(212), Python substitutes f = 212, computes (212 - 32) * 5 / 9 = 180 * 5 / 9 = 100.0, and returns 100.0. This is correct because 212°F is the boiling point of water, which equals 100°C.

Question 3: INTERMEDIATE

Write a function called is_even that takes an integer and returns True if the number is even and False if it is odd. Then write a second function called count_evens that takes a list of integers and uses is_even to count how many even numbers are in the list. Test with [3, 8, 15, 22, 7, 40].
Show answer
def is_even(n): return n % 2 == 0 def count_evens(numbers): count = 0 for num in numbers: if is_even(num): count += 1 return count Calling count_evens([3, 8, 15, 22, 7, 40]) returns 3 because 8, 22, and 40 are even. This example shows how one function can call another — count_evens relies on is_even to do the checking, keeping each function focused on a single task.

Question 4: APPLIED

A pizza shop charges $8.00 for a small pizza (10-inch diameter), $12.00 for a medium (14-inch), and $16.00 for a large (18-inch). Write a function called price_per_sq_inch that takes the price and diameter as parameters and returns the price per square inch of pizza. Which size is the best deal? (Use the formula: area = π × (diameter ÷ 2)²; use 3.14159 for π.)
Show answer
def price_per_sq_inch(price, diameter): radius = diameter / 2 area = 3.14159 * radius ** 2 return price / area Small: price_per_sq_inch(8, 10) → 8 ÷ 78.54 ≈ $0.102 per sq inch. Medium: price_per_sq_inch(12, 14) → 12 ÷ 153.94 ≈ $0.078 per sq inch. Large: price_per_sq_inch(16, 18) → 16 ÷ 254.47 ≈ $0.063 per sq inch. The large pizza is the best deal because it has the lowest price per square inch. This demonstrates how returning a value lets you compare results across multiple function calls.

Question 5: CRITICAL THINKING

Consider the following code. Predict exactly what will be printed, and explain why. Pay close attention to the difference between return and print(). def mystery(x): print("A:", x) x = x + 10 print("B:", x) return x result = mystery(5) print("C:", result) print("D:", mystery(result))
Show answer
The output is: A: 5 B: 15 C: 15 A: 15 B: 25 D: 25 First call mystery(5): prints "A: 5", adds 10 to get 15, prints "B: 15", returns 15. That return value is stored in result. Then "C: 15" is printed. Next, mystery(result) is called with 15 — it prints "A: 15", adds 10 to get 25, prints "B: 25", and returns 25. That returned 25 is passed to the outer print(), producing "D: 25". This problem illustrates that print() outputs text immediately while the function runs, whereas return delivers a value only after the function finishes.

SUMMARY

Lesson Summary

Summary

In this lesson, you learned how to define functions using the def keyword, give them descriptive names, and specify parameters to accept input values. You explored the critical distinction between return (which sends a value back to the calling code for further use) and print() (which only displays text on the screen). You also saw how arguments are the actual values passed to a function when you call it, while parameters are the placeholder variable names in the definition.

Key patterns you should remember include: functions with default parameter values for optional arguments, functions that return multiple values as tuples, and the fact that omitting return causes a function to return None automatically. Functions are the fundamental building blocks of organized, reusable code — every program you write from now on should make use of them.

Varsity Tutors • Python • Defining Functions — Define functions with def and return values