Parameters
Parameters are pieces of information you can send into a subprogram (like a procedure or function) to help it do its job.
Procedure with parameters
A procedure that displays a message might need a name as a parameter so it can say:
“Welcome, Jamie!”
def welcome_message(name): # name is a formal parameter
print("Welcome", name)
# Main
welcome_message("Jamie") # "Jamie" is the actual parameter
def welcome_message(name): # Formal parameter
print("Welcome", name)
# Main
customer = "Jamie"
welcome_message(customer) # Actual parameter
Function with parameters
A function that receives numbers as parameters and returns their total.
def add_nums(num1, num2) # Formal parameters
total = num1 + num2
return total
# Main
total = add_nums(3,7) # Actual parameters
print(total)
def add_nums(num1, num2) # Formal parameters
total = num1 + num2
return total
# Main
num1 = 3
num2 = 7
total = add_nums(num1, num2) # Actual parameters
print(total)
def add_nums(num1, num2, num3, num4) # Formal parameters
total = num1 + num2
return total
# Main
total = add_nums(3,6,2,8) # Actual parameters
print(total)
Formal and actual parameters
| Type | What it means | Where it’s used |
|---|---|---|
| Formal parameter | A placeholder for a value | In the subprogram definition |
| Actual parameter | The real value you pass in | When calling the subprogram |
Think of formal parameters as empty boxes, and actual parameters as the values that fill them.
Why use parameters?
-
To send information into a subprogram
-
To make subprograms work with different data each time
-
To avoid repeating code by reusing the same subprogram
Key points
-
A subprogram can have one or more parameters
-
Parameters make your code flexible and reusable
-
The order of parameters matters – it must match between the call and the definition