Parameters and Arguments
Before we go further it is important to understand the difference between parameters and arguments. These two words are often used interchangeably but they mean different things and using the correct term will make you a more effective communicator as a developer.
Think of a function as a form. Parameters are the blank fields on the form waiting to be filled in. Arguments are the actual information you write into those fields when you submit it.
Parameters
A parameter is a variable defined inside a function's parentheses when you create the function. It acts as a placeholder for a value the function will receive when it is called. The parameter has no real value until something is passed in.
In this example name and age are
parameters:
Arguments
An argument is the actual value you pass into a
function when you call it. The argument fills in the placeholder
that the parameter created. In this example "Eric"
and 26 are arguments:
Types of Parameters and Arguments
There are several ways to pass arguments into a function. Each has its own use case and you will see all of them in real world Python code.
-
Positional values are matched to parameters
by their order. The first argument fills the first parameter,
the second fills the second, and so on.
greet("Kevin", 53) -
Keyword values are matched to parameters by
name rather than position. This means the order does not matter.
greet(age=53, name="Kevin") -
Default parameters have a fallback value that
is used if no argument is provided when the function is called.
def greet(name, age=30): -
*args allows a function to accept any number
of positional arguments. Useful when you do not know in advance
how many values will be passed in.
def add(*numbers): -
**kwargs allows a function to accept any number
of keyword arguments. Each one is received as a key value pair.
def show(**info):
We will work through examples of each type in the sections that follow.
Parameters, Arguments and return
In the previous lesson we created functions that performed tasks but all of the logic and data lived inside the function. In the real world functions need to accept data from outside, work with it, and hand something back. That is where parameters, arguments and return come in.
We need to understand
return, because without it your functions will
always produce None.
return and None
Run the code below and observe what happens:
Nothing printed. We forgot the print() function. But
even with print() something unexpected happens:
We see None. But why? The function is clearly adding
the two numbers together so where is the result?
The problem is that the function is performing the
calculation but it is not creating anything in memory
to hold the answer. The result exists for a fraction of a second
and then disappears. Python has nothing to give back to
print() so it returns None.
To fix this we need to use return.
The return keyword tells the function to take the
result and hand it back to wherever the function
was called from, creating a value in memory that can be used,
stored or printed.
Now we get 7. The function adds the numbers and
return hands the result back to print().
A good rule to follow when writing functions is this: a function should do one thing, do it well, and return something. While functions can technically do multiple things at once, keeping them focused makes your code easier to read, test and reuse.
Using return with Variables
Because return creates a value in memory, we can assign
that value to a variable and use it anywhere in our code, including
inside other function calls.
total = sum(2, 5) calls the function and stores the
returned value in total. We can then pass
total into the next function call just like any other
variable. The last two print statements produce the same result,
one using the variable and one nesting the function call directly.
Nested Functions
You can also define a function inside another function. This is called a nested function. The inner function is only accessible from inside the outer function. Try running the first example and observe the result:
None again. The inner function has a
return statement but the outer function does not.
Python runs sum(), finds sum_sum() inside
it but never gets the result back out. The fix is to
return the inner function call from the outer function:
Now we get 10. But notice something. In the next
example the inner function uses completely different parameter
names. Does it still work?
Yes it does. And here is why. Parameter names are
local to the function they belong to. When we
write return sum_sum(num1, num2) we are passing the
values of num1 and num2
from the outer function into the inner function. The inner function
receives those values and assigns them to its own parameter names
n1 and n2. The names are different but
the values are the same. This concept is called
scope and we will cover it in detail in an
upcoming lesson.
return Exits the Function
There is one important behaviour of return that you
must always keep in mind. The moment Python hits a
return statement it immediately exits the
function. Any code written below the return
line will never run.
Try the example below. Notice that the first
print() is above the return and the
second is below it. Predict which one will run before you execute
the code.
Only the first print ran. The moment Python hit
return num1 + num2 it exited the function and the
second print() was never reached. It does not matter
how much code you write below a return statement,
Python will never execute it.
This is an easy mistake to make and a common source of bugs,
especially in longer functions. Always make sure that any code
you need to run is placed before the
return statement.
Time to experiment!
Coding Exercises (VS Code) Instructions:
- Create a file named parameters.py in your part51 folder.
- Complete the tasks and use # comments to explain your answers.
Exercise 1: Parameters and Arguments
-
Task: Define a function called
introduce()that takes two parameters,nameandage. - Goal: Inside the function print a sentence using both parameters. Call the function using positional arguments and then call it again using keyword arguments in a different order. Write a comment explaining the difference between the two calls and why the output is the same.
Exercise 2: Default Parameters
-
Task: Define a function called
greet()that takes two parameters,nameandlanguagewith a default value of"English". -
Goal: Call the function three times. Once
without passing a language, once passing
"Spanish"and once passing"Thai". Print a different greeting based on the language inside the function. Write a comment explaining when default parameters are useful.
Exercise 3: return
-
Task: Define a function called
multiply()that takes two parametersnum1andnum2and returns their product. -
Goal: Store the result in a variable called
resultand print it. Then passresultback into the function as one of the arguments and print the new result. Write a comment explaining what would happen if you removed thereturnstatement.
Exercise 4: *args
-
Task: Define a function called
add_all()that uses*argsto accept any number of numbers. -
Goal: Inside the function use a loop to add
all the numbers together and return the total. Call the function
three times with a different number of arguments each time.
Write a comment explaining what
*argsactually is inside the function and what data type it is.
Exercise 5: return Exits the Function
-
Task: Define a function called
check_age()that takes one parameterage. -
Goal: Write the function so that if the age
is under 18 it prints
"Access denied."and returns immediately. If the age is 18 or above it prints"Access granted.". Call the function with an age under 18 and then with an age of 18 or above. Write a comment explaining why the code after the firstreturnnever runs when the age is under 18.
Don't Forget to commit and Push!