Previous | Tutorial index | Next
Functions are the building blocks of any Python program. They allow you to encapsulate a piece of logic into a named, reusable subroutine that can be executed (called) whenever needed. Without functions, your code would be a long, repetitive, and unmanageable list of instructions. In this tutorial, we will explore what functions are, why they are essential, how they work under the hood, and how to use the builtâin functions that Python provides.
At its core, a function is a reusable block of code that performs a specific task. You can think of it as a small machine: you feed it some inputs (optional), it does its job, and optionally gives you back a result.
Imagine a coffee machine. It has a name (function name), you put in coffee beans and water (parameters/inputs), it processes them (body), and it outputs a cup of coffee (return value). You can use the same machine multiple times, with different types of beans, to get different coffees. That's exactly what a function does.
Functions bring numerous benefits to programming:
calculate_tax(), send_email()).Without functions (repetitive):
# Calculate area of rectangle 1
width1 = 5
height1 = 3
area1 = width1 * height1
print(area1)
# Calculate area of rectangle 2 (duplicate code)
width2 = 7
height2 = 2
area2 = width2 * height2
print(area2)
With a function (reusable):
def rectangle_area(width, height):
return width * height
print(rectangle_area(5, 3)) # 15
print(rectangle_area(7, 2)) # 14
The function version is shorter, clearer, and easier to modify.
Python comes with a rich set of builtâin functions that are always available. These include:
print() â displays output to the console.len() â returns the length of a sequence (string, list, etc.).type() â returns the type of an object.input() â reads user input from the console.int(), float(), str() â convert values to different types.max(), min(), sum(), sorted(), and many more.You can use these functions directly without defining them.
Custom functions are those you define yourself using the def keyword. They extend the language with your own logic. We will start defining custom functions in the next tutorials.
name = input("Enter your name: ")
print(f"Hello, {name}!")
print(f"Your name has {len(name)} characters.")
A function consists of several parts:
calculate_average).None).Hereâs a schematic breakdown:
def function_name(parameter1, parameter2):
"""Optional docstring describing the function."""
# Body: one or more statements
result = parameter1 + parameter2
return result
def keyword marks the beginning of the function definition.: ends the header.When you call a function (e.g., greet("Alice")), Python follows these steps:
return statement (or reaches the end), it sends a value back to the caller and control returns to the point where the function was called.def add(a, b):
result = a + b
return result
x = add(5, 3) # Call add; passes 5 to a, 3 to b; result becomes 8; returns 8; x = 8
print(x) # 8
Behind the scenes, Python uses a call stack to keep track of function calls. Each call creates a new stack frame that stores local variables and the return address. When a function returns, its frame is popped. This is why recursive functions can cause stack overflow if they go too deep.
The return value is the result that the function hands back to the caller. You use the return keyword to specify it. A function can:
return a, b).None).Example:
def multiply(a, b):
return a * b
product = multiply(4, 5) # product = 20
If you forget to include return, the function returns None. This is common for functions that only perform an action (like printing).
Itâs important to distinguish between these two terms:
a and b in def add(a, b):).5 and 3 in add(5, 3)).Parameters are the placeholders; arguments are the concrete data.
A function can have no parameters and no explicit return.
def say_hello():
print("Hello, world!")
say_hello() # Prints "Hello, world!"
Such functions are useful for performing actions without needing inputs or producing outputs.
In Python, methods are functions that belong to objects (e.g., list.append()). They are called on an object and often modify it. For now, we focus on standalone functions; methods will be covered later in objectâoriented programming.
print without parentheses prints the function object itself.def line must end with a colon.print, if, for, etc.return.Best practices:
calculate_total, get_user_input).In this tutorial, we have focused on the concept and the builtâin functions. In the upcoming tutorials, you will learn to define your own functions using def, specify parameters, return values, and much more.
What is a function?
Which of the following is a builtâin function in Python?
length()len()string.len()str_len()What does the return statement do?
True or False: A function must always have at least one parameter.
What is the difference between a parameter and an argument?
What does the following code print?
def show():
print("Inside function")
result = show()
print(result)
Inside function and NoneInside function and 0Inside function and Inside functionNoneWhich keyword is used to define a function in Python?
functiondefdefinefuncWhat is the output of print(type(5))?
<class 'int'><class 'float'><class 'str'><class 'function'>True or False: The body of a function must be indented.
Why are functions beneficial? (Select all that apply)
Exercise 1: Using Builtâins
Write a script that:
sum().min() and max().Exercise 2: Experimenting with input()
Write a program that:
"Hello, full_name!".len().Exercise 3: Calling a Function Many Times
Given the following function definition, call it five times using a loop (or manually):
def say_hi():
print("Hi there!")
Exercise 4: Return Value Usage
Write a function multiply(a, b) that returns the product. Then call it with numbers and store the result in a variable, print it.
result = multiply(4, 5) print(result) # 20
</details>
---
### đ Homework â Deeper Thinking
#### Short Answer Questions
**1. Function Call Analysis**
Given the following code:
```python
def mystery(x, y):
z = x + y
return z * 2
a = 5
b = 3
result = mystery(a, b)
print(result)
mystery return when called with (5, 3)?mystery(a, b) is called.2. Builtâin Functions Exploration
Research and list five builtâin functions that you havenât used yet. For each, write a short example of how to use it and what it does.
3. Functions and Modularity
Describe how you could use functions to write a program that calculates the area of a circle (Ďr²) and the circumference (2Ďr). Without writing the code, explain what parameters each function would take, what they would return, and how they could be reused.
4. Comparing with Other Languages
If you have experience with another programming language, how does the concept of functions in Python differ from functions in that language? If you donât, explain why functions are considered firstâclass citizens in Python.
5. Function Without Return
Write a function display_message(msg) that prints the message but does not return anything. Call it with "Hello". What is the value of result = display_message("Hello")? Print it. Explain the output.
result = display_message("Hello") # prints "Hello" print(result) # prints None
The function prints the message but returns `None` (implicitly). So `result` is `None`.
</details>
### Homework Hints
- **Q1**: `mystery(5,3)` â z=8, returns 16. Output: 16.
- **Q2**: Provide examples for `abs(-5)` etc.
- **Q3**: `circle_area(radius)` returns Ďr²; `circle_circumference(radius)` returns 2Ďr. Both take one parameter.
- **Q4**: In Python, functions are objects; can be assigned to variables, passed as arguments, etc.
- **Q5**: `result = display_message("Hello")` will print "Hello" and `result` will be `None`; printing `result` shows `None`.
## Summary
In this tutorial, you have learned:
- The definition of a function as a reusable subroutine.
- Why functions are essential for code reuse, modularity, testing, and maintainability.
- The difference between builtâin functions (like `print()`, `len()`, `type()`) and custom functions.
- The parts of a function: name, parameters, body, and return value.
- How function calls work: control transfer, argument assignment, execution, and returning.
- The distinction between parameters and arguments.
- Best practices and common pitfalls.
Functions are the cornerstone of structured programming. In the next tutorials, you will dive deeper into creating your own functions, handling arguments, returning values, and using advanced function features like lambdas and decorators.
*Happy coding with functions!*
<!-- tutorial-navigation:start -->
[Previous](../unit-6/t-7.html) | [Tutorial index]() | | [Next](t-2.html)
<!-- tutorial-navigation:end -->