What Is A Function?: Greeting
What Is A Function?: Greeting
def greeting():
"""This function prints a greeting"""
print("Hello!")
greeting()
OUTPUT:
Hello!
When defining a function, the first thing you need is the appropriate Python
keyword: def. This keyword tells the Python interpreter that what follows is a function.
def
The name of the function follows the def keyword. The name can be anything you'd
like, but you want to ensure that it makes sense. Above, the function name is greeting.
Function naming conventions and rules are similar to those for variable names.
def greeting
After the function's name, you'll find parentheses (). When you need to provide
information for the function, you'll find parameters inside of the parentheses.
Parameters will be discussed shortly, but the above function has none, so there's
nothing between each parenthesis.
def greeting()
def greeting():
All of the Python code that will be executed when the function is used must be
indented, as you can see above. This is no different that an if block or for loop. The
indentation is maintained until the end of the function's definition.
The first line of code of the function is called a docstring (documentation string).
A docstring is used to specify the purpose of the function. A function's docstring is
defined by including a string literal as the first statement in the function's definition.
A string literal is text enclosed within triple-quotes, and they can be a single line or
multiple lines. Although it is not required, all functions should have a docstring.
def greeting():
"""This function prints a greeting"""
def greeting():
"""This function prints a greeting"""
print("Hello!")
greeting()
Below the function definition, you'll find the line of code that calls the
function: greeting(). When you define a function, like how greeting was defined above,
the code is not executed unless it is called, or invoked.
def increment(value):
"""This function increments a value"""
print("Old value =", value)
value += 1
print("New value =", value)
increment(10)
OUTPUT:
Old value = 10
New value = 11
Function Parameters
In the definition of the increment function above, you should see that there is now a
variable name nestled between the parenthesis:
def increment(value):
increment(10)
If a value for the parameter is left out of the call to the function, it will produce an
error (NOTE: the # ... below means that the other code was left out in order to
highlight the relevant code; you will see this from time-to-time in this course):
# ...
increment()
OUTPUT:
As you can see above, the error was verify specific as to the problem:
TypeError: increment() missing 1 required positional argument: 'value'
But, what is an argument?
Arguments to a Function
When a function requires input, its definition includes parameters, as you saw above.
When you make use of the function by calling/invoking it, you must provide the
required input. The data that you provide for each parameter is called an argument.
The increment function had one parameter value:
def increment(value):
increment(10, 5)
OUTPUT:
Old value = 10
New value = 15
As you can see above, the step_size parameter is used as the amount to increment
the value of value. Previously, it was incremented by 1; in this case, you can
specifically set the step size (2 is used in the example).
To illustrate an optional parameter, the step_size parameter is given a default value
using the assignment operator = and the default value. Below, the default value of
the step_size parameter is 1.
increment(10,5)
increment(10)
OUTPUT:
Old value = 10
New value = 15
Old value = 10
New value = 11
increment(10,5)
increment(10)
The first call to increment includes arguments for both parameters. The output, as
expected, increments the value by 10 to 15.
The second call does not include the argument for the second parameter. Thus, the
function uses the default values that was specified in the function's definition. The
output shows that the value of 10 was incremented by the default step size (1) to 11.
Keyword Arguments
Above, you saw that you must provide arguments to a function in the same
sequence as expressed in the function's definition. Each of these arguments is
referred to as a positional argument.
However, arguments can also be provided as a key-value pair, which means the
order is no longer relevant. To illustrate take a look at the change to the call to
the increment function below:
increment(value=2, step_size=2)
value=2 and step_size=2 are each a keyword argument; the key and value are both
provided.
If the sequence is changed, it will still work and produce the same output:
increment(step_size=3, value=3)
As you can see, when you use keyword arguments, the sequence of the function's
parameters is irrelevant.
new_value = increment(5, 3)
print("The new value is", new_value)
OUTPUT:
In the definition of the increment function, take a look at the one line of code (not the
docstring):
To return a value from a function, you use the return keyword followed by the value,
variable, or expression.
When increment is called, the value returned by the function is captured in
the new_value variable, which you can see as it's printed to the console.
Here's another example:
OUTPUT:
def get_settings():
"""This function returns two dictionaries as a tuple"""
dict1 = {'name': 'Bob', 'color': 'blue'}
dict2 = {'name': 'Sally', 'color': 'red'}
return (dict1, dict2)
tuple = get_settings()
print(tuple)
OUTPUT:
As you can see, you have a lot of flexibility when it comes to the types of data you
can return from your functions.
def greeting():
"""This function prints a greeting"""
print("Hello!")
print(greeting())
OUTPUT:
Hello!
None
As you can see in the output, when the "result" of the greeting() call is printed to the
console, it prints the value None. You can see this below the first line of the output,
where "Hello!" is printed.
Great! Now that you understand how to define a function with or without parameters,
invoke a function with or without parameters, and return data from a function, it's
time to discuss scope.
print(user)
What do you think will be printed when the print function is executed?
OUTPUT:
Andrew Jones
The user variable that was declared outside of the function is printed. Now, if you
want to print the user variable in the function you would need to invoke the function
like so:
print(my_function('John', 'Smith')
OUTPUT:
John Smith
Here you can see that the function was invoked and the user variable inside of the
function is used to store the new name.
In the following example, the global variable user will be used inside of the function.
def the_user():
"""Return the value of global variable user"""
# The global variable user is returned
return user
OUTPUT:
Andrew Jones
y = 25
def my_function():
global y
print('y is', y)
y=5
print('the new value of global y is', y)
my_function()
print('y is now', y)
y is 25
the new value of global y is 5
y is now 5
Setup
In VS Code, ensure your integrated terminal is open. If not, you can press control +
~ to open it.
In the integrated terminal, enter the following command and hit enter (if yapf is
already installed, it will simply inform you):
In the user settings, you will need to go to Extensions and then Python. Then scroll
down until you get to a section for Formatting: Yapf Path and add the word yapf to the
box below, as shown:
Once you have the settings configured, cmd + s or ctrl + s to save. You can close the
settings window once finished.
Lambda Functions
The lamda operator is used to create small, unnamed, anonymous functions.
These lambda function are considered throw-away functions, because they're only
used when they're defined. Most of the time, lambda functions are used in
combination with the built-in list functions filter() and map(). You'll learn about these
shortly.
When creating a lambda function, the following syntax is used:
Take a look at the example below which creates a lambda function and assigns it to
the variable my_lambda:
a = lambda x: x > 10
print(a(20))
True
This new lambda function a tests whether the input x is greater than 10,
returning Trueif so and False if not. After passing in the argument of 20, the function
executes 20 > 10 and then returns the value of True (because 20 is greater than 10).
OUTPUT:
The above code has numbered comments that are discussed below:
1. First, a list of integers is created and assigned to the numbers variable.
2. A lambda function for squaring a number is created and assigned to the
variable square.
3. The map function is called. As you can see, the map function takes two
parameters:
o The lambda function to be applied to every item in a collection is the
first parameter.
o The collection of items to which the lambda function will be applied is
the second parameter.
The lambda function that was created in step 2 is the first argument, while
the numbers list that was created in step 1 is the second argument. In the next
code example, you'll see a situation where there are more than two
parameters.
The results of the call to map is stored in the variable map_results.
4. The value returned from the call to map is map object. If it were printed to the
console, it would look like the following:
5. <map object at 0x1022a0320>
OUTPUT:
Above, the call to map includes the lambda function as the first argument, list_a as
the second argument, and list_b as the final argument. This is different from the
previous example, where map was only provided two arguments.
# 3. call `filter` using the `is_even` lambda function and the list `numbers`
filter_results = filter(is_even, numbers)
# 4. `filter` returns a special type of data like `map`, but it can be converted
# to a list using the `list` function
results = list(filter_results)
OUTPUT:
[2, 4]