Understanding Python Functions Basics
Understanding Python Functions Basics
In programming, as we start to write bigger and more complex programs, one thing
we will start to notice is we will often have to repeat the same set of steps in many
different places in our program.
Let’s imagine we were building an application to help people plan trips! When using
a trip planning application we can say a simple procedure could look like this:
Functions are a convenient way to group our code into reusable blocks. A function
contains a sequence of steps that can be performed repeatedly throughout a
program without having to repeat the process of writing the same code again.
In this lesson, we are going to explore the idea of a function by slowly building out a
Python program for our trip planning steps!
Instructions
Notice how the function navigation_steps() serves as a container for the three steps
in the procedure and can be reused across multiple users as they plan their trips to
different locations.
Click Next when you are ready to learn more about functions.
Why Functions?
Let’s come back to the trip planning application we just discussed in the previous
exercise. The steps we talked about for our program were:
print("Setting the Empire State Building as the starting point and Time Square as our
destination.")
If our program now had 100 new people trying to find the best directions between
the Empire State Building and Times Square, we would need to run each of our three
print statements 100 times!
Now, if you’re thinking about using a loop here, your intuition would be totally right!
Unfortunately, we won’t be always traveling between the same two locations which
means a loop won’t be as effective when we want to customize a trip. We will
address this in the upcoming sections!
Instructions
1.
Run the pre-written print() statements to see what they output.
2.
Write the same set of print statements three more times. Run the code again
and see the output.
Hint
Make sure that the three print statements are all duplicated three more times.
3.
Hopefully now you have some perspective about your life without functions!
In the next section, we will learn how we can refactor our code to utilize
functions to reuse code.
Click Run your code again and then click Next to continue.
Giải:
# First user wants to travel between these two points!
print("Setting the Empire State Building as the starting point and Time Square as our
destination.")
print("Calculating the total distance between our points.")
print("The best route is by train and will take approximately 10 minutes.")
Chạy ra:
Calculating the total distance between our points.
The best route is by train and will take approximately 10 minutes.
Setting the Empire State Building as the starting point and Time Square as our
destination.
Calculating the total distance between our points.
The best route is by train and will take approximately 10 minutes.
Setting the Empire State Building as the starting point and Time Square as our
destination.
Calculating the total distance between our points.
The best route is by train and will take approximately 10 minutes.
Defining a Function
A function consists of many parts, so let’s first get familiar with its core - a function
definition.
def function_name():
# functions tasks go here
There are some key components we want to note here:
Following the function name is a pair of parenthesis ( ) that can hold input
values known as parameters (more on parameters later in the lesson!). In this
example function, we have no parameters.
Lastly, we have one or more valid python statements that make up the
function body (where we have our python comment).
Notice we’ve indented our # function tasks go here comment. Like loops and
conditionals, code inside a function must be indented to show that they are part of
the function.
Here is an example of a function that greets a user for our trip planning application:
def trip_welcome():
print("Welcome to Tripcademy!")
print("Let's get you to your destination.")
Note: Pasting this code into the editor and clicking Run will result in an empty output
terminal. The print() statements within the function will not execute since our
function hasn’t been used. We will explore this further in the next exercise; for now,
let’s practice defining a function.
Instructions
1.
Two of the most common NYC attractions include the Empire State Building
and Times Square.
In [Link], we’ll write a function that prints the directions via subway from
the Empire State Building to Times Square.
Note: When we run the code, we will see an error: “IndentationError: expected
an indented block”. This will occur when we don’t populate a function with any
statements. We will populate it with code in the next step.
Hint
Remember the core of a function - a definition. Check to make sure you have all the
components for a function definition.
def my_function_name():
2.
Within the body of the function, use three print() statements to output the
following directions:
If you are interested in seeing the output, call your function like this:
directions_to_timesSq()
Giải:
print ("Walk 4 mins to 34th St Herald Square train station")
print ("Take the Northbound N, Q, R, or W train 1 stop")
print ("Get off the Times Square 42nd Street stop")
Calling a Function
Now that we’ve practiced defining a function, let’s learn about calling a function to
execute the code within its body.
The process of executing the code inside the body of a function is known as calling it
(This is also known as “executing a function”). To call a function in Python, type out
its name followed by parentheses ( ).
def directions_to_timesSq():
print("Walk 4 mins to 34th St Herald Square train station.")
print("Take the Northbound N, Q, R, or W train 1 stop.")
print("Get off the Times Square 42nd Street stop.")
To call our function, we must type out the function’s name followed by a pair of
parentheses and no indentation:
directions_to_timesSq()
Calling the function will execute the print statements within the body (from the top
statement to the bottom statement) and result in the following output:
Instructions
1.
Call the directions_to_timesSq() function.
Run your code again and see how your output changes.
Hint
Remember to add the print statement inside of the function definition
for directions_to_timesSq(). It should be indented and contain the text "Take lots of
pictures!". Make sure to place it after the other print statements in the function.
Giải:
def directions_to_timesSq():
print("Walk 4 mins to 34th St Herald Square train station.")
print("Take the Northbound N, Q, R, or W train 1 stop.")
print("Get off the Times Square 42nd Street stop.")
print ("Take lots of pictures!")
directions_to_timesSq()
Chạy ra:
Walk 4 mins to 34th St Herald Square train station.
Take the Northbound N, Q, R, or W train 1 stop.
Get off the Times Square 42nd Street stop.
Take lots of pictures!
Whitespace & Execution Flow
Consider our welcome function for our trip planning application:
def trip_welcome():
print("Welcome to Tripcademy!")
print("Let's get you to your destination.")
The print statements all run together when trip_welcome() is called. This is because
they have the same base level of indentation (2 spaces).
In Python, the amount of whitespace tells the computer what is part of a function
and what is not part of that function.
def trip_welcome():
# Indented code is part of the function body
print("Welcome to Tripcademy!")
print("Let's get you to your destination.")
trip_welcome()
Our trip_welcome() function steps will not print Woah, look at the weather outside!
Don't walk, take the train! on our function call. The print() statement was
unindented to show it was not a part of the function body but rather a separate
statement.
Woah, look at the weather outside! Don't walk, take the train!
Welcome to Tripcademy!
Let's get you to your destination.
Lastly, note that the execution of a program always begins on the first line. The code
is then executed one line at a time from top to bottom. This is known as execution
flow and is the order a program in python executes code.
Woah, look at the weather outside! Don't walk, take the train! was printed before
the print() statements from the function trip_welcome().
Even though our function was defined before our lone print() statement, we didn’t
call our function until after.
Instructions
1.
We are going to help our trip planner users figure out if they should travel
today based on the weather. Let’s let our users know we can check the
weather for them.
Write a print() statement that will output Checking the weather for you!.
Checkpoint 2 Passed
Stuck? Get a hint
2.
We took a look outside and see a bright sunny day. Write a function
called weather_check() that will print a message to our users that it’s a great
day to travel! The function should output:
What is different?
Giải:
def trip_welcome():
print("Welcome to Tripcademy!")
print("Let's get you to your destination.")
print("Checking the weather for you!")
trip_welcome()
def weather_check():
print("Looks great outside! Enjoy your trip.")
print("False Alarm, the weather changed! There is a thunderstorm approaching. Canc
el your plans and stay inside.")
weather_check()
Chạy ra:
Welcome to Tripcademy!
Let's get you to your destination.
Checking the weather for you!
False Alarm, the weather changed! There is a thunderstorm approaching. Cancel
your plans and stay inside.
Looks great outside! Enjoy your trip.
Parameters & Arguments
Let’s return to our trip_welcome() function one more time! Let’s modify our function
to give a welcome that is a bit more detailed.
def trip_welcome():
print("Welcome to Tripcademy!")
print("Looks like you're going to Times Square today.")
trip_welcome()
This will output:
Welcome to Tripcademy!
Looks like you're going to Times Square today.
Our function does a really good job of welcoming anyone who is traveling to Times
Square but a really poor job if they are going anywhere else. In order for us to make
our function a bit more dynamic, we are going to use the concept of
function parameters.
Function parameters allow our function to accept data as an input value. We list the
parameters a function takes as input between the parentheses of a function ( ).
def my_function(single_parameter)
# some code
In the context of our trip_welcome() function, it would like this:
def trip_welcome(destination):
print("Welcome to Tripcademy!")
print("Looks like you're going to " + destination + " today.")
In the above example, we define a single parameter called destination and apply it in
our function body in the second print statement. We are telling our function it
should expect some data passed in for destination that it can apply to any
statements in the function body.
But how do we actually use this parameter? Our parameter of destination is used by
passing in an argument to the function when we call it.
trip_welcome("Times Square")
This would output:
Welcome to Tripcademy!
Looks like you're going to Times Square today.
To summarize, here is a quick breakdown of the distinction between a parameter
and an argument:
The parameter is the name defined in the parenthesis of the function and can
be used in the function body.
The argument is the data that is passed in when we call the function and
assigned to the parameter name.
Let’s write a function with parameters and call the function with an argument to see
it all in action!
Instructions
1.
We want to create a program that allows our users to generate the directions
for their upcoming trip!
Note: Since we did not define any code in our function yet, we will receive an
error in our output terminal. Don’t worry, we will be filling in the code in the
next step.
Hint
Function parameters must be defined in the parenthesis of our function definition:
def some_function(single_parameter):
#some code
2.
generate_trip_instructions() should print out the following:
Run:
Looks like you are planning a trip to visit Central Park
You can use the public subway system to get to Central Park
Looks like you are planning a trip to visit Grand Central Station
You can use the public subway system to get to Grand Central Station
Multiple Parameters
Using a single parameter is useful but functions let us use as many parameters as we
want! That way, we can pass in more than one input to our functions.
We can write a function that takes in more than one parameter by using commas:
# Calling my_function
my_function(argument1, argument2)
For example take our trip applications trip_welcome() function that has two
parameters:
The ordering of your parameters is important as their position will map to the
position of the arguments and will determine their assigned value in the function
body (more on this in the next exercise!).
Welcome to Tripcademy
Looks like you are traveling from Prospect Park
And you are heading to Atlantic Terminal
Let’s practice writing and calling a multiple parameter function!
Instructions
1.
Our travel application users want to calculate the total expenses they may have
to incur on a trip.
Write a function called calculate_expenses that will have four parameters (in
exact order):
. plane_ticket_price
. car_rental_rate
. hotel_rate
. trip_time
Each of these parameters will account for a different expense that our users
will incur.
Note: Like before, if we run this function now, we will get an error since there
are no statements in the body.
Hint
Remember that the parameters go between the parentheses in the function
definition and that they are separated by commas. The order of the parameters is
also important!
2.
Within the body of the function, let’s start to make some calculations for our
expenses. First, let’s calculate the total price for a car rental.
We also have a coupon to give our users some cashback for their hotel visit so
subtract 10 from that total in the same statement. Woohoo, coupons!
Hint
Use * to perform multiplication between the two variables. Don’t forget to
subtract 10 after!
4.
Lastly, let’s print a nice message for our users to see the total. Use print to
output the sum of car_rental_total, hotel_total and plane_ticket_price.
Hint
Use + to perform the addition operation on the three variables.
5.
Call your function with the following argument values for the parameters
listed:
plane_ticket_price : 200
car_rental_rate : 100
hotel_rate : 100
trip_time: 5
Hint
Your output should be:
1190
Giải:
# Write your code below:
def calculate_expenses (plane_ticket_price, car_rental_rate, hotel_rate, trip_time):
car_rental_total = car_rental_rate * trip_time
hotel_total = hotel_rate * trip_time - 10
print (car_rental_total + hotel_total + plane_ticket_price)
calculate_expenses(200,100,100,5)
Run:
1190
Types of Arguments
In Python, there are 3 different types of arguments we can give a function.
Positional Arguments are arguments we have already been using! Their assignments
depend on their positions in the function call. Let’s look at a function
called calculate_taxi_price() that allows our users to see how much a taxi would cost
to their destination
# 100 is miles_to_travel
# 10 is rate
# 5 is discount
calculate_taxi_price(100, 10, 5)
Alternatively, we can use Keyword Arguments where we explicitly refer to what each
argument is assigned to in the function call. Notice in the code example below that
the arguments do not follow the same order as defined in the function declaration.
Instructions
1.
Tripcademy (our trusty travel app) needs to allow passengers to plan a trip
(duh).
Note: Since we did not define any code in our function yet, we will receive an
error in our output terminal. Don’t worry, we will be filling in the code in the
next step.
Hint
Remember the structure of a multi-parameter function:
print(learning + py_funcs)
Would output:
I am learning Functions
Note:We can add an extra space at the end of learning to make sure the string is
properly formated when it is combined.
4.
Call the function trip_planner() with the following values for the parameters:
first_destination: "France"
second_destination: "Germany"
final_destination: "Denmark"
Hint
Your output should be:
first_destination: "Denmark"
second_destination: "France"
final_destination: "Germany"
first_destination: "Iceland"
.
.
final_destination: "Germany"
.
.
second_destination: "India"
Hint
Your output should be:
first_destination: "Brooklyn"
.
.
second_destination: "Queens"
Hint
Your output should be:
Giải:
def trip_planner(first_destination, second_destination, final_destination= "Codecade
my HQ"):
print ("Here is what your trip will look like!")
print("First, we will stop in " + first_destination + ", then " + second_destination + ",
and lastly " + final_destination)
trip_planner("France", "Germany", "Denmark")
trip_planner("Denmark","France", "Germany" )
trip_planner(first_destination= "Iceland",final_destination = "Germany",
second_destination ="India")
trip_planner ("Brooklyn","Queens")
Run:
Here is what your trip will look like!
First, we will stop in France, then Germany, and lastly Denmark
Here is what your trip will look like!
First, we will stop in Denmark, then France, and lastly Germany
Here is what your trip will look like!
First, we will stop in Iceland, then India, and lastly Germany
Here is what your trip will look like!
First, we will stop in Brooklyn, then Queens, and lastly Codecademy HQ
Built-in Functions vs User Defined Functions
There are two distinct categories for functions in the world of Python. What we have
been writing so far in our exercises are called User Defined Functions - functions that
are written by users (like us!).
There is another category called Built-in functions - functions that come built into
Python for us to use. Remember when we were using print or str? Both of these
functions are built into the language for us, which means we have been using built-in
functions all along!
There are lots of different built-in functions that we can use in our programs. Take a
look at this example of using len() to get the length of a string:
destination_name = "Venkatanarasimharajuvaripeta"
28
Here we are using a total of two built-in functions in our example: print(), and len().
There are even more obscure ones like help() where Python will print a link to
documentation for us and provide some details:
help("string")
Would output (shortened for readability):
NAME
string - A collection of string constants.
MODULE REFERENCE
[Link]
Instructions
1.
We were provided a list of prices for some gift shop items:
T-shirt: 9.75
Shorts: 15.50
Mug: 5.99
Poster: 2.00
Create a variable called max_price and call the built-in function max() with the
variables of prices to get the maximum price.
Print max_price.
Hint
The max() built-in function takes in a series of consecutive arguments and returns
the max value. Here is an example:
max_value = max(1, 4, 5, 9, 6)
print(max_value)
Would output:
9
For our example, pass the variable names for our prices in as the arguments to get
the max value.
2.
Using the same set of prices, create a new variable called min_price and use
the built-in function min() with the variables of prices to get the minimum
price.
Print min_price.
Hint
__The min() built-in function takes in a series of consecutive arguments and returns
the min value. Here is an example:
min_price = min(4, 1, 5, 9, 6)
print(min_price)
Would output:
1
For our example, pass the variable names for our prices in as the arguments to get
the min value.
3.
Use the built-in function round() to round the price of the
variable tshirt_price by one decimal place.
Save the result to a variable called rounded_price and print it.
Hint
The round() built-in function takes in two arguments. The first argument is the
number we want to round, followed by an argument on how many decimal places
we want to round it.
Here is an example:
rounded_zero = round(10.54, 0)
rounded_one = round(10.54, 1)
print(rounded_zero)
print(rounded_one)
Would output:
11.00
10.5
Giải:
tshirt_price = 9.75
shorts_price = 15.50
mug_price = 5.99
poster_price = 2.00
print (rounded_price)
Run: 15.5
2.0
9.8
Variable Access
As we expand our programs with more functions, we might start to ponder, where
exactly do we have access to our variables? To examine this, let’s revisit a modified
version of the first function we built out together:
def trip_welcome(destination):
print(" Looks like you're going to the " + destination + " today. ")
What if we wanted to access the variable destination outside of the function? Could
we use it? Take a second to think about what the following program will output,
then check the result below!
def trip_welcome(destination):
print(" Looks like you're going to the " + destination + " today. ")
print(destination)
Output Results
We call the part of a program where destination can be accessed its scope.
The scope of destination is only inside the trip_welcome().
budget = 1000
print(budget)
trip_welcome()
Our output would be:
1000
Looks like you're going to California
Your budget for this trip is 1000
Here we are able to access the budget both inside the trip_welcome function as well
as our print() statement. If a variable lives outside of any function it can be accessed
anywhere in the file.
We will be exploring the concept of scope more after this entire lesson but for now,
let’s play around!
Note: Working with multiple functions can be a bit overwhelming at first. Don’t
hesitate to use hints or even look at the solution code if you get stuck.
Instructions
1.
Our users want to be able to save a list of their favorite places in our travel
application.
We have received a rough draft for this implementation from another coder,
but there are some problems with variable scope which prevent it from
working properly.
Take a second to understand what the program is doing and then hit Run the
code to see the error.
Hint
The error is a bit scary. Don’t worry we will fix it, just take a second to think about
what might be wrong.
Aha! It must be a scope issue. Fix the scope of favorite_locations so that both
our functions can access it.
Giải:
favorite_locations = "Paris, Norway, Iceland"
# This function will print a hardcoded count of how many locations we have.
def print_count_locations():
print_count_locations()
show_favorite_locations()
Here’s an example of a program that will return a converted currency for a given
location a user may want to visit in our trip planner application.
100 dollars in US currency would give you 140 New Zealand dollars
Saving our values returned from a function like we did
with new_zealand_exchange allows us to reuse the value (in the form of a variable)
throughout the rest of the program.
Note: Working with multiple functions can be a bit overwhelming at first. Don’t
hesitate to use hints or even look at the solution code if you get stuck.
Instructions
1.
Our travel application is getting really popular. Some of our users have posted
on social media that it would be useful if our application could help them track
their budget during trips. We want to help them track their starting budget and
let them know how much they have left after an expense.
The first parameter will be budget and the second parameter will be expense.
Our function will be taking in a budget value as well as the expense we want to
subtract.
We will want our function to return the budget minus the expense our
travelers are incurring.
Hint
Remember to use the keyword return followed by the subtraction
of expense from budget.
3.
Looks like the most common expense our travelers are incurring is a t-shirt
purchase.
Let’s create a variable called shirt_expense and for now, we will give it a set
value of 9 (We are not accounting for currency changes at the moment). Make
sure this is defined outside of the functions in your script.
Hint
Define shirt_expense outside of all of the functions in your script and set it equal
to 9.95.
4.
Now that we have an expense to subtract, create a new variable
called new_budget_after_shirt and set it to be the function call
of deduct_expense().
my_function(argument1, argument2)
5.
Lastly, we want our users to see the remaining budget.
def print_remaining_budget(budget):
print("Your remaining budget is: $" + str(budget))
print_remaining_budget(current_budget)
print_remaining_budget(new_budget_after_shirt)
Run:
Your remaining budget is: $3500.75
Your remaining budget is: $3491.75
Multiple Returns
Sometimes we may want to return more than one value from a function. We can
return several values by separating them with a comma. Take a look at this example
of a function that allows users in our travel application to check the upcoming
week’s weather (starting on Monday):
def threeday_weather_report(weather):
first_day = " Tomorrow the weather will be " + weather[0]
second_day = " The following day it will be " + weather[1]
third_day = " Two days from now it will be " + weather[2]
return first_day, second_day, third_day
This function takes in a set of data in the form of a list for the upcoming week’s
weather. We can get our returned function values by assigning them to variables
when we call the function:
print(monday)
print(tuesday)
print(wednesday)
This will print:
Instructions
1.
Our users liked the previous functionality that we added to our travel
application, but recently we have had an influx of users planning trips in Italy.
We want to create a small function to output the top places to visit in Italy.
Another member of our team already started on the implementation of this
feature but it is still missing a few key details.
Take a second to review the code and click Run when you are ready to move
on. For now, there will be no output.
2.
We want to be able to return the three most popular destinations from our
function top_tourist_locations_italy().
my_function():
a=1
b=2
c=3
return a, b, c
3.
In order to use our three returned values from top_tourist_locations_italy() we
need to assign them to new variables names after we call our function.
Rome
Venice
Florence
Giải:
top_tourist_location_italy = ['first', 'second', 'third']
def top_tourist_locations_italy():
first = "Rome"
second = "Venice"
third = "Florence"
Instructions
1.
Alright, this is it. We are going to use all of our knowledge of functions to build
out TripPlanner V1.0.
First, like in our previous exercises, we want to make sure to welcome our
users to the application.
def function_name(single_parameter):
# Some Code
2.
Next, we are going to generate messages for a user’s planned trip.
. origin
. destination
. estimated_time
. mode_of_transport
Give the parameter mode_of_transport a default value of "Car". The program
will error out if we run it since we have not defined a function body yet. Don’t
worry we will do that in the next step.
Hint
Here is an example of a four-parameter function definition with a default value for
the last parameter:
Note: The estimated_time parameter will come in the form of a decimal. Make
sure to use str() to convert the parameter in your print statement.
Hint
Use + to concatenate a string variable with another string. For example:
world = "World"
Hello World
Since we know estimated_time will be a number. We will need to use
the str() function to convert it to a string. Here is an example:
number = 101
print("You are taking a " + str(101) + " course"
Would output:
estimated_time_rounded(2.43)
Where 2 represents 2 hours and .43 represents 43 minutes.
Hint
Here is how you would use the round() function and return it from a user-defined
function:
def return_round():
rounded_value = round(5.53)
return rounded_value
5.
Great job!
We have successfully finished our first version of the trip builder application.
Go ahead and uncomment the provided function calls and fill in the values with
whatever you like.
Once have filled in the arguments, run the program to see it all in action.
Hint
Your output should look something like this: