Use parameters
11.3 Structured Programming – Using Parameters
What are Parameters?
Think of a parameter as a placeholder in a recipe. The recipe (function) tells you how to make a dish, but the exact ingredients (values) can change each time you cook. In programming, a parameter is a variable that receives a value when a function is called. 📚
Why Use Parameters?
- Reusability – Write a function once, use it many times with different data.
- Modularity – Break complex tasks into smaller, manageable parts.
- Clarity – Parameters make it clear what data a function needs.
Defining Parameters in Python
In Python, you define parameters inside the parentheses of a function definition:
def greet(name):
print(f"Hello, {name}!")
Here, name is a parameter. When we call greet("Alice"), name receives the value "Alice".
Example: A Simple Calculator
Let’s build a function that adds two numbers. The numbers are parameters, so we can add any pair of numbers we like.
def add(a, b):
return a + b
result = add(5, 7) # result is 12
The add function can now be used for any two numbers, not just 5 and 7. 🎲
Parameters vs. Arguments
| Term | Definition |
|---|---|
| Parameter | Placeholder in function definition. |
| Argument | Actual value passed when calling the function. |
Exam Tip Box
📌 Remember: When writing a function, list the parameters in the order they are needed. In the exam, you may be asked to write a function that takes two parameters and returns their product. Make sure you include the return statement – otherwise the function will return None by default.
📌 Tip: Use descriptive parameter names like length or radius instead of single letters. This makes your code easier to read and less error‑prone.
Advanced: Default Parameters
You can give a parameter a default value. If the caller does not provide that argument, the default is used.
def greet(name="Student"):
print(f"Hello, {name}!")
greet() # prints "Hello, Student!"
greet("Bob") # prints "Hello, Bob!"
This is handy for optional features or when you want a sensible default. 🎯
Mathematical Example with LaTeX
Suppose we want a function that calculates the area of a circle. The formula is:
$$A = \pi r^2$$
In code, r is a parameter:
import math
def circle_area(radius):
return math.pi * radius ** 2
Call circle_area(3) to get the area for a radius of 3 units.
Practice Exercise
- Create a function
multiply(a, b)that returns the product of two numbers. - Test it with the pairs (4, 5) and (7, 0).
- Modify the function to use a default value of 1 for
b.
Try to write the function with clear, descriptive names and include a return statement. Good luck! 🚀
Revision
Log in to practice.