A function that does the exact same thing every time is useful, but a function that can be customized each time you call it is even better. You can achieve this flexibility by using parameters. Parameters allow you to pass data, called arguments, into a function when you call it.
Table of Contents
📥 What Are Parameters and Arguments?
Parameters are the variables you list inside the parentheses when you define a function. They act as placeholders for the data the function will receive. Arguments are the actual values you provide for those parameters when you call the function. For example:def greet(name): # 'name' is a parameter
print(f"Hello, {name}!")
greet("Alice") # "Alice" is an argument
When you call `greet(“Alice”)`, Python assigns the value “Alice” to the `name` parameter inside the function.
🎁 Providing Default Values for Parameters
Sometimes you want a parameter to have a default value if no argument is provided. You can do this by assigning a value to the parameter directly in the function definition using an equals sign. For example:def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
Now you can call this function with one argument, greet("Bob")
, and it will use the default greeting. Or you can provide a different greeting as a second argument: greet("Charlie", "Hi")
.
📤 Returning a Value from a Function
Many functions need to compute a result and send it back to the part of the code that called it. You do this using the return
keyword. When a `return` statement is executed, the function immediately stops and sends back the specified value. For example:def add(a, b):
return a + b
sum_result = add(5, 3) # sum_result will be 8
This allows you to store the function’s output in a variable and use it for further calculations.
By using parameters and return values, you can create functions that are not only reusable but also highly flexible and powerful, forming the core building blocks of any significant Python program.
—
Stephenson, Ben. The Python Workbook: A Brief Introduction with Exercises and Solutions. 3rd ed., Springer, 2025.
- Python Coding Essentials: Reliability by Abstraction
- Python Coding Essentials: Different Types of Data
- Python Coding Essentials: Embrace Storage and Persistence
- Python Coding Essentials: Neater Code with Modules
- Python Coding Essentials: Lock Down with Data Encryption
- Python Coding Essentials: Files and Modules Done Quickly
- Python’s Itertools Module – How to Loop More Efficiently