0% found this document useful (0 votes)
699 views

Khóa Học Python

This document provides an overview of a Python programming course that includes the following topics: 1. The course covers theory and exercises, including introductions to printing text, comments, variables, and common errors. 2. Each topic is broken down into multiple parts that provide examples and instructions for writing small programs to demonstrate concepts like printing names, updating variables, and fixing syntax and naming errors. 3. Community forums are available for asking questions about topics like when to use single vs. double quotes and how to handle errors.

Uploaded by

Thùy Chang
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
699 views

Khóa Học Python

This document provides an overview of a Python programming course that includes the following topics: 1. The course covers theory and exercises, including introductions to printing text, comments, variables, and common errors. 2. Each topic is broken down into multiple parts that provide examples and instructions for writing small programs to demonstrate concepts like printing names, updating variables, and fixing syntax and naming errors. 3. Community forums are available for asking questions about topics like when to use single vs. double quotes and how to handle errors.

Uploaded by

Thùy Chang
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 391

Khóa học python

A, Lí thuyết + bài tập


I. Chương 1: Hello world
a. Part 1
HELLO WORLD
Welcome
Python is a programming language. Like other languages, it gives us a way to communicate
ideas. In the case of a programming language, these ideas are “commands” that people use to
communicate with a computer!

We convey our commands to the computer by writing them in a text file using a programming
language. These files are called programs. Running a program means telling a computer to read
the text file, translate it to the set of operations that it understands, and perform those actions.

Instructions

Change Codecademy to your name in the script to the right. Run the code to see what it does!

As soon as you’re ready, move on to the next exercise to begin learning to write your own
Python programs!

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a look at this
material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this exercise:

1.

Why do I need to enter my name on a different line?

2.

How can I use an integer in a print function?


Still have questions? View this exercise's thread in the Codecademy Forums.
script.py

b. Part 2
HELLO WORLD
Comments
Ironically, the first thing we’re going to do is show how to tell a computer to
ignore a part of a program. Text written in a program but not run by the
computer is called a comment. Python interprets anything after a # as a
comment.

Comments can:

 Provide context for why something is written the way it is:

# This variable will be used to count the number of times


anyone tweets the word persnickety
persnickety_count = 0
 Help other people reading the code understand it faster:

# This code will calculate the likelihood that it will


rain tomorrow
complicated_rain_calculation_for_tomorrow()
 Ignore a line of code and see how a program will run without it:

# useful_value = old_sloppy_code()
useful_value = new_clean_code()

Instructions

1.
Documentation is an important step in programming. Write a comment
describing the first program you want to write!
Checkpoint 2 Passed

Stuck? Get a hint

Concept Review
Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

In the context of this exercise that introduces comments, where should


comments be added to the code? Can I just add comments to every line
of code to be safe?

2.

Why is there no output in the terminal?

3.

How to make multiline comments, and autocompletion of quotes

Still have questions? View this exercise's thread in the Codecademy Forums.

c. Part 3
HELLO WORLD
Print
Now what we’re going to do is teach our computer to communicate. The gift
of speech is valuable: a computer can answer many questions we have about
“how” or “why” or “what” it is doing. In Python, the print() function is used to
tell a computer to talk. The message to be printed should be surrounded by
quotes:

# from Mary Shelley's Frankenstein


print("There is something at work in my soul, which I do not
understand.")
In the above example, we direct our program to print() an excerpt from a
notable book. The printed words that appear as a result of the print() function
are referred to as output. The output of this example program would be:

There is something at work in my soul, which I do not


understand.

Instructions

1.
Print the distinguished greeting “Hello world!”
Checkpoint 2 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

Are quotes always necessary inside of a print() ?

2.
How can I use quotes inside of a string?

3.

How can I skip or jump to a new line while printing?

Still have questions? View this exercise's thread in the Codecademy Forums.

d. Part 4
HELLO WORLD
Strings
Computer programmers refer to blocks of text as strings. In our last exercise,
we created the string “Hello world!”. In Python a string is either surrounded by
double quotes ("Hello world") or single quotes ('Hello world'). It doesn’t
matter which kind you use, just be consistent.

Instructions

1.
Print your name using the print() command.
Checkpoint 2 Passed

Stuck? Get a hint


2.
If your print statement uses double-quotes ", change them to single-quotes '.
If it uses single-quotes ', change them to double-quotes ".

Try running your code again after switching the type of quote-marks. Is
anything different about the output?
Checkpoint 3 Passed

Stuck? Get a hint

Concept Review
Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

When should single or double quotes be used for a string?

Still have questions? View this exercise's thread in the Codecademy Forums.

e. Part 5
HELLO WORLD
Variables
Programming languages offer a method of storing data for reuse. If there is a
greeting we want to present, a date we need to reuse, or a user ID we need to
remember we can create a variable which can store a value. In Python,
we assign variables by using the equals sign (=).

message_string = "Hello there"


# Prints "Hello there"
print(message_string)
In the above example, we store the message “Hello there” in a variable
called message_string. Variables can’t have spaces or symbols in their names
other than an underscore (_). They can’t begin with numbers but they can have
numbers after the first letter (e.g., cool_variable_5 is OK).

It’s no coincidence we call these creatures “variables”. If the context of a


program changes, we can update a variable but perform the same logical
process on it.

# Greeting
message_string = "Hello there"
print(message_string)

# Farewell
message_string = "Hasta la vista"
print(message_string)
Above, we create the variable message_string, assign a welcome message, and
print the greeting. After we greet the user, we want to wish them goodbye.
We then update message_string to a departure message and print that out.

Instructions

1.
Update the variable meal to reflect each meal of the day before we print it.
Checkpoint 2 Passed

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

After a variable is assigned to an initial value, can the variable later be


reassigned to another value that is of a different data type than its initial
value?

2.

Can print be used on more than just strings?


3.

Why change a variable rather than just create a new one?

Still have questions? View this exercise's thread in the Codecademy Forums.

f. Part 6
HELLO WORLD
Errors
Humans are prone to making mistakes. Humans are also typically in charge of
creating computer programs. To compensate, programming languages
attempt to understand and explain mistakes made in their programs.

Python refers to these mistakes as errors and will point to the location where
an error occurred with a ^ character. When programs throw errors that we
didn’t expect to encounter we call those errors bugs. Programmers call the
process of updating the program so that it no longer produces unexpected
errors debugging.

Two common errors that we encounter while writing Python


are SyntaxError and NameError.

 SyntaxError means there is something wrong with the way your program


is written — punctuation that does not belong, a command where it is
not expected, or a missing parenthesis can all trigger a SyntaxError.
 A NameError occurs when the Python interpreter sees a word it does not
recognize. Code that contains something that looks like a variable but
was never defined will throw a NameError.

Instructions

1.
You might encounter a SyntaxError if you open a string with a single quote
and end it with double quotes. Update the string so that it starts and ends
with the same punctuation.

You might encounter a NameError if you try to print a single word string but fail
to put any quotes around it. Python expects the word of your string to be
defined elsewhere but can’t find where it’s defined. Add quotes to either side
of the string to squash this bug.

Update the malformed strings in the workspace to all be strings.


Checkpoint 2 Passed

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

I spelled everything correctly, but still receive a NameError. Why?

2.

Why does an error in python shut down the whole program?

Still have questions? View this exercise's thread in the Codecademy Forums.

g. Part 7
HELLO WORLD
Numbers
Computers can understand much more than just strings of text. Python has a
few numeric data types. It has multiple ways of storing numbers. Which one
you use depends on your intended purpose for the number you are saving.

An integer, or int, is a whole number. It has no decimal point and contains all
counting numbers (1, 2, 3, …) as well as their negative counterparts and the
number 0. If you were counting the number of people in a room, the number
of jellybeans in a jar, or the number of keys on a keyboard you would likely
use an integer.

A floating-point number, or a float, is a decimal number. It can be used to


represent fractional quantities as well as precise measurements. If you were
measuring the length of your bedroom wall, calculating the average test score
of a seventh-grade class, or storing a baseball player’s batting average for the
1998 season you would likely use a float.

Numbers can be assigned to variables or used literally in a program:

an_int = 2
a_float = 2.1

print(an_int + 3)
# Output: 5
Above we defined an integer and a float as the variables an_int and a_float.
We printed out the sum of the variable an_int with the number 3. We call the
number 3 here a literal, meaning it’s actually the number 3 and not a variable
with the number 3 assigned to it.

Floating-point numbers can behave in some unexpected ways due to how


computers store them. For more information on floating-point numbers and
Python, review Python’s documentation on floating-point limitations.

Instructions

1.
A recent movie-going experience has you excited to publish a review. You
rush out of the cinema and hastily begin programming to create your movie-
review website: The Big Screen’s Greatest Scenes Decided By A Machine.

Create the following variables and assign integer numbers to


them: release_year and runtime.
Checkpoint 2 Passed

Stuck? Get a hint


2.
Now, create the variable rating_out_of_10 and assign it a float number
between one and ten.
Checkpoint 3 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

Why would I ever use integers given that floats cover more values and
are more flexible?

2.

Why don’t I need to define my variable as a float or integer?

Still have questions? View this exercise's thread in the Codecademy Forums.


h. Part 8
HELLO WORLD
Calculations
Computers absolutely excel at performing calculations. The “compute” in their
name comes from their historical association with providing answers to
mathematical questions. Python performs the arithmetic operations of
addition, subtraction, multiplication, and division with +, -, *, and /.

# Prints "500"
print(573 - 74 + 1)

# Prints "50"
print(25 * 2)

# Prints "2.0"
print(10 / 5)
Notice that when we perform division, the result has a decimal place. This is
because Python converts all ints to floats before performing division. In older
versions of Python (2.7 and earlier) this conversion did not happen, and
integer division would always round down to the nearest integer.

Division can throw its own special error: ZeroDivisionError. Python will raise
this error when attempting to divide by 0.

Mathematical operations in Python follow the standard mathematical order of


operations.

Instructions

1.
Print out the result of this equation: 25 * 68 + 13 / 28
Checkpoint 2 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!
Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

In this exercise, we placed expressions and mathematical operations


inside of the print() function. Is the input always evaluated first before
anything is printed?

Still have questions? View this exercise's thread in the Codecademy Forums.

i. Part 9
HELLO WORLD
Changing Numbers
Variables that are assigned numeric values can be treated the same as the
numbers themselves. Two variables can be added together, divided by 2, and
multiplied by a third variable without Python distinguishing between the
variables and literals (like the number 2 in this example). Performing arithmetic
on variables does not change the variable — you can only update a variable
using the = sign.

coffee_price = 1.50
number_of_coffees = 4

# Prints "6.0"
print(coffee_price * number_of_coffees)
# Prints "1.5"
print(coffee_price)
# Prints "4"
print(number_of_coffees)

# Updating the price


coffee_price = 2.00
# Prints "8.0"
print(coffee_price * number_of_coffees)
# Prints "2.0"
print(coffee_price)
# Prints "4"
print(number_of_coffees)
We create two variables and assign numeric values to them. Then we perform
a calculation on them. This doesn’t update the variables! When we update
the coffee_price variable and perform the calculations again, they use the
updated values for the variable!

Instructions

1.
You’ve decided to get into quilting! To calculate the number of squares you’ll
need for your first quilt let’s create two variables: quilt_width and quilt_length.
Let’s make this first quilt 8 squares wide and 12 squares long.
Checkpoint 2 Passed

2.
Print out the number of squares you’ll need to create the quilt!
Checkpoint 3 Passed

3.
It turns out that quilt required a little more material than you have on hand!
Let’s only make the quilt 8 squares long. How many squares will you need for
this quilt instead?
Checkpoint 4 Passed

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

What actually happens when you change a variable to some other value
in Python?
2.

How can I print a sentence with the calculation?

Still have questions? View this exercise's thread in the Codecademy Forums.

j. Part 10
HELLO WORLD
Exponents
Python can also perform exponentiation. In written math, you might see
an exponent as a superscript number, but typing superscript numbers isn’t
always easy on modern keyboards. Since this operation is so related to
multiplication, we use the notation **.

# 2 to the 10th power, or 1024


print(2 ** 10)

# 8 squared, or 64
print(8 ** 2)

# 9 * 9 * 9, 9 cubed, or 729


print(9 ** 3)

# We can even perform fractional exponents


# 4 to the half power, or 2
print(4 ** 0.5)
Here, we compute some simple exponents. We calculate 2 to the 10th power,
8 to the 2nd power, 9 to the 3rd power, and 4 to the 0.5th power.

Instructions

1.
You really like how the square quilts from last exercise came out, and decide
that all quilts that you make will be square from now on.

Using the exponent operator, print out how many squares you’ll need for a
6x6 quilt, a 7x7 quilt, and an 8x8 quilt.
Checkpoint 2 Passed

2.
Your 6x6 quilts have taken off so well, 6 people have each requested 6 quilts.
Print out how many tiles you would need to make 6 quilts apiece for 6 people.
Checkpoint 3 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

How many squares for 6 people who want 6 quilts of 6x6 squares?

2.

Do spaces in python expressions do anything?

3.
In this exercise, the exponent operator is used for positive exponents.
Does exponentiation work with negative exponents as well?

Still have questions? View this exercise's thread in the Codecademy Forums.

k. Part 11
HELLO WORLD
Modulo
Python offers a companion to the division operator called the modulo
operator. The modulo operator is indicated by % and gives the remainder of a
division calculation. If the number is divisible, then the result of the modulo
operator will be 0.

# Prints 4 because 29 / 5 is 5 with a remainder of 4


print(29 % 5)

# Prints 2 because 32 / 3 is 10 with a remainder of 2


print(32 % 3)

# Modulo by 2 returns 0 for even numbers and 1 for odd numbers


# Prints 0
print(44 % 2)
Here, we use the modulo operator to find the remainder of division
operations. We see that 29 % 5 equals 4, 32 % 3 equals 2, and 44 % 2 equals 0.

The modulo operator is useful in programming when we want to perform an


action every nth-time the code is run. Can the result of a modulo operation be
larger than the divisor? Why or why not?

Instructions

1.
You’re trying to divide a group into four teams. All of you count off, and you
get number 27.
Find out your team by computing 27 modulo 4. Save the value to my_team.
Checkpoint 2 Passed

2.
Print out my_team. What number team are you on?
Checkpoint 3 Passed

3.
Food for thought: what number team are the two people next to you (26 and
28) on? What are the numbers for all 4 teams? (Optional Challenge Question)
Checkpoint 4 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

How is modulo used and how does it determine which team?

2.

In the context of this exercise, can the result of a modulo operation be


larger than the divisor?

3.

How can I determine the numbers for all 4 teams?


Still have questions? View this exercise's thread in the Codecademy Forums.

l. Part 12
HELLO WORLD
Concatenation
The + operator doesn’t just add two numbers, it can also “add” two strings!
The process of combining two strings is called string concatenation.
Performing string concatenation creates a brand new string comprised of the
first string’s contents followed by the second string’s contents (without any
added space in-between).

greeting_text = "Hey there!"


question_text = "How are you doing?"
full_text = greeting_text + question_text

# Prints "Hey there!How are you doing?"


print(full_text)
In this sample of code, we create two variables that hold strings and then
concatenate them. But we notice that the result was missing a space between
the two, let’s add the space in-between using the same concatenation
operator!

full_text = greeting_text + " " + question_text

# Prints "Hey there! How are you doing?"


print(full_text)
Now the code prints the message we expected.

If you want to concatenate a string with a number you will need to make the
number a string first, using the str() function. If you’re trying to print() a
numeric variable you can use commas to pass it as a different argument rather
than converting it to a string.

birthday_string = "I am "


age = 10
birthday_string_2 = " years old today!"
# Concatenating an integer with strings is possible if we turn
the integer into a string first
full_birthday_string = birthday_string + str(age)
+ birthday_string_2

# Prints "I am 10 years old today!"


print(full_birthday_string)

# If we just want to print an integer


# we can pass a variable as an argument to
# print() regardless of whether
# it is a string.

# This also prints "I am 10 years old today!"


print(birthday_string, age, birthday_string_2)
Using str() we can convert variables that are not strings to strings and then
concatenate them. But we don’t need to convert a number to a string for it to
be an argument to a print statement.

Instructions

1.
Concatenate the strings and save the message they form in the
variable message.

Now uncomment the print statement and run your code to see the result in
the terminal!
Checkpoint 2 Passed

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.
How does string concatenation work?

2.

What is an argument in python?

3.

Why should we use concatenation instead of just the print() function?

Still have questions? View this exercise's thread in the Codecademy Forums.

m. Part 13
HELLO WORLD
Plus Equals
Python offers a shorthand for updating variables. When you have a number
saved in a variable and want to add to the current value of the variable, you
can use the += (plus-equals) operator.

# First we have a variable with a number saved


number_of_miles_hiked = 12

# Then we need to update that variable


# Let's say we hike another two miles today
number_of_miles_hiked += 2

# The new value is the old value


# Plus the number after the plus-equals
print(number_of_miles_hiked)
# Prints 14
Above, we keep a running count of the number of miles a person has gone
hiking over time. Instead of recalculating from the start, we keep a grand total
and update it when we’ve gone hiking further.

The plus-equals operator also can be used for string concatenation, like so:

hike_caption = "What an amazing time to walk through nature!"

# Almost forgot the hashtags!


hike_caption += " #nofilter"
hike_caption += " #blessed"
We create the social media caption for the photograph of nature we took on
our hike, but then update the caption to include important social media tags
we almost forgot.

Instructions

1.
We’re doing a little bit of online shopping and find a pair of new sneakers.
Right before we check out, we spot a nice sweater and some fun books we
also want to purchase!

Use the += operator to update the total_price to include the prices


of nice_sweater and fun_books.

The prices (also included in the workspace) are:

 new_sneakers = 50.00
 nice_sweater = 39.00
 fun_books = 20.00
Checkpoint 2 Passed

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums
Here are some helpful links to the top questions asked by coders about this
exercise:

1.

In Python, can the += operator be used to add more than one value at a
time?

2.

Using print() without concatenation?

Still have questions? View this exercise's thread in the Codecademy Forums.

n. Part 14
HELLO WORLD
Multi-line Strings
Python strings are very flexible, but if we try to create a string that occupies
multiple lines we find ourselves face-to-face with a SyntaxError. Python offers a
solution: multi-line strings. By using three quote-marks (""" or ''') instead of
one, we tell the program that the string doesn’t end until the next triple-
quote. This method is useful if the string being defined contains a lot of
quotation marks and we want to be sure we don’t close it prematurely.

leaves_of_grass = """
Poets to come! orators, singers, musicians to come!
Not to-day is to justify me and answer what I am for,
But you, a new brood, native, athletic, continental, greater
than
  before known,
Arouse! for you must justify me.
"""
In the above example, we assign a famous poet’s words to a variable. Even
though the quote contains multiple linebreaks, the code works!

If a multi-line string isn’t assigned a variable or used in an expression it is


treated as a comment.

Instructions

1.
Assign the string

Stranger, if you passing meet me and desire to speak to me, why


  should you not speak to me?
And why should I not speak to you?
to the variable to_you.
Checkpoint 2 Passed

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

Can we perform the same operations on multi-line strings that we


perform on other strings?

2.

How to create a multiline string in the editor?


Still have questions? View this exercise's thread in the Codecademy Forums.

o. Part 15

HELLO WORLD
Review
In this lesson, we accomplished a lot of things! We instructed our computers to print messages,
we stored these messages as variables, and we learned to update those messages depending on
the part of the program we were in. We performed mathematical calculations and explored some
of the mathematical expressions that Python offers us. We learned about errors and other
valuable skills that will continue to serve us as we develop our programming skills.

Good job!

Here are a few more resources to add to your toolkit:

 Codecademy Docs: Python


 Codecademy Workspaces: Python

Make sure to bookmark these links so you have them at your disposal.

Instructions

1.
Create variables:

 my_age
 half_my_age
 greeting
 name
 greeting_with_name

Assign values to each using your knowledge of division and concatenation!


Checkpoint 2 Passed

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a look at this
material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this exercise:

1.
We can use concatenation to create a string that repeats multiple times by adding itself
over and over, but this may become tedious for many repetitions. Is there a shorthand
method to repeat a string multiple times?

2.

What programming language should I choose? (video)

3.

How does real-world software get made? (video)

Still have questions? View this exercise's thread in the Codecademy Forums.


script.py
II. Quiz
1. What happens when running the following code?
message = What a cool message!
print(message)
III. “

IV. 2.
V.

VI. 3.
VII.

VIII. 4.
IX.

X. 5.
XI. 6.
XII.

XIII. 7.
XIV.

XV. 8.
XVI.

XVII. 9.
XVIII.

XIX. 10.s pr
XX.

11.

12.
13.

III. Block letter


LEARN PYTHON 3

Block Letters

ASCII art is a graphic design technique that uses computers for presentation
and consists of pictures pieced together from individual characters.

Write a Python program called initials.py that displays the initials of your


name in block letters as shown and dip your toes into ASCII art.
Happy coding!

Tasks

5/5 Complete

Mark the tasks as complete by checking them off


What we are building in this project:
1.

Take a look at the complete alphabet and find your initials. Notice how each
block letter is 7x5 and formed by the letter itself.

My initials are S and L, so my initials.py program should output:

SSS   L
S   S  L
S      L
SSS   L
    S  L
S   S  L
SSS   LLLLL
Once you are ready, mark this task complete by checking off the box.
Stuck? Get a hint
Setting up:
2.

First, write two comments with:

 Your first and last name.


 A fun fact about yourself.

Stuck? Get a hint

3.

Output your first initial as a block letter. There are a few ways to do this!

Press Save to run your program.


Stuck? Get a hint

4.

Output your second initial as a block letter by adding to the print() statements.

Press Save to run your program.


Stuck? Get a hint
Solution:
5.

Don’t forget to check off all the tasks before moving on.

Sample solutions:

 initials.py
 snowman.py

P.S. If you make something cool, share it with us!


IV.
LEARN PYTHON 3

Receipts for Lovely Loveseats

We’ve decided to pursue the dream of small-business ownership and open up


a furniture store called Lovely Loveseats for Neat Suites on Fleet Street. With
our newfound knowledge of Python programming, we’re going to build a
system to help speed up the process of creating receipts for your customers.

In this project, we will be storing the names and prices of a furniture store’s
catalog in variables. You will then process the total price and item list of
customers, printing them to the output terminal.

Please note: Projects do not run tests against your code. This experience is
more open to your interpretation and gives you the freedom to explore.
Remember that all variables must be declared before they are referenced in
your code.

If you get stuck during this project or would like to see an experienced
developer work through it, click “Get Unstuck“ to see a project walkthrough
video.

Tasks

20/20 Complete

Mark the tasks as complete by checking them off


Adding In The Catalog
1.

Let’s add in our first item, the Lovely Loveseat that is the store’s namesake.
Create a variable called lovely_loveseat_description and assign to it the following
string:

Lovely Loveseat. Tufted polyester blend on wood. 32 inches high x 40 inches wide
x 30 inches deep. Red or white.
Stuck? Get a hint
2.

Great, now let’s create a price for the loveseat. Create a


variable lovely_loveseat_price and set it equal to 254.00.
Stuck? Get a hint

3.

Let’s extend our inventory with another characteristic piece of furniture! Create
a variable called stylish_settee_description and assign to it the following string:

Stylish Settee. Faux leather on birch. 29.50 inches high x 54.75 inches wide x 28
inches deep. Black.
4.

Now let’s set the price for our Stylish Settee. Create a
variable stylish_settee_price and assign it the value of 180.50.
5.

Fantastic, we just need one more item before we’re ready for business. Create
a new variable called luxurious_lamp_description and assign it the following:

Luxurious Lamp. Glass and iron. 36 inches tall. Brown with cream shade.
6.

Let’s set the price for this item. Create a variable called luxurious_lamp_price and
set it equal to 52.15.
7.

In order to be a business, we should also be calculating sales tax. Let’s store


that in a variable as well.

Define the variable sales_tax and set it equal to .088. That’s 8.8%.


Our First Customer
8.

Our first customer is making their purchase! Let’s keep a running tally of their
expenses by defining a variable called customer_one_total. Since they haven’t
purchased anything yet, let’s set that variable equal to 0 for now.
9.
We should also keep a list of the descriptions of things they’re purchasing.
Create a variable called customer_one_itemization and set that equal to the empty
string "". We’ll tack on the descriptions to this as they make their purchases.
Stuck? Get a hint

10.

Our customer has decided they are going to purchase our Lovely Loveseat!
Add the price to customer_one_total.
Stuck? Get a hint

11.

Let’s start keeping track of the items our customer purchased. Add the
description of the Lovely Loveseat to customer_one_itemization.
Stuck? Get a hint

12.

Our customer has also decided to purchase the Luxurious Lamp! Let’s add the
price to the customer’s total.
Stuck? Get a hint

13.

Let’s keep the itemization up-to-date and add the description of the Luxurious
Lamp to our itemization.
14.

They’re ready to check out! Let’s begin by calculating sales tax. Create a
variable called customer_one_tax and set it equal to customer_one_total times sales_tax.
Stuck? Get a hint

15.

Add the sales tax to the customer’s total cost.


Stuck? Get a hint

16.

Let’s start printing up their receipt! Begin by printing out the heading for their
itemization. Print the phrase "Customer One Items:".
Stuck? Get a hint

17.

Print customer_one_itemization.
Stuck? Get a hint

18.

Now add a heading for their total cost: Print out "Customer One Total:"
19.

Now print out their total! Our first customer now has a receipt for the things
they purchased.
20.

Congratulations! We created our catalog and served our first customer. We


used our knowledge of strings and numbers to create and update variables.
We were able to print out an itemized list and a total cost for our customer.
Lovely!

V.
Make the Most of Your Codecademy Membership

Learn about the different features Codecademy has to offer!

Codecademy has helped tens of millions of people to learn to code,


everything from hello world to getting new tech jobs, but when it comes down to
it, you get out what you put in. If you want to be best set up for success, this
guide is for you.
Valuable Resources
There are hundreds of hours of free content on Codecademy, and thousands
of hours of Pro material; but no matter your membership level, the key to
success is learning intelligently. If you build the habits to use our features, it
will be easier for you to master technical skills.

Mobile App
Keep practicing and stay sharp as you go with our mobile app
on iOS and Android.

Workspaces

Workspaces allow learners to work in their own integrated development


environment (IDE) right inside Codecademy. Build or try whatever you want
with these unguided sandboxes, share your code, or keep it private. Not sure
what to make? Grab code from your coursework and use it as a template.

Cheatsheets

Coding is less about memorization and more about understanding principles;


cheatsheets help you quickly refresh your memory and get back to work. You
can find them linked in lessons, or head to their homepage to find them all,
broken down by the course section in which you learned them.

Docs

Cheatsheets are a handy companion for consuming coursework, but when


coding in the real world, programmers need documentation. With Docs, you
have an entirely open-source reference material to cover far more than a
course can.
Code Challenges

With technical interviews (and coding in general), practice makes perfect. Now,
you can practice real code challenges from actual interviews to see how your
skills stack up, or just solve them for fun. If you get stuck, we’ll point you to
what you still need to learn.

Learn What to Learn

Not certain what language to pick up or what career path to choose? Flick
through the Learn What to Learn course, where we’ve consolidated the best
resources to help you make a choice with confidence. An hour of planning
now could save you days of wasted effort later.

There is also an excellent forum post by Galina, one of our curriculum


developers, that discusses how to best get started when beginning your
coding journey.

Community

Learning to code is challenging, but it’s easier if you can team up. Ask
questions, stay connected, and find motivation with multiple communal
experiences through Codecademy:
 Community forum: ask and answer questions about anything on
Codecademy.

 Discord: chat in real-time with other learners across the globe.

 Chapters: find like-minded people in your area and learn to code


together. There are even multiple virtual-first groups to join if you don’t
find one nearby.

 Facebook group: discuss the broader world of coding with tens of


thousands of other learners.

 30-Day Challenge: join others in a sprint to make progress and make


learning a habit.

Video Library

Need a break from the IDE but still want to be productive? Watch hundreds of
educational and motivational video content on everything from basic coding
concepts to career advice, all on-topic and on-platform.

Pro Features
If you want to supercharge your learning, Pro’s the thing for you - here’s how
it can help.

Paths
Skill Paths and Career Paths are step-by-step roadmaps that take you through
what you need to learn a specific skill or transition to a specific career in tech.
They’ll tell you what to learn and in what order, cutting out the guesswork and
to the chase. Our Career Paths cover everything that you’ll find in a $15,000
boot camp curriculum, plus more, and you can team up to tackle them with
a cohort group.

Projects, Challenge Projects, and Portfolio Projects

As you learn, you’ll work on guided projects to put the things you’re learning
to use. You’ll find a variety of project types. Some offer step-by-step guidance
while others offer more of a challenge by only describing the final outcome of
the project. If you take a Path, you’ll build your own Portfolio Projects as well,
designed to simulate professional coding tasks. The solutions to these
portfolio projects will be unique to you! Check out all the projects available to
you via the Projects Library.
Interview prep

If you’re taking one of our Career Paths, you’ll find interview prep essentials
built-in. Learn interview techniques to prepare for technical interviews,
including algorithm and data structure practice. Go even further
with dedicated skill paths on acing the interview across a range of languages
and disciplines.

Practice & Review

With your Pro membership, you’ll find it easier to brush up on what you’ve
learned. Choose for yourself what to practice with links from each module of
your coursework. Or let us take the guesswork out with smart practice. Click
the practice session link from syllabi and AI will prioritize concepts for you by
using spaced repetition — a scientifically proven way of helping you memorize
new ideas.
Quizzes

Test yourself as you make your way through a Path or course. Quizzes help
you retain all the things you’re learning — plus, they’ll help you feel confident
that you’re mastering the material.

Certificates

When you complete a Pro course, you’ll earn a certificate. You can share it on
your resume or your LinkedIn profile to showcase your skills or prepare for
your job search.
Conclusion
If you made it this far, you’re a highly motivated learner - we’re excited to see
how far you’ll go, and hope some of the features you learned about today
help. Please take a moment to answer two quick questions for feedback on
this resource. Happy coding!
VI.
User Input

How to assign variables with user input.

So far, we’ve covered how to assign variables values directly in a Python file.
However, we often want a user of a program to enter new information into the
program.
How can we do this? As it turns out, another way to assign a value to a
variable is through user input.

While we output a variable’s value using print(), we assign information to a


variable using input(). The input() function requires a prompt message, which it
will print out for the user before they enter the new information. For example:
likes_snakes = input("Do you like snakes? ")
In the example above, the following would occur:

1. The program would print "Do you like snakes? " for the user.
2. The user would enter an answer (e.g., "Yes! I have seven pythons as pets!") and
press  enter .
3. The variable likes_snakes would be assigned a value of the user’s answer.
Try constructing a statement to collect user input on your own!

Fill in the blank

Fill in the blanks in the code to complete a statement that asks a user “What is
your favorite flightless bird?” and then stores their answer in the
variable favorite_flightless_bird.
= ()
 input
 favorite_flightless_bird
 prompt
 "What is your favorite flightless bird?"
 get_input
 user.input

Click or drag and drop to fill in the blank

Check answer

Not only can input() be used for collecting all sorts of different information from
a user, but once you have that information stored as a variable you can use it
to simulate interaction:
>>> favorite_fruit = input("What is your favorite fruit? ")
What is your favorite fruit? mango

>>> print("Oh cool! I like " + favorite_fruit + " too, but I think my favorite fruit is apple.")
Oh cool! I like mango too, but I think my favorite fruit is apple.
These are pretty basic implementations of input(), but as you get more familiar
with Python you’ll find more and more interesting scenarios where you will
want to interact with your users.
II. control flow
a. Part 1
CONTROL FLOW
Introduction to Control Flow
Imagine waking up in the morning.

You wake up and think, “Ugh. Is it a weekday?”

If so, you have to get up and get dressed and get ready for work or school. If
not, you can sleep in a bit longer and catch a couple extra Z’s. But alas, it is a
weekday, so you are up and dressed and you go to look outside, “What’s the
weather like? Do I need an umbrella?”

These questions and decisions control the flow of your morning, each step
and result is a product of the conditions of the day and your surroundings.
Your computer, just like you, goes through a similar flow every time it
executes code. A program will run (wake up) and start moving through its
checklists, is this condition met, is that condition met, okay let’s execute this
code and return that value.

This is the control flow of your program. In Python, your script will execute
from the top down, until there is nothing left to run. It is your job to include
gateways, known as conditional statements, to tell the computer when it
should execute certain blocks of code. If these conditions are met, then run
this function.

Over the course of this lesson, you will learn how to build conditional
statements using boolean expressions, and manage the control flow in your
code.

Instructions

Click Next to proceed to the next exercise.

Concept Review
Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

Are decisions in Control Flow required to be binary, as in, only evaluated


to “Yes” or “No”?

Still have questions? View this exercise's thread in the Codecademy Forums.


b. part 2
CONTROL FLOW
Boolean Expressions
In order to build control flow into our program, we want to be able to check if
something is true or not. A boolean expression is a statement that can either
be True or False.

Let’s go back to the ‘waking up’ example. The first question, “Is today a
weekday?” can be written as a boolean expression:

Today is a weekday.
This expression can be True if today is Tuesday, or it can be False if today is
Saturday. There are no other options.

Consider the phrase:

Friday is the best day of the week.


Is this a boolean expression?

No, this statement is an opinion and is not objectively True or False. Someone


else might say that “Wednesday is the best weekday,” and their statement
would be no less True or False than the one above.
How about the phrase:

Sunday starts with the letter 'C'.


Is this a boolean expression?

Yes! This expression can only be True or False, which makes it a boolean


expression. Even though the statement itself is false (Sunday starts with the
letter ‘C’), it is still a boolean expression.

Instructions

1.
Determine if the following statements are boolean expressions or not. If they
are, set the matching variable to the right to "Yes" and if not set the variable
to "No". Here’s an example of what to do:

Example statement:

My dog is the cutest dog in the world.


This is an opinion and not a boolean expression, so you would
set example_statement to "No" in the editor to the right. Okay, now it’s your turn:

Statement one:

Dogs are mammals.


Statement two:

My dog is named Pavel.


Statement three:

Dogs make the best pets.


Statement four:

Cats are female dogs.


Checkpoint 2 Passed

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!
Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

Within the context of this exercise, can boolean expressions be


combined into a longer expression?

2.

Why am I getting the wrong response for statement 4?

Still have questions? View this exercise's thread in the Codecademy Forums.


c. Part 3
CONTROL FLOW
Boolean Variables
Before we go any further, let’s talk a little bit about True and False. You may
notice that when you type them in the code editor (with uppercase T and F),
they appear in a different color than variables or strings. This is
because True and False are their own special type: bool.

True and False arethe only bool types, and any variable that is assigned one of


these values is called a boolean variable.

Boolean variables can be created in several ways. The easiest way is to simply
assign True or False to a variable:

set_to_true = True
set_to_false = False
You can also set a variable equal to a boolean expression.
bool_one = 5 != 7
bool_two = 1 + 1 != 2
bool_three = 3 * 3 == 9
These variables now contain boolean values, so when you reference them they
will only return the True or False values of the expression they were assigned.

print(bool_one)    # True

print(bool_two)    # False

print(bool_three)  # True

Instructions

1.
Create a variable named my_baby_bool and set it equal to "true".
Checkpoint 2 Passed

Stuck? Get a hint


2.
Check the type of my_baby_bool using type(my_baby_bool).

You’ll have to print it to get the results to display in the terminal.


Checkpoint 3 Passed

Stuck? Get a hint


3.
It’s not a boolean variable! Boolean values True and False always need to be
capitalized and do not have quotation marks.

Create a variable named my_baby_bool_two and set it equal to True.


Checkpoint 4 Passed

Stuck? Get a hint


4.
Check the type of my_baby_bool_two and make sure you successfully created a
boolean variable.

You’ll have to print it to get the results to display in the terminal.


Checkpoint 5 Passed

Stuck? Get a hint

Concept Review
Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

True and False seem like valid variable names, so can these be used like
normal variables in Python?

Still have questions? View this exercise's thread in the Codecademy Forums.

d. Part 3
CONTROL FLOW
Relational Operators: Equals and Not Equals
Now that we understand what boolean expressions are, let’s learn to create
them in Python. We can create a boolean expression by using relational
operators.

Relational operators compare two items and return either True or False. For this
reason, you will sometimes hear them called comparators.

The two relational operators we’ll cover first are:

 Equals: ==
 Not equals: !=

These operators compare two items and return True or False if they are equal or
not.

We can create boolean expressions by comparing two values using these


operators:
1 == 1     # True

2 != 4     # True

3 == 5     # False

'7' == 7   # False


Each of these is an example of a boolean expression.

Why is the last statement false? The '' marks in '7' make it a string, which is


different from the integer value 7, so they are not equal. When using relational
operators it is important to always be mindful of type.

Instructions

1.
Determine if the following boolean expressions are True or False. Input your
answer as True or False in the appropriate variable to the right.

Statement one:

(5 * 2) - 1 == 8 + 1


Statement two:

13 - 6 != (3 * 2) + 1


Statement three:

3 * (2 - 1) == 4 - 1


Checkpoint 2 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:
1.

What is the difference between = and == in Python? Is there any


relation?

Still have questions? View this exercise's thread in the Codecademy Forums.

e. Part 5
CONTROL FLOW
If Statement
“Okay okay okay, boolean variables, boolean expressions, blah blah blah, I thought I was
learning how to build control flow into my code!”

You are, I promise you!

Understanding boolean variables and expressions is essential because they are the building
blocks of conditional statements.

Recall the waking-up example from the beginning of this lesson. The decision-making process of
“Is it raining? If so, bring an umbrella” is a conditional statement.

Here it is phrased in a different way:

If it is raining, then bring an umbrella.


Can you pick out the boolean expression here?

Right, "it is raining" is the boolean expression, and this conditional statement is checking to see if it
is True.

If "it is raining" == True then the rest of the conditional statement will be executed and you will bring
an umbrella.

This is the form of a conditional statement:

If [it is raining], then [bring an umbrella]


In Python, it looks very similar:

if is_raining:
  print("bring an umbrella")
You’ll notice that instead of “then” we have a colon, :. That tells the computer that what’s
coming next is what should be executed if the condition is met.

Let’s take a look at another conditional statement:


if 2 == 4 - 2:
  print("apple")
Will this code print apple to the terminal?

Yes, because the condition of the if statement, 2 == 4 - 2 is True.

Let’s work through a couple more together.

Instructions

1.
In script.py, there is an if statement. I wrote this because my coworker Dave kept using my
computer without permission and he is a real doofus. If the user_name is Dave, it tells him to stay
off my computer.

Enter a user name in the field for user_name and try running the program.
Checkpoint 2 Passed

Stuck? Get a hint


2.
Oh no! We got a SyntaxError! This happens when we make a small error in the syntax of the
conditional statement.

Read through the error message carefully and see if you can find the error. Then, fix it, and run
the code again.
Checkpoint 3 Passed

Stuck? Get a hint


3.
Ugh! Dave got around my security and has been logging onto my computer using our coworker
Angela’s user name, angela_catlady_87.

Set your user_name to be angela_catlady_87.

Update the program with a second if statement so it checks for Angela’s user name as well and
prints

"I know it is you, Dave! Go away!"


in response. That’ll teach him!
Checkpoint 4 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a look at this
material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this exercise:
1.

If we had a similar function with multiple if statements, and used print instead of return
for each one, what would happen?

2.

Can I have more than one function with the same name?

Still have questions? View this exercise's thread in the Codecademy Forums.

f. Part 6
CONTROL FLOW
Relational Operators II
Now that we’ve added conditional statements to our toolkit for building
control flow, let’s explore more ways to create boolean expressions. So far we
know two relational operators, equals and not equals, but there are a ton (well,
four) more:

 > greater than
 >= greater than or equal to
 < less than
 <= less than or equal to

Let’s say we’re running a movie streaming platform and we want to write a
program that checks if our users are over 13 when showing them a PG-13
movie. We could write something like:

if age <= 13:


  print("Sorry, parental control required")
This function will take the user’s age and compare it to the number 13. If age is
less than or equal to 13, it will print out a message.

Let’s try some more!


Instructions

1.
Create an if statement that checks if x and y are equal, print the string below if
so:

"These numbers are the same"


Checkpoint 2 Passed

Stuck? Get a hint


2.
The nearby college, Calvin Coolidge’s Cool College (or 4C, as the locals call it)
requires students to earn 120 credits to graduate.

Write an if statement that checks if the student has enough credits to


graduate. If they do, print the string:

"You have enough credits to graduate!"


Can a student with 120 credits graduate from Calvin Coolidge’s Cool College?
Checkpoint 3 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

In the context of this exercise, can relational operators be applied to


values other than numbers?

2.
Do I need to be utilizing return or print?

Still have questions? View this exercise's thread in the Codecademy Forums.

g. Part 7
CONTROL FLOW
Boolean Operators: and
Often, the conditions you want to check in your conditional statement will
require more than one boolean expression to cover. In these cases, you can
build larger boolean expressions using boolean operators. These operators
(also known as logical operators) combine smaller boolean expressions into
larger boolean expressions.

There are three boolean operators that we will cover:

 and
 or
 not

Let’s start with and.

and combines
two boolean expressions and evaluates as True if both its
components are True, but False otherwise.

Consider the example:

Oranges are a fruit and carrots are a vegetable.


This boolean expression is comprised of two smaller expressions, oranges are a
fruit and carrots are a vegetable, both of which are True and connected by the
boolean operator and, so the entire expression is True.

Let’s look at an example of some AND statements in Python:

(1 + 1 == 2) and (2 + 2 == 4)   # True

(1 > 9) and (5 != 6)            # False

(1 + 1 == 2) and (2 < 1)        # False


(0 == 10) and (1 + 1 == 1)      # False
Notice that in the second and third examples, even though part of the
expression is True, the entire expression as a whole is False because the other
statement is False. The fourth statement is also False because both components
are False.

Instructions

1.
Set the variables statement_one and statement_two equal to the results of the
following boolean expressions:

Statement one:

(2 + 2 + 2 >= 6) and (-1 * -1 < 0)


Statement two:

(4 * 2 <= 8) and (7 - 1 == 6)


Checkpoint 2 Passed

2.
Let’s return to Calvin Coolidge’s Cool College. 120 credits aren’t the only
graduation requirement, you also need to have a GPA of 2.0 or higher.

Rewrite the if statement so that it checks to see if a student meets both


requirements using an and statement.

If they do, print the string:

"You meet the requirements to graduate!"


Checkpoint 3 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums
Here are some helpful links to the top questions asked by coders about this
exercise:

1.

What is the order of operations for logical operators?

2.

If we have a transitive relation of expressions combined with and , like (a


< b) and (b < c) and (c < d) , can this be shortened?

Still have questions? View this exercise's thread in the Codecademy Forums.

h. Part 8
CONTROL FLOW
Boolean Operators: or
The boolean operator or combines two expressions into a larger expression
that is True if either component is True.

Consider the statement

Oranges are a fruit or apples are a vegetable.


This statement is composed of two expressions: oranges are a fruit which
is True and apples are a vegetable which is False. Because the two expressions are
connected by the or operator, the entire statement is True. Only one
component needs to be True for an or statement to be True.

In English, or implies that if one component is True, then the other component


must be False. This is not true in Python. If an or statement has
two True components, it is also True.

Let’s take a look at a couple of examples in Python:


True or (3 + 4 == 7)    # True
(1 - 1 == 0) or False   # True
(2 < 0) or True         # True
(3 == 8) or (3 > 4)     # False
Notice that each or statement that has at least one True component is True, but
the final statement has two False components, so it is False.

Instructions

1.
Set the variables statement_one and statement_two equal to the results of the
following boolean expressions:

Statement one:

(2 - 1 > 3) or (-5 * 2 == -10)


Statement two:

(9 + 5 <= 15) or (7 != 4 + 3)


Checkpoint 2 Passed

2.
The registrar’s office at Calvin Coolidge’s Cool College has another request.
They want to send out a mailer with information on the commencement
ceremonies to students who have met at least one requirement for graduation
(120 credits and 2.0 GPA).

Write an if statement that checks if a student either has 120 or more


credits or a GPA 2.0 or higher, and if so prints:

"You have met at least one of the requirements."


Checkpoint 3 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums
Here are some helpful links to the top questions asked by coders about this
exercise:

1.

When comparing one value with multiple values, can we just separate
each value with or ?

Still have questions? View this exercise's thread in the Codecademy Forums.

i. Part 9
CONTROL FLOW
Boolean Operators: not
The final boolean operator we will cover is not. This operator is straightforward:
when applied to any boolean expression it reverses the boolean value. So if we
have a True statement and apply a not operator we get a False statement.

not True == False


not False == True
Consider the following statement:

Oranges are not a fruit.


Here, we took the True statement oranges are a fruit and added a not operator to
make the False statement oranges are not a fruit.

This example in English is slightly different from the way it would appear in
Python because in Python we add the not operator to the very beginning of the
statement. Let’s take a look at some of those:

not 1 + 1 == 2  # False


not 7 < 0       # True

Instructions

1.
Set the variables statement_one and statement_two equal to the results of the
following boolean expressions:
Statement one:

not (4 + 5 <= 9)


Statement two:

not (8 * 2) != 20 - 4


Checkpoint 2 Passed

2.
The registrar’s office at Calvin Coolidge’s Cool College has been so impressed
with your work so far that they have another task for you.

They want you to return to a previous if statement and add in several checks


using and and not statements:

 If a student’s credits is not greater or equal to 120, it should print:

"You do not have enough credits to graduate."

 If their gpa is not greater or equal to 2.0, it should print:

"Your GPA is not high enough to graduate."

 If their credits is not greater than or equal to 120 and their gpa is


not greater than or equal to 2.0, it should print:

"You do not meet either requirement to graduate!"


Make sure your return value matches those strings exactly. Capitalization,
punctuation, and spaces matter!
Checkpoint 3 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:
1.

In Python, why would this work, (not True == False), but not this? (True
== not False)

2.

What is an example of the not boolean?

Still have questions? View this exercise's thread in the Codecademy Forums.

j. Part 10
CONTROL FLOW
Else Statements
As you can tell from your work with Calvin Coolidge’s Cool College, once you
start including lots of if statements in a function the code becomes a little
cluttered and clunky. Luckily, there are other tools we can use to build control
flow.

else statements
allow us to elegantly describe what we want our code to do
when certain conditions are not met.

else statements
always appear in conjunction with if statements. Consider our
waking-up example to see how this works:

if weekday:
  print("wake up at 6:30")
else:
  print("sleep in")
In this way, we can build if statements that execute different code if conditions
are or are not met. This prevents us from needing to write if statements for
each possible condition, we can instead write a blanket else statement for all
the times the condition is not met.
Let’s return to our if statement for our movie streaming platform. Previously,
all it did was check if the user’s age was over 13 and if so, print out a message.
We can use an else statement to return a message in the event the user is too
young to watch the movie.

if age >= 13:


  print("Access granted.")
else:
  print("Sorry, you must be 13 or older to watch this movie.")

Instructions

1.
Calvin Coolidge’s Cool College has another request for you. They want you to
add an additional check to a previous if statement. If a student is failing to
meet both graduation requirements, they want it to print:

"You do not meet the requirements to graduate."


Add an else statement to the existing if statement.
Checkpoint 2 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

In Python, is it necessary, or best practice, to include an else for every if


statement?
2.

Why can’t else go in the middle of different ifs?

Still have questions? View this exercise's thread in the Codecademy Forums.

k. Part 11
CONTROL FLOW
Else If Statements
We have if statements, we have else statements, we can also
have elif statements.

Now you may be asking yourself, what the heck is an elif statement? It’s exactly
what it sounds like, “else if”. An elif statement checks another condition after
the previous if statements conditions aren’t met.

We can use elif statements to control the order we want our program to check


each of our conditional statements. First, the if statement is checked, then
each elif statement is checked from top to bottom, then finally the else code is
executed if none of the previous conditions have been met.

Let’s take a look at this in practice. The following if statement will display a


“thank you” message after someone donates to a charity; there will be a
curated message based on how much was donated.

print("Thank you for the donation!")

if donation >= 1000:


  print("You've achieved platinum status")
elif donation >= 500:
  print("You've achieved gold donor status")
elif donation >= 100:
  print("You've achieved silver donor status")
else:
  print("You've achieved bronze donor status")
Take a second to think about this function. What would happen if all of
the elif statements were simply if statements? If you donated $1100.00, then
the first three messages would all print because each if condition had been
met.

But because we used elif statements, it checks each condition sequentially and


only prints one message. If I donate $600.00, the code first checks if that is
over 1000, which it is not, then it checks if it’s over 500, which it is, so it prints
that message, then because all of the other statements are elif and else, none of
them get checked and no more messages get printed.

Try your hand at some other elif statements.

Instructions

1.
Calvin Coolidge’s Cool College has noticed that students prefer to get letter
grades.

Write an if/elif/else statement that:

 If grade is 90 or higher, print "A"


 Else if grade is 80 or higher, print "B"
 Else if grade is 70 or higher, print "C"
 Else if grade is 60 or higher, print "D"
 Else, print "F"
Checkpoint 2 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.
Is there a limit to the number of elif statements allowed?

2.

Do I need to return grade, or are there other options?

3.

Why can’t I set a global variable within a function?

Still have questions? View this exercise's thread in the Codecademy Forums.

l. Part 12
CONTROL FLOW
Review
Great job! We covered a ton of material in this lesson and we’ve increased the
number of tools in our Python toolkit by several-fold. Let’s review what we’ve
learned this lesson:

 Boolean expressions are statements that can be either True or False


 A boolean variable is a variable that is set to either True or False.
 We can create boolean expressions using relational operators:
o ==: Equals
o !=: Not equals
o >: Greater than
o >=: Greater than or equal to
o <: Less than
o <=: Less than or equal to
 if statements can be used to create control flow in your code.
 else statements can be used to execute code when the conditions of
an if statement are not met.
 elif statements can be used to build additional checks into
your if statements

Let’s put these skills to the test!

Instructions

Optional: Little Codey is an interplanetary space boxer, who is trying to win


championship belts for various weight categories on other planets within the
solar system.

Write a space.py program that helps Codey keep track of their target weight
by:

1. Checks which number planet is equal to.


2. It should then compute their weight on the destination planet.

Here is the table of conversions:

# Planet Relative Gravity


1 Venus 0.91
2 Mars 0.38
3 Jupiter 2.34
4 Saturn 1.06
5 Uranus 0.92
6 Neptune 1.19
Click to see a hint!
Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

A Boolean expression with multiple conditions can get quite long. How
to keep things concise?

2.

How to correctly use NOT?

3.

What are the differences between using if and elif?

Still have questions? View this exercise's thread in the Codecademy Forums


 Quiz
Magic 8 ball
LEARN PYTHON 3

Magic 8-Ball

The Magic 8-Ball is a popular toy developed in the 1950s for fortune-telling or


advice seeking.

Write a magic8.py Python program that can answer any “Yes” or “No”


question with a different fortune each time it executes.
We’ll be using the following 9 possible answers for our Magic 8-Ball:

 Yes - definitely.
 It is decidedly so.
 Without a doubt.
 Reply hazy, try again.
 Ask again later.
 Better not tell you now.
 My sources say no.
 Outlook not so good.
 Very doubtful.

The output of the program will have the following format:

[Name] asks: [Question]


Magic 8-Ball’s answer: [Answer]
For example:

Joe asks: Is this real life?


Magic 8-Ball's answer: Better not tell you now
Let’s get started!

Tasks

15/15 Complete

Mark the tasks as complete by checking them off


Setting up
1.

In magic8.py, declare a variable name and assign it to the name of the person


who will be asking the Magic 8-Ball.
Stuck? Get a hint

2.

Next, declare a variable question, and assign it to a “Yes” or “No” question you’d


like to ask the Magic 8-Ball.
Stuck? Get a hint

3.
We want to store the answer of the Magic 8-Ball in another variable, which
we’ll call answer. For now, assign this variable to an empty string.
Stuck? Get a hint
Generating a random number
4.

In order for the answer to be different each time we run the program, we will
utilize randomly generated values.

Note: This will be something new! But don’t worry, we will try to explain this
topic thoroughly and also supply the code.

In Python, we can use the .randint() function from the random module to generate


a random number from a range.

But first, let’s import this module so we can use its functions. Add this line of
code to the top of magic8.py:

import random
Stuck? Get a hint

5.

Next, we’ll create a variable to store the randomly generated value. Declare a
variable called random_number, and assign it to the function call:

random.randint(1, 9)
which will generate a random number between 1 (inclusive) and 9 (inclusive).

Next, add a print() statement that outputs the value of random_number, and run the
program several times to ensure random values are being generated as
expected.

Once you’re sure this is working as we expected, feel free to comment out
this print() statement.
Stuck? Get a hint
Control Flow
6.
Now that we’ve declared all the variables needed, it’s time to implement the
core logic of our program!

For this section, we’ll be utilizing control flow using an if/elif/else statement to


assign different answers for each randomly generated value.

First, write an if statement where if the random_number is equal to 1, answer is


assigned to the phrase “Yes - definitely.”
Stuck? Get a hint

7.

Next, write an elif statement after the if statement where if the random_number is


equal to 2, answer is assigned to the phrase “It is decidedly so”.

Then, continue writing elif statements for each of the remaining phrases for the
values 3 to 9.

Recall that the 9 possible answers of the Magic 8-Ball are:

1. Yes - definitely.
2. It is decidedly so.
3. Without a doubt.
4. Reply hazy, try again.
5. Ask again later.
6. Better not tell you now.
7. My sources say no.
8. Outlook not so good.
9. Very doubtful.
Stuck? Get a hint

8.

Following the if/elif statements, add an else statement that will set answer to the


string “Error”, if the number was accidentally assigned a value outside of our
range.
Stuck? Get a hint
Seeing the result
9.

Now, let’s see our program in action! Write a print() statement to output the
asker’s name and their question, which should be in the following format:

[Name] asks: [Question]


For example, when we run the program, the output should look something
like:

Joe asks: Will I win the lottery?


Stuck? Get a hint

10.

Add a second print() statement that will output the Magic 8-Ball’s answer in the


following format:

Magic 8-Ball's answer: [answer]


For example, when running the program it should look something like:

Magic 8-Ball's answer: My sources say no


Stuck? Get a hint

11.

Great job! You’ve successfully utilized your knowledge of conditionals and


previous fundamental Python concepts to create a program that generates
different fortunes.

Run your program several times to see that it’s working as expected.
Stuck? Get a hint
Optional Challenges
12.

If you’re up for some more challenges, try implementing the following


features to your program.

So far, the Magic 8-Ball provides 9 possible fortunes. Try to add a few more
possible answers to the program.
To do this, you will need to increase the range of randomly generated
numbers and add additional elif statements for each new answer.
Stuck? Get a hint

13.

What if the asker does not provide a name, such that the value of name is an
empty string? If the name string is empty, the output of the program looks like
the following:

asks: Will I win the lottery?


Magic 8 Ball's answer: Outlook not so good
As you can see, the formatting of the output can use some improvement when
there is no name provided.

We can address this by printing out just the question, such that it looks like
the following:

Question: Will I win the lottery?


Magic 8-Ball's answer: Outlook not so good
You can implement this by creating an if/else statement such that:

 If the name is an empty string, it will only print the question.


 Else, the player’s name and question are both printed.

Stuck? Get a hint

14.

What if the question string is empty? If the user does not provide any question,
then the Magic 8-Ball cannot provide a fortune, otherwise, the fabric of reality
is at risk!

To ensure that the fabric of reality is safe, we can create an if/else statement


where:

 If the question is an empty string, print out a message to the user.


 Else, print the name and question, with the Magic 8-Ball’s answer.

Stuck? Get a hint


Solution
15.

Don’t forget to check off all the tasks before moving on.

Sample solutions:

 magic8.py

P.S. If you make something cool, share it with us!


Stuck? Get a hint

d. shall shipping
LEARN PYTHON 3
Sal's Shipping
Sal runs the biggest shipping company in the tri-county area, Sal’s Shippers. Sal wants to make
sure that every single one of his customers has the best, and most affordable experience shipping
their packages.

In this project, you’ll build a program that will take the weight of a package and determine the
cheapest way to ship that package using Sal’s Shippers.

Sal’s Shippers has several different options for a customer to ship their package:

 Ground Shipping, which is a small flat charge plus a rate based on the weight of your
package.

 Ground Shipping Premium, which is a much higher flat charge, but you aren’t charged
for weight.

 Drone Shipping (new), which has no flat charge, but the rate based on weight is triple the
rate of ground shipping.

Here are the prices:

Ground Shipping

Price per Flat


Weight of Package
Pound Charge
2 lb or less $1.50 $20.00
Price per Flat
Weight of Package
Pound Charge
Over 2 lb but less
$3.00 $20.00
than or equal to 6 lb
Over 6 lb but less
$4.00 $20.00
than or equal to 10 lb
Over 10 lb $4.75 $20.00

Ground Shipping Premium

Flat charge: $125.00

Drone Shipping

Price per Flat


Weight of Package
Pound Charge
2 lb or less $4.50 $0.00
Over 2 lb but less
$9.00 $0.00
than or equal to 6 lb
Over 6 lb but less
than or equal to 10 $12.00 $0.00
lb
Over 10 lb $14.25 $0.00

Write a shipping.py Python program that asks the user for the weight of their package and then
tells them which method of shipping is cheapest and how much it will cost to ship their package
using Sal’s Shippers.

Note that the walkthrough video for this project is slightly out of date — the walkthrough was
done using a version of this project that uses functions. Feel free to come back to the video after
having been introduced to functions!
Tasks

9/9 Complete
Mark the tasks as complete by checking them off
Ground Shipping:
1.
First things first, define a weight variable and set it equal to any number.
Stuck? Get a hint
2.
Next, we need to know how much it costs to ship a package of given weight by normal ground
shipping based on the “Ground shipping” table above.

Write a comment that says “Ground Shipping”.

Create an if/elif/else statement for the cost of ground shipping. It should check for weight, and print
the cost of shipping a package of that weight.
Stuck? Get a hint
3.
A package that weighs 8.4 pounds should cost $53.60 to ship with normal ground shipping:

8.4\ lb \times \$4.00 + \$20.00 = \$53.608.4 lb×$4.00+$20.00=$53.60


Test that your ground shipping function gets the same value.
Stuck? Get a hint
Ground Shipping Premium:
4.
We’ll also need to make sure we include the price of premium ground shipping in our code.

Create a variable for the cost of premium ground shipping.

Note: This does not need to be an if statement because the price of premium ground shipping
does not change with the weight of the package.
Stuck? Get a hint
5.
Print it out for the user just in case they forgot!
Stuck? Get a hint
Drone Shipping:
6.
Write a comment for this section of the code, “Drone Shipping”.

Create an if/elif/else statement for the cost of drone shipping. This statement should check
against weight and print the cost of shipping a package of that weight.
Stuck? Get a hint
7.
A package that weighs 1.5 pounds should cost $6.75 to ship by drone:

1.5\ lb \times \$4.50 + \$0.00 = \$6.751.5 lb×$4.50+$0.00=$6.75


Test that your drone shipping function gets the same value.
Solution:
8.
Great job! Now, test everything one more time!

What is the cheapest method of shipping a 4.8 pound package and how much would it cost?

What is the cheapest method of shipping a 41.5 pound package and how much would it cost?

(See hint for answers)


Stuck? Get a hint
9.
Don’t forget to check off all the tasks before moving on.

Sample solutions:

 shipping.py

P.S. If you make something cool, share it with us!


Stuck? Get a hint
shipping.py
V. Erros in python

ERRORS IN PYTHON
Review
Finding bugs is a huge part of a programmer’s life. Don’t be intimidated by
them! In fact, errors in your code mean you’re trying to do something cool.
In this lesson, we have learned about the three types of Python errors:

 SyntaxError:Error caused by not following the proper structure (syntax) of


the language.
 NameError: Errors reported when the interpreter detects an object that is
unknown.
 TypeError: Errors thrown when an operation is applied to an object of an
inappropriate type.

There is also another type of error that doesn’t have error messages that we
will cover down the line:

 Logic errors: Errors found by the programmer when the program isn’t
doing what it is intending to do.

Remember, Google and Stack Overflow are a programmer’s BFFs (best friends


forever) in situations where an error is giving you a lot of trouble. For some
more motivation, check out this blog post.

We wish you the best of luck in your bug-squashing journey! 🔎

Instructions

Inside review.py, see if you can intentionally spin up some new errors!

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Still have questions? View this exercise's thread in the Codecademy Forums.


C.Lists
1. introductions
a. INTRODUCTION TO LISTS
What is a List?
In programming, it is common to want to work with collections of data. In
Python, a list is one of the many built-in data structures that allows us to work
with a collection of data in sequential order.

Suppose we want to make a list of the heights of students in a class:

 Noelle is 61 inches tall


 Ava is 70 inches tall
 Sam is 67 inches tall
 Mia is 64 inches tall

In Python, we can create a variable called heights to store these integers into


a list:

heights = [61, 70, 67, 64]


Notice that:

1. A list begins and ends with square brackets ( [ and ]).


2. Each item (i.e., 67 or 70) is separated by a comma (,)
3. It’s considered good practice to insert a space () after each comma, but
your code will run just fine if you forget the space.

Let’s write our own list!

Instructions

1.
Examine the existing list heights in your code editor.

A new student just joined the class!

 Chloe is 65 inches tall

Add Chloe’s height to the end of the list heights.


Checkpoint 2 Passed

Stuck? Get a hint


2.
Remove the # in front of the definition of the list broken_heights. If you run this
code, you’ll get an error in your terminal:
SyntaxError: invalid syntax
Add commas (,) to broken_heights so that it runs without errors.
Checkpoint 3 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

For this exercise, how can I edit the existing list variable in the code to
add new data items?

2.

Why do lists use brackets instead of parenthesis?

3.

How can I look up the index of an item in my list?

Still have questions? View this exercise's thread in the Codecademy Forums.


b. INTRODUCTION TO LISTS
What can a List contain?
Lists can contain more than just numbers.

Let’s revisit our classroom example with heights:

 Noelle is 61 inches tall


 Ava is 70 inches tall
 Sam is 67 inches tall
 Mia is 64 inches tall

Instead of storing each student’s height, we can make a list that contains their
names:

names = ["Noelle", "Ava", "Sam", "Mia"]


We can even combine multiple data types in one list. For example, this list
contains both a string and an integer:

mixed_list_string_number = ["Noelle", 61]


Lists can contain any data type in Python! For example, this list contains a
string, integer, boolean, and float.

mixed_list_common = ["Mia", 27, False, 0.5]


Let’s experiment with different data types in our own lists!

Instructions

1.
Add any additional string to the end of the list ints_and_strings.
Checkpoint 2 Passed

Stuck? Get a hint


2.
Create a new list called sam_height_and_testscore that contains:

1. The string "Sam" (to represent Sam’s name)


2. The number 67 (to represent Sam’s height)
3. The float 85.5 (to represent Sam’s score)
4. The boolean True (to represent Sam passing the test)

Make sure to write the elements in exact order.


Checkpoint 3 Passed
Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

Is it possible to put different types of data in the same list variable?

Still have questions? View this exercise's thread in the Codecademy Forums.


c. INTRODUCTION TO LISTS
Empty Lists
A list doesn’t have to contain anything. You can create an empty list like this:

empty_list = []
Why would we create an empty list?

Usually, it’s because we’re planning on filling it up later based on some other input. We’ll talk
about two ways of filling up a list in the next exercise.

Let’s practice writing an empty list!

Instructions

1.
Create an empty list and call it my_empty_list. Don’t put anything in the list just yet.
Checkpoint 2 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a look at this
material's cheatsheet!
Community Forums

Here are some helpful links to the top questions asked by coders about this exercise:

1.

For this exercise, are there any other options for creating an empty list?

Still have questions? View this exercise's thread in the Codecademy Forums.


script.py
1
2
my_empty_list = []
your_empty_list = []

Run
 
Output:

d. INTRODUCTION TO LISTS

List Methods
As we start exploring lists further in the next exercises, we will encounter the
concept of a method.

In Python, for any specific data-type ( strings, booleans, lists, etc. ) there is
built-in functionality that we can use to create, manipulate, and even delete
our data. We call this built-in functionality a method.

For lists, methods will follow the form of list_name.method(). Some methods will
require an input value that will go between the parenthesis of the method ( ).
An example of a popular list method is .append(), which allows us to add an
element to the end of a list.

append_example = [ 'This', 'is', 'an', 'example']


append_example.append('list')

print(append_example)
Will output:

['This', 'is', 'an', 'example', 'list']

Instructions

We will be exploring .append() and many other methods in the upcoming


exercises but for now take a second to examine and play around with the code
for two common list methods.

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Still have questions? View this exercise's thread in the Codecademy Forums.


e. INTRODUCTION TO LISTS
Growing a List: Append
We can add a single element to a list using the .append() Python method.

Suppose we have an empty list called garden:

garden = []
We can add the element "Tomatoes" by using the .append() method:

garden.append("Tomatoes")

print(garden)
Will output:
['Tomatoes']
We see that garden now contains "Tomatoes"!

When we use .append() on a list that already has elements, our new element is
added to the end of the list:

# Create a list
garden = ["Tomatoes", "Grapes", "Cauliflower"]

# Append a new element


garden.append("Green Beans")
print(garden)
Will output:

['Tomatoes', 'Grapes', 'Cauliflower', 'Green Beans']


Let’s use the .append() method to manipulate a list.

Instructions

1.
Jiho works for a gardening store called Petal Power. Jiho keeps a record of
orders in a list called orders.

Use print to inspect the orders he has received today.


Checkpoint 2 Passed

Stuck? Get a hint


2.
Jiho just received a new order for "tulips". Use append to add this string to orders.
Checkpoint 3 Passed

Stuck? Get a hint


3.
Another order has come in! Use append to add "roses" to orders.
Checkpoint 4 Passed

Stuck? Get a hint


4.
Use print to inspect the orders Jiho has received today.
Checkpoint 5 Passed

Stuck? Get a hint

Concept Review
Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

Is it possible to use the append() function to add more than one item at
a time to a list?

Still have questions? View this exercise's thread in the Codecademy Forums.


f. INTRODUCTION TO LISTS
Growing a List: Plus (+)
When we want to add multiple items to a list, we can use + to combine two
lists (this is also known as concatenation).

Below, we have a list of items sold at a bakery called items_sold:

items_sold = ["cake", "cookie", "bread"]


Suppose the bakery wants to start selling "biscuit" and "tart":

items_sold_new = items_sold + ["biscuit", "tart"]


print(items_sold_new)
Would output:

['cake', 'cookie', 'bread', 'biscuit', 'tart']


In this example, we created a new variable, items_sold_new, which contained both
the original items sold, and the new items. We can inspect the
original items_sold and see that it did not change:

print(items_sold)
Would output:

['cake', 'cookie', 'bread']


We can only use + with other lists. If we type in this code:

my_list = [1, 2, 3]
my_list + 4
we will get the following error:

TypeError: can only concatenate list (not "int") to list


If we want to add a single element using +, we have to put it into a list with
brackets ([]):

my_list + [4]
Let’s use + to practice combining two lists!

Instructions

1.
Jiho is updating a list of orders. He just received orders for "lilac" and "iris".

Create a list called new_orders that contains our new orders.


Checkpoint 2 Passed

Stuck? Get a hint


2.
Use + to create a new list called orders_combined that
combines orders with new_orders.
Checkpoint 3 Passed

Stuck? Get a hint


3.
Remove the # and whitespace in front of the list broken_prices. If you run this
code, you’ll get an error:

TypeError: can only concatenate list (not "int") to list


Fix the command by inserting brackets ([ and ]) so that it will run without
errors.
Checkpoint 4 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!
Community Forums

Still have questions? View this exercise's thread in the Codecademy Forums.


h. INTRODUCTION TO LISTS
Accessing List Elements
We are interviewing candidates for a job. We will call each candidate in order,
represented by a Python list:

calls = ["Juan", "Zofia", "Amare", "Ezio", "Ananya"]


First, we’ll call "Juan", then "Zofia", etc.

In Python, we call the location of an element in a list its index.

Python lists are zero-indexed. This means that the first element in a list has
index 0, rather than 1.

Here are the index numbers for the list calls:

Element Index
"Juan" 0
"Zofia" 1
"Amare" 2
"Ezio" 3
"Ananya" 4

In this example, the element with index 2 is "Amare".

We can select a single element from a list by using square brackets ( []) and the
index of the list item. If we wanted to select the third element from the list,
we’d use calls[2]:

print(calls[2])
Will output:

Amare
Note: When accessing elements of a list, you must use an int as the index. If
you use a float, you will get an error. This can be especially tricky when using
division. For example print(calls[4/2]) will result in an error, because 4/2 gets
evaluated to the float 2.0.

To solve this problem, you can force the result of your division to be an int by
using the int() function. int() takes a number and cuts off the decimal point. For
example, int(5.9) and int(5.0) will both become 5. Therefore, calls[int(4/2)] will result
in the same value as calls[2], whereas calls[4/2] will result in an error.

Instructions

1.
Use square brackets ([ and ]) to select the 4th employee from the list employees.
Save it to the variable employee_four.
Checkpoint 2 Passed

Stuck? Get a hint


2.
Paste the following code into script.py:

print(employees[8])
What happens? Why?
Checkpoint 3 Passed

Stuck? Get a hint


3.
Selecting an element that does not exist produces an IndexError.

In the line of code that you pasted, change 8 to an index that exists so that
you don’t get an IndexError.

Run your code again!


Checkpoint 4 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Still have questions? View this exercise's thread in the Codecademy Forums.


INTRODUCTION TO LISTS
Accessing List Elements: Negative Index
What if we want to select the last element of a list?

We can use the index -1 to select the last item of a list, even when we don’t
know how many elements are in a list.

Consider the following list with 6 elements:

pancake_recipe = ["eggs", "flour", "butter", "milk", "sugar", "love"]


If we select the -1 index, we get the final element, "love".

print(pancake_recipe[-1])
Would output:

love
This is equivalent to selecting the element with index 5:

print(pancake_recipe[5])
Would output:

love
Here are the negative index numbers for our list:

Element Index
"eggs" -6
"flour" -5
"butter" -4
"milk" -3
"sugar" -2
"love" -1

Instructions

1.
Create a variable called last_element.

Assign the last element in shopping_list to the variable last_element using a negative


index.
Checkpoint 2 Passed

Stuck? Get a hint


2.
Now select the element with index 5 and save it to the variable index5_element.
Checkpoint 3 Passed
Stuck? Get a hint
3.
Use print to display both index5_element and last_element.

Note that they are equal to "cereal"!


Checkpoint 4 Passed

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Still have questions? View this exercise's thread in the Codecademy Forums.


INTRODUCTION TO LISTS
Modifying List Elements
Let’s return to our garden.

garden = ["Tomatoes", "Green Beans", "Cauliflower", "Grapes"]


Unfortunately, we forgot to water our cauliflower and we don’t think it is
going to recover.

Thankfully our friend Jiho from Petal Power came to the rescue. Jiho gifted us
some strawberry seeds. We will replace the cauliflower with our new seeds.

We will need to modify the list to accommodate the change to our garden list.


To change a value in a list, reassign the value using the specific index.

garden[2] = "Strawberries"

print(garden)
Will output:

["Tomatoes", "Green Beans", "Strawberries", "Grapes"]


Negative indices will work as well.

garden[-1] = "Raspberries"

print(garden)
Will output:

["Tomatoes", "Green Beans", "Strawberries", "Raspberries"]

Instructions

1.
We have decided to start selling some of our garden produce. Word around
our town has spread and people are interested in getting some of our
delicious vegetables and fruit.

We decided to create a waitlist to make sure we can sell to all of our new
customers!

Define a list called garden_waitlist and set the value to contain our customers (in
order): "Jiho", "Adam", "Sonny", and "Alisha".
Checkpoint 2 Passed

Stuck? Get a hint


2.
"Adam" decided his fridge is too full at the moment and asked us to remove
him from the waitlist and make space for one of our other townsfolk.

Replace "Adam" with our other interested customer "Calla" using the index


method we used in the narrative.

Print garden_waitlist to see the change!


Checkpoint 3 Passed

Stuck? Get a hint


3.
Alisha realized she was already stocked with all the items we are selling. She
asked us to replace her with her friend Alex who just ran out.

Replace Alisha with Alex using a negative index.

Print garden_waitlist again to see the change!


Checkpoint 4 Passed

Stuck? Get a hint

Concept Review
Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Still have questions? View this exercise's thread in the Codecademy Forums.


INTRODUCTION TO LISTS
Shrinking a List: Remove
We can remove elements in a list using the .remove() Python method.

Suppose we have a filled list called shopping_line that represents a line at a


grocery store:

shopping_line = ["Cole", "Kip", "Chris", "Sylvana"]


We could remove "Chris" by using the .remove() method:

shopping_line.remove("Chris")

print(shopping_line)
If we examine shopping_line, we can see that it now doesn’t contain "Chris":

["Cole", "Kip", "Sylvana"]


We can also use .remove() on a list that has duplicate elements.

Only the first instance of the matching element is removed:

# Create a list
shopping_line = ["Cole", "Kip", "Chris", "Sylvana", "Chris"]

# Remove a element
shopping_line.remove("Chris")
print(shopping_line)
Will output:

["Cole", "Kip", "Sylvana", "Chris"]


Let’s practice using the .remove() method to remove elements from a list.

Instructions

1.
We have decided to get into the grocery store business. Our manager Calla
has decided to store all the inventory purchases in a list to help track what
products need to be ordered.

Let’s create a list called order_list with the following values (in this particular
order):

"Celery", "Orange Juice", "Orange", "Flatbread"

Print order_list to see the current list.


Checkpoint 2 Passed

Stuck? Get a hint


2.
We are in luck! We actually found a spare case of "Flatbread" in our back storage.
We won’t need to order it anymore. Let’s remove it from order_list using
the .remove() method.

Print order_list to see the current list.


Checkpoint 3 Passed

Stuck? Get a hint


3.
Our store has grown to be a huge success! We decided to open a second
store and require a new order list. Calla has done us the favor of putting one
together.

Create a new list called new_store_order_list and assign it the following values (in


order):

"Orange", "Apple", "Mango", "Broccoli", "Mango"

Note: Our second store is going to need two orders of mangos so the value is
duplicated.

Print new_store_order_list to see the current list.


Checkpoint 4 Passed

Stuck? Get a hint


4.
We are in luck again! We actually found a spare case of "Mango" in our back
storage.
We won’t be needing to place two orders anymore.

Let’s remove it from new_store_order_list using the .remove() method.

Print new_store_order_list to see the current list.


Checkpoint 5 Passed

Stuck? Get a hint


5.
Calla ran to tell us some important news! She asked us to remove "Onions" from
our new new_store_order_list. If we double-check our list, we will notice we don’t
have "Onions" on our list.

Let’s see what happens when we try to remove an item that does not exist.

Call the .remove() method with the value of "Onions" on our new_store_order_list list.


Checkpoint 6 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Still have questions? View this exercise's thread in the Codecademy Forums.


INTRODUCTION TO LISTS
Two-Dimensional (2D) Lists
We’ve seen that the items in a list can be numbers or strings. Lists can contain
other lists! We will commonly refer to these as two-dimensional (2D) lists.

Once more, let’s look at a class height example:

 Noelle is 61 inches tall


 Ava is 70 inches tall
 Sam is 67 inches tall
 Mia is 64 inches tall

Previously, we saw that we could create a list representing both Noelle’s name
and height:
noelle = ["Noelle", 61]
We can put several of these lists into one list, such that each entry in the list
represents a student and their height:

heights = [["Noelle", 61], ["Ava", 70], ["Sam", 67], ["Mia", 64]]


We will often find that a two-dimensional list is a very good structure for
representing grids such as games like tic-tac-toe.

#A 2d list with three lists in each of the indices.


tic_tac_toe = [
            ["X","O","X"],
            ["O","X","O"],
            ["O","O","X"]
]
Let’s practice creating our own 2D list!

Instructions

1.
A new student named "Vik" has joined our class. Vik is 68 inches tall. Add a
sublist to the end of the heights list that represents Vik and his height.
Checkpoint 2 Passed

Stuck? Get a hint


2.
Create a two-dimensional list called ages where each sublist contains a
student’s name and their age. Use the following data:

 "Aaron" is 15
 "Dhruti" is 16
Checkpoint 3 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums
Here are some helpful links to the top questions asked by coders about this
exercise:

1.

Can a list variable contain items which are also lists of data?

Still have questions? View this exercise's thread in the Codecademy Forums.


INTRODUCTION TO LISTS
Accessing 2D Lists
Let’s return to our classroom heights example:

heights = [["Noelle", 61], ["Ali", 70], ["Sam", 67]]


Two-dimensional lists can be accessed similar to their one-dimensional
counterpart. Instead of providing a single pair of brackets [ ] we will use an
additional set for each dimension past the first.

If we wanted to access "Noelle"‘s height:

#Access the sublist at index 0, and then access the 1st index of that sublist.
noelles_height = heights[0][1]
print(noelles_height)
Would output:

61
Here are the index numbers to access data for the list heights:

Element Index
"Noelle" heights[0][0]
61 heights[0][1]
"Ali" heights[1][0]
70 heights[1][1]
"Sam" heights[2][0]
67 heights[2][1]

Let’s practice accessing data in a two-dimensional list.

Instructions
1.
We want to have a way to store all of our classroom test score data.

Using the provided table, create a two-dimensional list called class_name_test to


represent the data. Each sublist in class_name_test should have one student’s
name and their associated score.

Name Test Score


"Jenny" 90
"Alexus" 85.5
"Sam" 83
"Ellie" 101.5

Print class_name_test to see the result.


Checkpoint 2 Passed

Stuck? Get a hint


2.
Use double square brackets ([][]) to select Sam‘s test score from the
list class_name_test.

Save it to the variable sams_score.

Print the variable sams_score to see the result.


Checkpoint 3 Passed

Stuck? Get a hint


3.
Use double square brackets ([][]) to select Ellies test score from the
list class_name_test. This time only use negative indices!

Save it to the variable ellies_score.

Print the variable ellies_score to see the result.


Checkpoint 4 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums
Still have questions? View this exercise's thread in the Codecademy Forums.
INTRODUCTION TO LISTS
Modifying 2D Lists
Now that we know how to access two-dimensional lists, modifying the
elements should come naturally.

Let’s return to a classroom example, but now instead of heights or test scores,
our list stores the student’s favorite hobby!

class_name_hobbies = [["Jenny", "Breakdancing"], ["Alexus", "Photography"],


["Grace", "Soccer"]]
"Jenny" changed their mind and is now more interested in "Meditation".

We will need to modify the list to accommodate the change to


our class_name_hobbies list. To change a value in a two-dimensional list, reassign
the value using the specific index.

# The list of Jenny is at index 0. The hobby is at index 1.


class_name_hobbies[0][1] = "Meditation"
print(class_name_hobbies)
Would output:

[["Jenny", "Meditation"], ["Alexus", "Photography"], ["Grace", "Soccer"]]


Negative indices will work as well.

# The list of Grace is the last entry. The hobby is the last element.
class_name_hobbies[-1][-1] = "Football"
print(class_name_hobbies)
Would output:

[["Jenny", "Meditation"], ["Alexus", "Photography"], ["Grace", "Football"]]

Instructions

1.
Our school is expanding! We are welcoming a new set of students today from
all over the world.
Using the provided table, create a two-dimensional list called incoming_class to
represent the data. Each sublist in incoming_class should contain the name,
nationality, and grade for a single student.

Grade
Name Nationality
Level
"Kenny" "American" 9
"Tanya" "Russian" 9
"Madison" "Indian" 7

Print incoming_class to see our list.


Checkpoint 2 Passed

Stuck? Get a hint


2.
"Madison" passed an exam to advance a grade. She will be pushed into 8th
grade rather than her current 7th in our list.

Modify the list using double brackets [][] to make the change. Use positive
indices.

Print incoming_class to see our change.


Checkpoint 3 Passed

Stuck? Get a hint


3.
"Kenny" likes to be called by his nickname "Ken". Modify the list using double
brackets [][] to accommodate the change but only using negative indices.

Print incoming_class to see our change.


Checkpoint 4 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Still have questions? View this exercise's thread in the Codecademy Forums.


INTRODUCTION TO LISTS
Review
So far, we have learned:

 How to create a list


 How to access, add, remove, and modify list elements
 How to create a two-dimensional list
 How to access and modify two-dimensional list elements

Let’s practice these skills.

Instructions

1.
Maria is entering customer data for her web store business. We’re going to
help her organize her data.

Start by turning this list of customer first names into a list called first_names.
Make sure to enter the names in this order:

 Ainsley
 Ben
 Chani
 Depak
Checkpoint 2 Passed

Stuck? Get a hint


2.
Maria wants to track all customer’s preferred sizes for her clothing. Create a
list called preferred_size.

Fill our new list preferred_size with the following data, containing the preferred
sizes for Ainsley, Ben, and Chani:

["Small", "Large", "Medium"]


Checkpoint 3 Passed

Stuck? Get a hint


3.
Oh no! We forgot to add Depak’s size.

Depak’s size is "Medium". Use .append() to add "Medium" to the preferred_size list.


Print preferred_size to see our change.
Checkpoint 4 Passed

Stuck? Get a hint


4.
Maria is having a hard time visualizing which customer is associated with each
size. Let’s restructure our two lists into a two-dimensional list to help Maria.

In addition to our already available data, Maria is adding a third value for each
customer that reflects if they want expedited shipping on their orders.

This will be reflected using a boolean value ( True for expedited, False for regular)

Create a two-dimensional list called customer_data using the following table as a


reference for the data. Each sublist should contain a name, size, and expedited
shipping option for a single person.

Expedited
Name Size
Shipping
"Ainsley" "Small" True
"Ben" "Large" False
"Medium
"Chani"
" True
"Medium
"Depak"
" False

Print customer_data to see the data.


Checkpoint 5 Passed

Stuck? Get a hint


5.
"Chani" reached out to Maria. She requested to switch to regular shipping to
save some money.

Change the data value for "Chani"‘s shipping preference to False in our two-
dimensional list to reflect the change.
Checkpoint 6 Passed

Stuck? Get a hint


6.
"Ben" reached out to Maria asking to remove his shipping option because he is
not sure what type he wants.
Use the .remove() method to delete the shipping value from the sublist that
contains ben’s data.

Note: We never explicitly went over how to use the .remove() method on a 2d


list together. If you feel like you are struggling, take a look at the hint for some
guidance.
Checkpoint 7 Passed

Stuck? Get a hint


7.
Great job making it this far! One last thing, Maria received new
customers, "Amit" and "Karim", the following 2d list contains their data:

[["Amit", "Large", True], ["Karim", "X-Large", False]]


Create a new variable customer_data_final. Combine our existing
list customer_data with our new customer 2d list using + by adding it to the end
of customer_data.

Print customer_data_final to see our final result.


Checkpoint 8 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

If I have a list containing items, how can I empty or delete all the
contents of the list?

Still have questions? View this exercise's thread in the Codecademy Forums.


b. Quiz
c. Gradebook
LEARN PYTHON 3

Gradebook

You are a student and you are trying to organize your subjects and grades
using Python. Let’s explore what we’ve learned about lists to organize your
subjects and scores.

Tasks

10/10 Complete

Mark the tasks as complete by checking them off


Create Some Lists:
1.

Create a list called subjects and fill it with the classes you are taking:
 "physics"
 "calculus"
 "poetry"
 "history"

Stuck? Get a hint

2.

Create a list called grades and fill it with your scores:

 98
 97
 85
 88

Stuck? Get a hint

3.

Manually (without any methods) create a two-dimensional list to


combine subjects and grades. Use the table below as a reference to associated
values.

Name Test Score


"physics" 98

"calculus" 97

"poetry" 85

"history" 88

Assign the value into a variable called gradebook.


Stuck? Get a hint

4.

Print gradebook.

Does it look how you expected it would?


Stuck? Get a hint
Add More Subjects:
5.

Your grade for your computer science class just came in! You got a perfect
score, 100!

Use the .append() method to add a list with the values of "computer science" and an


associated grade value of 100 to our two-dimensional list of gradebook.
Stuck? Get a hint

6.

Your grade for "visual arts" just came in! You got a 93!

Use append to add ["visual arts", 93] to gradebook.


Stuck? Get a hint
Modify The Gradebook:
7.

Our instructor just told us they made a mistake grading and are rewarding an
extra 5 points for our visual arts class.

Access the index of the grade for your visual arts class and modify it to be 5
points greater.
Stuck? Get a hint

8.

You decided to switch from a numerical grade value to a Pass/Fail option for
your poetry class.

Find the grade value in your gradebook for your poetry class and use
the .remove() method to delete it.
Stuck? Get a hint

9.

Use the .append() method to then add a new "Pass" value to the sublist where


your poetry class is located.
Stuck? Get a hint
One Big Gradebook!
10.

You also have your grades from last semester, stored in last_semester_gradebook.

Create a new variable full_gradebook that combines


both last_semester_gradebook and gradebook using + to have one complete grade
book.

Print full_gradebook to see our completed list.


d. Working with list in python
1. WORKING WITH LISTS IN PYTHON
Working with Lists

Now that we know how to create and access list data, we can start to explore
additional ways of working with lists.

In this lesson, you’ll learn how to:

 Add and remove items from a list using a specific index.


 Create lists with continuous values.
 Get the length of a list.
 Select portions of a list (called slicing).
 Count the number of times that an element appears in a list.
 Sort a list of items.

Note: In some of the exercises, we will be using built-in functions in Python. If


you haven’t yet explored the concept of a function, it may look a bit new.
Below we compare it to the method syntax we learned in the earlier lesson.

Here is a preview:

# Example syntax for methods


list.method(input)

# Example syntax for a built-in function


builtinfuncion(input)
Instructions

Take a second to preview some of the things we will be learning by examining


the graphic of common list methods and built-in functions.

When you’re ready, continue to the next exercise.

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

Is it possible to sort() a list but do it in reverse order?

Still have questions? View this exercise's thread in the Codecademy Forums.


c. WORKING WITH LISTS IN PYTHON
2.

Adding by Index: Insert

The Python list method .insert() allows us to add an element to a specific index


in a list.

The .insert() method takes in two inputs:

1. The index you want to insert into.


2. The element you want to insert at the specified index.

The .insert() method will handle shifting over elements and can be used with
negative indices.
To see it in action let’s imagine we have a list representing a line at a store:

store_line = ["Karla", "Maxium", "Martim", "Isabella"]


"Maxium" saved a spot for his friend "Vikor" and we need to adjust the list to add
him into the line right behind "Maxium".

For this example, we can assume that "Karla" is the front of the line and the rest
of the elements are behind her.

Here is how we would use the .insert() method to insert "Vikor" :

store_line.insert(2, "Vikor")
print(store_line)
Would output:

['Karla', 'Maxium', 'Vikor', 'Martim', 'Isabella']


Some important things to note:

1. The order and number of the inputs is important. The .insert() method


expects two inputs, the first being a numerical index, followed by any
value as the second input.
2. When we insert an element into a list, all elements from the specified
index and up to the last index are shifted one index to the right. This
does not apply to inserting an element to the very end of a list as it will
simply add an additional index and no other elements will need to shift.
Let’s practice using .insert()!

Instructions

2.

We are helping out a popular grocery store called Jiho’s Produce.

Every week the store has to choose the order in which it displays some of its
popular items on sale in the front window to attract customers.

Jiho, the store owner, likes to store the items for the display in a list.
Check out the current display list in our code editor. Click Run to print out the
list.
Checkpoint 2 Passed

2.

Jiho found out some great news! "Pineapple" is back in stock.

Jiho would like to put "Pineapple" in the front of the list so it is the first item
customers see in the display window.

Use .insert() to add "Pineapple" to the front of the list.

Print the resulting list to see the change.

Note: For this list, the front will be the element at index 0
Checkpoint 3 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Still have questions? View this exercise's thread in the Codecademy Forums.

3. WORKING WITH LISTS IN PYTHON

Removing by Index: Pop

Just as we learned to insert elements at specific indices, Python gives us a


method to remove elements at a specific index using a method called .pop().

The .pop() method takes an optional single input:

1. The index for the element you want to remove.

To see it in action, let’s consider a list called cs_topics that stores a collection of


topics one might study in a computer science program.
cs_topics = ["Python", "Data Structures", "Balloon Making", "Algorithms", "Clowns
101"]
Two of these topics don’t look like they belong, let’s see how we remove them
using .pop().

First let’s remove "Clowns 101":

removed_element = cs_topics.pop()
print(cs_topics)
print(removed_element)
Would output:

['Python', 'Data Structures', 'Balloon Making', 'Algorithms']


'Clowns 101'
Notice two things about this example:

1. The method can be called without a specific index. Using .pop() without


an index will remove whatever the last element of the list is. In our
case "Clowns 101" gets removed.
2. .pop() is unique in that it will return the value that was removed. If we
wanted to know what element was deleted, simply assign a variable to
the call of the .pop() method. In this case, we assigned it to removed_element.
Lastly let’s remove "Balloon Making":

cs_topics.pop(2)
print(cs_topics)
Would output:

['Python', 'Data Structures', 'Algorithms']


Notice two things about this example:

1. The method can be called with an optional specific index to remove. In


our case, the index 2 removes the value of "Balloon Making".
2. We don’t have to save the removed value to any variable if we don’t
care to use it later.

Note: Passing in an index that does not exist or calling .pop() on an empty list


will both result in an IndexError.
Let’s apply what we learned about the .pop() method.

Instructions

1.

We have decided to pursue the study of data science in addition to our


computer science coursework. We signed up for an online school that would
help us become proficient.

Check out the current list of topics we will be studying in our code editor.

Click Run to print out the list.


Checkpoint 2 Passed

2.

It looks like we have an overlap with our computer science curriculum for the
topic of "Python 3".

Let’s remove the topic from the list of data_science_topics using our newly
learned .pop() method.

Print data_science_topics to see your result.


Checkpoint 3 Passed

Stuck? Get a hint

3.

Looks like there is overlap on the "Algorithms" topic as well. Let’s use .pop() to


remove it as well.

Print data_science_topics to see the changes.


Checkpoint 4 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums
Still have questions? View this exercise's thread in the Codecademy Forums.
4.
WORKING WITH LISTS IN PYTHON

Consecutive Lists: Range

Often, we want to create a list of consecutive numbers in our programs. For


example, suppose we want a list containing the numbers 0 through 9:

my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Typing out all of those numbers takes time and the more numbers we type,
the more likely it is that we have a typo that can cause an error.

Python gives us an easy way of creating these types of lists using a built-in
function called range().

The function range() takes a single input, and generates numbers starting


at 0 and ending at the number before the input.

So, if we want the numbers from 0 through 9, we use range(10) because 10 is 1


greater than 9:

my_range = range(10)
print(my_range)
Would output:

range(0, 10)
Notice something different? The range() function is unique in that it creates
a range object. It is not a typical list like the ones we have been working with.

In order to use this object as a list, we have to first convert it using another
built-in function called list().

The list() function takes in a single input for the object you want to convert.

We use the list() function on our range object like this:

print(list(my_range))
Would output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Let’s try out using range()!

Instructions

1.

Modify number_list so that it is a range containing numbers starting at 0 and up


to, but not including, 9.
Checkpoint 2 Passed

Stuck? Get a hint

2.

Create a range called zero_to_seven with the numbers 0 through 7.

Print the result in list form.


Checkpoint 3 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Still have questions? View this exercise's thread in the Codecademy Forums.


5.
WORKING WITH LISTS IN PYTHON

The Power of Range!

By default, range() creates a list starting at 0. However, if we call range() with two


inputs, we can create a list that starts at a different number.

For example, range(2, 9) would generate numbers starting at 2 and ending


at 8 (just before 9):
my_list = range(2, 9)
print(list(my_list))
Would output:

[2, 3, 4, 5, 6, 7, 8]
If we use a third input, we can create a list that “skips” numbers.

For example, range(2, 9, 2) will give us a list where each number is 2 greater than
the previous number:

my_range2 = range(2, 9, 2)
print(list(my_range2))
Would output:

[2, 4, 6, 8]
We can skip as many numbers as we want!

For example, we’ll start at 1 and skip in increments of 10 between each number
until we get to 100:

my_range3 = range(1, 100, 10)


print(list(my_range3))
Would output:

[1, 11, 21, 31, 41, 51, 61, 71, 81, 91]
Our list stops at 91 because the next number in the sequence would be 101,
which is greater than 100 (our stopping point).

Let’s experiment with our additional range() inputs!

Instructions

1.

Modify the range() function that created the range range_five_three such that it:

 Starts at 5
 Has a difference of 3 between each item
 Ends before 15
Checkpoint 2 Passed
Stuck? Get a hint

2.

Create a range called range_diff_five that:

 Starts at 0
 Has a difference of 5 between each item
 Ends before 40
Checkpoint 3 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Still have questions? View this exercise's thread in the Codecademy Forums.


6.
WORKING WITH LISTS IN PYTHON

Length

Often, we’ll need to find the number of items in a list, usually called its length.

We can do this using a built-in function called len().

When we apply len() to a list, we get the number of elements in that list:

my_list = [1, 2, 3, 4, 5]

print(len(my_list))
Would output:

5
Let’s find the length of various lists!
Instructions

1.

Calculate the length of long_list and save it to the variable long_list_len.


Checkpoint 2 Passed

Stuck? Get a hint

2.

Use print() to examine long_list_len.
Checkpoint 3 Passed

Stuck? Get a hint

3.

We have provided a completed range() function for the variable big_range.

Calculate its length using the function len() and save it to a variable


called big_range_length.

Note: Range objects do not need to be converted to lists in order to


determine their length
Checkpoint 4 Passed

Stuck? Get a hint

4.

Use print() to examine big_range_length.
Checkpoint 5 Passed

Stuck? Get a hint

5.

Change the range() function that generates big_range so that it skips 100 instead


of 10 steps between items.

How does this change big_range_length?


Checkpoint 6 Passed

Stuck? Get a hint

Concept Review
Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

What is the relationship between the value returned by len() and the
indexes which can be used to access elements of a list?

Still have questions? View this exercise's thread in the Codecademy Forums.


7.
WORKING WITH LISTS IN PYTHON

Slicing Lists I

In Python, often we want to extract only a portion of a list. Dividing a list in


such a manner is referred to as slicing.

Lets assume we have a list of letters:

letters = ["a", "b", "c", "d", "e", "f", "g"]


Suppose we want to select from "b" through "f".

We can do this using the following syntax: letters[start:end], where:

 start isthe index of the first element that we want to include in our


selection. In this case, we want to start at "b", which has index 1.
 end is the index of one more than the last index that we want to include.
The last element we want is "f", which has index 5, so end needs to be 6.

sliced_list = letters[1:6]
print(sliced_list)
Would output:
["b", "c", "d", "e", "f"]
Notice that the element at index 6 (which is "g") is not included in our selection.

Instructions

1.

Use print() to examine the variable beginning.

Before hitting Run think about what elements beginning will contain?


Checkpoint 2 Passed

2.

Modify beginning, so that it selects the first 2 elements of suitcase.


Checkpoint 3 Passed

Stuck? Get a hint

3.

Create a new list called middle that contains the middle two items ( ["pants",
"pants"] ) from suitcase.

Print middle to see the slice!


Checkpoint 4 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

Can list elements be accessed in any order?


2.

Why is the end index one higher than the index we want?

Still have questions? View this exercise's thread in the Codecademy Forums.


8.
WORKING WITH LISTS IN PYTHON

Slicing Lists II

Slicing syntax in Python is very flexible. Let’s look at a few more problems we
can tackle with slicing.

Take the list fruits as our example:

fruits = ["apple", "cherry", "pineapple", "orange", "mango"]


If we want to select the first  n  elements of a list, we could use the following
code:

fruits[:n]
For our fruits list, suppose we wanted to slice the first three elements.

The following code would start slicing from index 0 and up to index 3. Note
that the fruit at index 3 (orange) is not included in the results.

print(fruits[:3])
Would output:

['apple', 'cherry', 'pineapple']


We can do something similar when we want to slice the last  n  elements in a
list:

fruits[-n:]
For our fruits list, suppose we wanted to slice the last two elements.
This code slices from the element at index -2 up through the last index.

print(fruits[-2:])
Would output:

['orange', 'mango']
Negative indices can also accomplish taking all but n last elements of a list.

fruits[:-n]
For our fruits example, suppose we wanted to slice all but the last element from
the list.

This example starts counting from the 0 index up to the element at index -1.

print(fruits[:-1])
Would output:

['apple', 'cherry', 'pineapple', 'orange']


Let’s practice some of these extra slicing techniques!

Instructions

1.

Create a new list called last_two_elements containing the final two elements


of suitcase.

Print last_two_elements to see your result.


Checkpoint 2 Passed

Stuck? Get a hint

2.

Create a new list called slice_off_last_three containing all but the last three


elements.

Print slice_off_last_three to see your result.


Checkpoint 3 Passed

Stuck? Get a hint

Concept Review
Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

Is there a way to find the last item in a list without using the len()
function?

Still have questions? View this exercise's thread in the Codecademy Forums.


9.
WORKING WITH LISTS IN PYTHON

Counting in a List

In Python, it is common to want to count occurrences of an item in a list.

Suppose we have a list called letters that represents the letters in the word


“Mississippi”:

letters = ["m", "i", "s", "s", "i", "s", "s", "i", "p", "p", "i"]
If we want to know how many times i appears in this word, we can use the list
method called .count():

num_i = letters.count("i")
print(num_i)
Would output:

4
Notice that since .count() returns a value, we can assign it to a variable to use it.

We can even use .count() to count element appearances in a two-dimensional


list.
Let’s use the list number_collection as an example:

number_collection = [[100, 200], [100, 200], [475, 29], [34, 34]]


If we wanted to know how often the sublist [100, 200] appears:

num_pairs = number_collection.count([100, 200])


print(num_pairs)
Would output:

2
Let’s count some list items using the .count() method!

Instructions

1.

Mrs. Wilson’s class is voting for class president. She has saved each student’s
vote into the list votes.

Use .count() to determine how many students voted for "Jake" and save the value
to a variable called jake_votes.
Checkpoint 2 Passed

Stuck? Get a hint

2.

Use print() to examine jake_votes.
Checkpoint 3 Passed

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

If the item being counted isn’t in the list, will count() return an error?
Still have questions? View this exercise's thread in the Codecademy Forums.
10.
WORKING WITH LISTS IN PYTHON

Sorting Lists I

Often, we will want to sort a list in either numerical (1, 2, 3, …) or alphabetical


(a, b, c, …) order.

We can sort a list using the method .sort().

Suppose that we have a list of names:

names = ["Xander", "Buffy", "Angel", "Willow", "Giles"]


Let’s see what happens when we apply .sort():

names.sort()
print(names)
Would output:

['Angel', 'Buffy', 'Giles', 'Willow', 'Xander']


As we can see, the .sort() method sorted our list of names in alphabetical order.

.sort() also
provides us the option to go in reverse. Instead of sorting in
ascending order like we just saw, we can do so in descending order.

names.sort(reverse=True)
print(names)
Would output:

['Xander', 'Willow', 'Giles', 'Buffy', 'Angel']


Note: The .sort() method does not return any value and thus does not need to
be assigned to a variable since it modifies the list directly. If we do assign the
result of the method, it would assign the value of None to the variable.

Let’s experiment sorting various lists!


Instructions

1.

Use .sort() to sort addresses.
Checkpoint 2 Passed

Stuck? Get a hint

2.

Use print() to see how addresses changed.


Checkpoint 3 Passed

3.

Remove the # and whitespace in front of the line sort(names). Edit this line so that
it runs without producing a NameError.
Checkpoint 4 Passed

Stuck? Get a hint

4.

Use print to examine sorted_cities. Why is it not the sorted version of cities?


Checkpoint 5 Passed

Stuck? Get a hint

5.

Edit the .sort() call on cities such that it sorts the cities in reverse order


(descending).

Print cities to see the result.


Checkpoint 6 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:
1.

Can a list be sorted in reverse order?

2.

Why does a sorted list print as none?

3.

What is the method of order for sorting the addresses?

Still have questions? View this exercise's thread in the Codecademy Forums.


11.
WORKING WITH LISTS IN PYTHON

Sorting Lists II

A second way of sorting a list in Python is to use the built-in function sorted().

The sorted() function is different from the .sort() method in two ways:

1. It comes before a list, instead of after as all built-in functions do.


2. It generates a new list rather than modifying the one that already exists.

Let’s return to our list of names:

names = ["Xander", "Buffy", "Angel", "Willow", "Giles"]


Using sorted(), we can create a new list, called sorted_names:
sorted_names = sorted(names)
print(sorted_names)
This yields the list sorted alphabetically:

['Angel', 'Buffy', 'Giles', 'Willow', 'Xander']


Note that using sorted did not change names:

print(names)
Would output:

['Xander', 'Buffy', 'Angel', 'Willow', 'Giles']

Instructions

1.

Use sorted() to order games and create a new list called games_sorted.


Checkpoint 2 Passed

Stuck? Get a hint

2.

Print both games and games_sorted. How are they different?


Checkpoint 3 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

Both sort() and sorted() can be used to sort a list. What is the difference
between them and when would I want to use one versus the other?
Still have questions? View this exercise's thread in the Codecademy Forums.
12.
WORKING WITH LISTS IN PYTHON

Review

In this lesson, we learned how to:

 Add elements to a list by index using the .insert() method.


 Remove elements from a list by index using the .pop() method.
 Generate a list using the range() function.
 Get the length of a list using the len() function.
 Select portions of a list using slicing syntax.
 Count the number of times that an element appears in a list using
the .count() method.
 Sort a list of items using either the .sort() method or sorted() function.

As you go through the exercises, feel free to use print() to see changes when
not explicitly asked to do so.

Instructions

1.

Our friend Jiho has been so successful in both the flower and grocery business
that she has decided to open a furniture store.

Jiho has compiled a list of inventory items into a list called inventory and wants
to know a few facts about it.

First, how many items are in the warehouse?

Save the answer to a variable called inventory_len.


Checkpoint 2 Passed

Stuck? Get a hint

2.
Select the first element in inventory. Save it to a variable called first.
Checkpoint 3 Passed

Stuck? Get a hint

3.

Select the last element from inventory. Save it to a variable called last.


Checkpoint 4 Passed

Stuck? Get a hint

4.

Select items from the inventory starting at index 2 and up to, but not including,


index 6.

Save your answer to a variable called inventory_2_6.


Checkpoint 5 Passed

Stuck? Get a hint

5.

Select the first 3 items of inventory. Save it to a variable called first_3.


Checkpoint 6 Passed

Stuck? Get a hint

6.

How many 'twin bed's are in inventory? Save your answer to a variable


called twin_beds.
Checkpoint 7 Passed

Stuck? Get a hint

7.

Remove the 5th element in the inventory. Save the value to a variable
called removed_item.
Checkpoint 8 Passed

Stuck? Get a hint

8.

There was a new item added to our inventory called "19th Century Bed Frame".

Use the .insert() method to place the new item as the 11th element in our
inventory.
Checkpoint 9 Passed
Stuck? Get a hint

9.

Sort inventory using the .sort() method or the sorted() function.

Remember, the sorted() function doesn’t change the original list — it creates a


new list with the elements properly sorted. If you use sorted() you’ll have to
set inventory equal to the value returned by sorted().

Print inventory to see the result.


Checkpoint 10 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

Is it possible to sort() a list but do it in reverse order?

Still have questions? View this exercise's thread in the Codecademy Forums.


V. Quiz
VI.
LEARN PYTHON 3

Len's Slice

You work at Len’s Slice, a new pizza joint in the neighborhood. You are going
to use your knowledge of Python lists to organize some of your sales data.

Tasks

14/14 Complete

Mark the tasks as complete by checking them off


Make Some Pizzas
1.

To keep track of the kinds of pizzas you sell, create a list called toppings that
holds the following:

 "pepperoni"
 "pineapple"
 "cheese"
 "sausage"
 "olives"
 "anchovies"
 "mushrooms"

Stuck? Get a hint

2.

To keep track of how much each kind of pizza slice costs, create a list
called prices that holds the following integer values:

 2
 6
 1
 3
 2
 7
 2

Stuck? Get a hint


3.

Your boss wants you to do some research on $2 slices.

Count the number of occurrences of 2 in the prices list, and store the result in a
variable called num_two_dollar_slices. Print it out.
Stuck? Get a hint

4.

Find the length of the toppings list and store it in a variable called num_pizzas.


Stuck? Get a hint

5.

Print the string We sell [num_pizzas] different kinds of pizza!,


where [num_pizzas] represents the value of our variable num_pizzas.
Stuck? Get a hint

6.

Use the existing data about the pizza toppings and prices to create a new two-
dimensional list called pizza_and_prices.

Each sublist in pizza_and_prices should have one pizza topping and an associated


price.

Price Topping
2 "pepperoni"

6 "pineapple"

1 "cheese"

3 "sausage"

2 "olives"

7 "anchovies"

2 "mushrooms"
For this new list make sure the prices come before the topping name like so:

[price, topping_name]
Note: You don’t need to use your original toppings and prices lists in this exercise.
Create a new two-dimensional list from scratch.
Stuck? Get a hint

7.

Print pizza_and_prices.

Does it look the way you expect?


Stuck? Get a hint
Sorting and Slicing Pizzas
8.

Sort pizza_and_prices so that the pizzas are in the order of increasing price


(ascending).
Stuck? Get a hint

9.

Store the first element of pizza_and_prices in a variable called cheapest_pizza.


Stuck? Get a hint

10.

A man walks into the pizza store and shouts “I will have your MOST
EXPENSIVE pizza!”

Get the last item of the pizza_and_prices list and store it in a variable


called priciest_pizza.
Stuck? Get a hint

11.

It looks like the most expensive pizza from the previous step was our very
last "anchovies" slice. Remove it from our pizza_and_prices list since the man bought
the last slice.
Stuck? Get a hint
12.

Since there is no longer an "anchovies" pizza, you want to add a new topping


called "peppers" to keep your customers excited about new toppings. Here is
what your new topping looks like:

[2.5, "peppers"]
Add the new peppers pizza topping to our list pizza_and_prices.

Note: Make sure to position it relative to the rest of the sorted data


in pizza_and_prices, otherwise our data will not be correctly sorted anymore!
Stuck? Get a hint

13.

Three mice walk into the store. They don’t have much money (they’re mice),
but they do each want different pizzas.

Slice the pizza_and_prices list and store the 3 lowest cost pizzas in a list


called three_cheapest.
Stuck? Get a hint

14.

Great job! The mice are very pleased and will be leaving you a 5-star review.

Print the three_cheapest list.
VII.
https://youtu.be/yDvRR8nWMNI
VIII.

Combining Lists: The Zip Function

Learn about a popular Python built-in function called zip().

In Python, we have an assortment of built-in functions that allow us to build


our programs faster and cleaner. One of those functions is zip().
The zip() function allows us to quickly combine associated data-sets without
needing to rely on multi-dimensional lists. While zip() can work with many
different scenarios, we are going to explore only a single one in this article.
Let’s use a list of student names and associated heights as our example data
set:

 Jenny is 61 inches tall

 Alexus is 70 inches tall

 Sam is 67 inches tall

 Grace is 64 inches tall

Suppose that we already had a list of names and a list of heights:

names = ["Jenny", "Alexus", "Sam", "Grace"]


heights = [61, 70, 67, 64]

If we wanted to create a nested list that paired each name with a height, we could use
the built-in function zip().
The zip() function takes two (or more) lists as inputs and returns an object that contains a
list of pairs. Each pair contains one element from each of the inputs. This is how we
would do it for our names and heights lists:
names_and_heights = zip(names, heights)

If we were to then examine this new variable names_and_heights, we would find it


looks a bit strange:
print(names_and_heights)

Would output:

<zip object at 0x7f1631e86b48>

This zip object contains the location of this variable in our computer’s memory.


Don’t worry though, it is fairly simple to convert this object into a useable list
by using the built-in function list():
converted_list = list(names_and_heights)
print(converted_list)
Outputs:

[('Jenny', 61), ('Alexus', 70), ('Sam', 67), ('Grace', 64)]


Notice two things:

1. Our data set has been converted from a zip memory object to an actual list
(denoted by [ ])
2. Our inner lists don’t use square brackets [ ] around the values. This is because
they have been converted into tuples (an immutable type of list).
Let’s practice using zip()!
Coding question

Use zip() to create a new variable called names_and_dogs_names that


combines owners and dogs_names lists into a zip object.
Then, create a new variable named list_of_names_and_dogs_names by calling
the list() function on names_and_dogs_names.
Print list_of_names_and_dogs_names.
Answer:

owners = ["Jenny", "Alexus", "Sam", "Grace"]
dogs_names = ["Elphonse", "Dr. Doggy DDS", "Carter", "Ralph"]
names_and_dogs_names = zip(owners, dogs_names)
list_of_names_and_dogs_names = list(names_and_dogs_names)
print(list_of_names_and_dogs_names)
D. Loops
I. Loops
1. What are loops
LOOPS

What are Loops?

In our everyday lives, we tend to repeat a lot of processes without noticing.

For instance, if we want to cook a delicious recipe, we might have to prepare


our ingredients by chopping them up. We chop and chop and chop until all of
our ingredients are the right size. At this point, we stop chopping.
If we break down our chopping task into a series of three smaller steps, we
have:

1. An initialization: We’re ready to cook and have a collection of


ingredients we want to chop. We will start at the first ingredient.
2. A repetition: We’re chopping away. We are performing the action of
chopping over and over on each of our ingredients, one ingredient at a
time.
3. An end condition: We see that we have run out of ingredients to chop
and so we stop.
In programming, this process of using an initialization, repetitions, and an
ending condition is called a loop. In a loop, we perform a process
of iteration (repeating tasks).

Programming languages like Python implement two types of iteration:

1. Indefinite iteration, where the number of times the loop is executed


depends on how many times a condition is met.
2. Definite iteration, where the number of times the loop will be executed
is defined in advance (usually based on the collection size).
Typically we will find loops being used to iterate a collection of items. In the
above example, we can think of our ingredients we want to chop as our
collection. This is a form of definite iteration since we know how long our
collection is in advance and thus know how many times we need to iterate
over the collection of ingredients.

Some collections might be small — like a short string, while other collections
might be massive like a range of numbers from 1 to 10,000,000! But don’t
worry, loops give us the ability to masterfully handle both ends of the
spectrum. This simple, but powerful, concept saves us a lot of time and makes
it easier for us to work with large amounts of data.

In this lesson, we’ll learn how to use Python to implement both definite and
indefinite iteration in our own programs.

Instructions
Look over (and over) the provided diagram. Then, go to the next exercise to
get looped in!

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Still have questions? View this exercise's thread in the Codecademy Forums.

2. Why loops
LOOPS

Why Loops?

Before we get to writing our own loops, let’s explore what programming
would be like if we couldn’t use loops.

Let’s say we have a list of ingredients and we want to print every element in the
list:

ingredients = ["milk", "sugar", "vanilla extract", "dough", "chocolate"]


If we only use print(), our program might look like this:

print(ingredients[0])
print(ingredients[1])
print(ingredients[2])
print(ingredients[3])
print(ingredients[4])
The output would be:

milk
sugar
vanilla extract
dough
chocolate
That’s still manageable, We’re writing 5 print() statements (or copying and
pasting a few times). Now imagine if we come back to this program and our
list had 10, or 24601, or … 100,000,000 elements? It would take an extremely
long time and by the end, we could still end up with inconsistencies and
mistakes.

Don’t dwell too long on this tedious scenario — we’ll learn how loops can help
us out in the next exercise. For now, let’s gain an appreciation for loops.

Instructions

1.

Using 10 print() statements, print out: "This can be so much easier with loops!".


Checkpoint 2 Passed

Stuck? Get a hint


Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

What kind of loop operations are available in Python?

Still have questions? View this exercise's thread in the Codecademy Forums.


3. For loops: introduction
LOOPS

For Loops: Introduction

Now that we can appreciate what loops do for us, let’s start with your first
type of loop, a for loop, a type of definite iteration.

In a for loop, we will know in advance how many times the loop will need to
iterate because we will be working on a collection with a predefined length. In
our examples, we will be using Python lists as our collection of elements.

With for loops, on each iteration, we will be able to perform an action on each


element of the collection.

Before we work with any collection, let’s examine the general structure of
a for loop:

for <temporary variable> in <collection>:


  <action>
Let’s break down each of these components:
1. A for keyword indicates the start of a for loop.
2. A <temporary variable> that is used to represent the value of the element in
the collection the loop is currently on.
3. An in keyword separates the temporary variable from the collection used
for iteration.
4. A <collection> to loop over. In our examples, we will be using a list.
5. An <action> to do anything on each iteration of the loop.

Let’s link these concepts back to our ingredients example. This for loop prints


each ingredient in ingredients:

ingredients = ["milk", "sugar", "vanilla extract", "dough", "chocolate"]

for ingredient in ingredients:


  print(ingredient)
In this example:

1. ingredient is the <temporary variable>.


2. ingredients is our <collection>.
3. print(ingredient) was the <action> performed on every iteration using the
temporary variable of ingredient.

This code outputs:

milk
sugar
vanilla extract
dough
chocolate
Some things to note about for loops:

 Temporary Variables:

A temporary variable’s name is arbitrary and does not need to be


defined beforehand. Both of the following code snippets do the exact
same thing as our above example:

for i in ingredients:
  print(i)
for item in ingredients:
print(item)
Programming best practices suggest we make our temporary variables
as descriptive as possible. Since each iteration (step) of our loop is
accessing an ingredient it makes more sense to call our temporary
variable ingredient rather than i or item.
 Indentation:

Notice that in all of these examples the print statement is indented.


Everything at the same level of indentation after the for loop declaration
is included in the loop body and is run on every iteration of the loop.

for ingredient in ingredients:


  # Any code at this level of indentation
  # will run on each iteration of the loop
  print(ingredient)
If we ever forget to indent, we’ll get an IndentationError or unexpected
behavior.
 Elegant loops:

Python loves to help us write elegant code so it allows us to write


simple for loops in one-line. In order to see the below example as one
line, you may need to expand your narrative window. Here is the
previous example in a single line:

for ingredient in ingredients: print(ingredient)


Note: One-line for loops are useful for simple programs. It is not
recommended you write one-line loops for any loop that has to perform
multiple complex actions on each iteration. Doing so will hurt the
readability of your code and may ultimately lead to buggier code.
Let’s practice writing our own for loop!

Instructions

1.

Run the code.

We should get an IndentationError because the print(game) line is not indented.


Checkpoint 2 Passed

Stuck? Get a hint

2.

Indent (2 spaces or tab) line 6 so that we don’t get an IndentationError when you


run the code.

Run the code again!


Checkpoint 3 Passed

Stuck? Get a hint

3.

Write a for loop that prints each sport in the list sport_games.


Checkpoint 4 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

Why do lines of code after a for loop have to be indented?

2.

What is the type of a temporary variable in a for loop?


Still have questions? View this exercise's thread in the Codecademy Forums.

4. For loops: using range


LOOPS

For Loops: Using Range

Often we won’t be iterating through a specific list (or any collection), but
rather only want to perform a certain action multiple times.

For example, if we wanted to print out a "Learning Loops!" message six times


using a for loop, we would follow this structure:

for <temporary variable> in <list of length 6>:


print("Learning Loops!")
Notice that we need to iterate through a list with a length of six, but we don’t
necessarily care what is inside of the list.

To create arbitrary collections of any length, we can pair our for loops with the
trusty Python built-in function range().

An example of how the range() function works, this code generates a collection


of 6 integer elements from 0 to 5:

six_steps = range(6)

# six_steps is now a collection with 6 elements:


# 0, 1, 2, 3, 4, 5
We can then use the range directly in our for loops as the collection to perform
a six-step iteration:

for temp in range(6):


  print("Learning Loops!")
Would output:

Learning Loops!
Learning Loops!
Learning Loops!
Learning Loops!
Learning Loops!
Learning Loops!
Something to note is we are not using temp anywhere inside of the loop body.
If we are curious about which loop iteration (step) we are on, we can
use temp to track it. Since our range starts at 0, we will add + 1 to our temp to
represent how many iterations (steps) our loop takes more accurately.

for temp in range(6):


  print("Loop is on iteration number " + str(temp + 1))
Would output:

Loop is on iteration number 1


Loop is on iteration number 2
Loop is on iteration number 3
Loop is on iteration number 4
Loop is on iteration number 5
Loop is on iteration number 6
Let’s try out using a range in a for loop!

Instructions

1.

Use the range() function in a for loop to print() out the provided promise variable


five times.
Checkpoint 2 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.
This exercise uses a range() function to cause the for loop to iterate a
specific number of times. Why can’t the number of times to iterate a for
loop be specified without range() ?

Still have questions? View this exercise's thread in the Codecademy Forums.

5. While loops: introduction


LOOPS
While Loops: Introduction
In Python, for loops are not the only type of loops we can use. Another type of
loop is called a while loop and is a form of indefinite iteration.

A while loop performs a set of instructions as long as a given condition is true.

The structure follows this pattern:

while <conditional statement>:


  <action>
Let’s examine this example, where we print the integers 0 through 3:

count = 0
while count <= 3:
  # Loop Body
  print(count)
  count += 1
Let’s break the loop down:

1. count is initially defined with the value of 0. The conditional statement in
the while loop is count <= 3, which is true at the initial iteration of the loop,
so the loop body executes.

Inside the loop body, count is printed and then incremented by 1.


2. When the first iteration of the loop has finished, Python returns to the
top of the loop and checks the conditional again. After the first
iteration, count would be equal to 1 so the conditional still evaluates
to True and so the loop continues.
3. This continues until the count variable becomes 4. At that point, when the
conditional is tested it will no longer be True and the loop will stop.
The output would be:

0
1
2
3
Note the following about while loops before we write our own:

 Indentation:

Notice that in our example the code under the loop declaration is
indented. Similar to a for loop, everything at the same level of
indentation after the while loop declaration is run on every iteration of
the loop while the condition is true.

while count <= 3:


  # Loop Body
  print(count)
  count += 1
  # Any other code at this level of indentation will
  # run on each iteration
If we ever forget to indent, we’ll get an IndentationError or unexpected
behavior.
 Elegant loops:

Similar to for loops, Python allows us to write elegant one-


line while loops. Here is our previous example in a single line:

count = 0
while count <= 3: print(count); count += 1
Note: Here we separate each statement with a ; to denote a separate
line of code.
Let’s practice writing a while loop!

Instructions
1.
Examine the while loop from the narrative in your code editor. There are
additional print() statements to help visualize the iterations.

Run the code to see what happens on each iteration of the loop. When you
are finished, comment out the example to make space for the rest of the
checkpoints.

To quickly comment out the code, use your cursor or mouse to highlight all
the code and press  command ⌘  +  /  on a Mac or  CTRL  +  /  on a Windows
machine.
Checkpoint 2 Passed

2.
Let’s write a while loop that counts down from 10 to 0(inclusive). Once our loop
is finished we will commemorate our accomplishment by printing "We have
liftoff!".

As we saw in the narrative, our key components will be:

1. A variable to keep track of the count, and also help our loop
eventually stop.
2. A condition that our while loop will check on each iteration.
3. Several code statements to execute on each iteration of the loop.
Let’s tackle the first component!

Create a variable named countdown and set the value to 10.


Checkpoint 3 Passed

3.
Now let’s tackle the actual while loop. Define a while loop that will run while
our countdown variable is greater than or equal to zero.

On each iteration:

1. We should print() the value of the countdown variable.


2. We should decrease the value of the countdown variable by 1

Make sure to only print the value of countdown.


If you notice the Run button spinning continuously or a “Lost connection to
Codecademy” message in an exercise, you may have an infinite loop! If the
stop condition for our loop is never met, we will create an infinite loop which
stops our program from running anything else. To exit out of an infinite loop
in an exercise, refresh the page — then fix the code for your loop.
Checkpoint 4 Passed

Stuck? Get a hint


4.
Now that we have built our loop, let’s commemorate our

6. While loops: lists


LOOPS

While Loops: Lists

A while loop isn’t only good for counting! Similar to how we saw for loops


working with lists, we can use while loops to iterate through a list as well.

Let’s return to our ingredient list:

ingredients = ["milk", "sugar", "vanilla extract", "dough", "chocolate"]


We know that while loops require some form of a variable to track the
condition of the loop to start and stop.

Take some time to think about what we would use to track whether we need
to start/stop the loop if we want to iterate through ingredients and print every
element.

Click here to find out!


We can then use this length in addition to another variable to construct
the while loop:

length = len(ingredients)
index = 0

while index < length:


  print(ingredients[index])
  index += 1
Let’s break this down:

# Length will be 5 in this case


length = len(ingredients)
Explanation

# Index starts at zero


index = 0
Explanation

while index < length:


Explanation

# The first iteration will print ingredients[0]


print(ingredients[index])
Explanation
# Increment index to access the next element in ingredients
# Each iteration gets closer to making the conditional no longer true
index += 1
Explanation

Our final output would be:

milk
sugar
vanilla extract
dough
chocolate
Let’s use a while loop to iterate through some lists!

Instructions

1.

We are going to write a while loop to iterate over the provided list python_topics.

First, we will need a variable to represent the length of the list. This will help us
know how many times our while loop needs to iterate.

Create a variable length and set its value to be the length of the list


of python_topics.
Checkpoint 2 Passed

Stuck? Get a hint

2.

Next, we will require a variable to compare to our length variable to make sure
we are able to implement a condition that eventually allows the loop to stop.

Create a variable called index and initialize the value to be 0.


Checkpoint 3 Passed
3.

Let’s now build our loop. We want our loop to iterate over the list
of python_topics and on each iteration print "I am learning about <element from
python_topics>". For this loop we will need the following components:

1. A condition for our while loop


2. A statement in the loop body to print from our condition
3. A statement in the loop body to increment our index forward.

The end result should output:

I am learning about variables


I am learning about control flow
I am learning about loops
I am learning about modules
I am learning about classes
If you notice the Run button spinning continuously or a “Lost connection to
Codecademy” message in an exercise, you may have an infinite loop! If the
stop condition for our loop is never met, we will create an infinite loop which
stops our program from running anything else. To exit out of an infinite loop
in an exercise, refresh the page — then fix the code for your loop.
Checkpoint 4 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Still have questions? View this exercise's thread in the Codecademy Forums.

7. infinite loops
LOOPS

Infinite Loops
We’ve iterated through lists that have a discrete beginning and end. However,
let’s consider this example:

my_favorite_numbers = [4, 8, 15, 16, 42]

for number in my_favorite_numbers:


  my_favorite_numbers.append(1)
Take some time to ponder what happens with this code.

Click to see what would happen!

A loop that never terminates is called an infinite loop. These are very
dangerous for our code because they will make our program run forever and
thus consume all of your computer’s resources.

A program that hits an infinite loop often becomes completely unusable. The
best course of action is to avoid writing an infinite loop.

Note: If you accidentally stumble into an infinite loop while developing on


your own machine, you can end the loop by using  control  +  c  to terminate the
program. If you’re writing code in our online editor, you’ll need to refresh the
page to get out of an infinite loop.

Let’s fix an infinite loop to see it in action.

Instructions

Suppose we have two lists of students, students_period_A and students_period_B. We


want to combine all students into students_period_B.

In your code editor, we have provided you a loop. Go ahead and uncomment
line 5 and before you run the code ponder why this code would cause an
infinite loop.

When you are ready, run this code. What do you notice happens? Over the run
button, notice the loading circle is continuing without anything happening.
This is an infinite loop! To end this program we must refresh the page. (Note:
The reason this loop is infinite is that we’re adding each student
in students_period_A to students_period_A which would create a never-ending list of all
the student names.)

Open this after you refresh the page

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

If an infinite loop is accidentally coded, will Python generate an error


message to indicate it?

2.

What can the iteration variable be named?

3.

How can I advance the exercise after the infinite loop?


Still have questions? View this exercise's thread in the Codecademy Forums.

8. loops control: break


LOOPS

Loop Control: Break

Loops in Python are very versatile. Python provides a set of control statements
that we can use to get even more control out of our loops.

Let’s take a look at a common scenario that we may encounter to see a use
case for loop control statements.

Take the following list items_on_sale as our example:

items_on_sale = ["blue shirt", "striped socks", "knit dress", "red headband", "dinosaur
onesie"]
It’s often the case that we want to search a list to check if a specific value
exists. What does our loop look like if we want to search for the value of "knit
dress" and print out "Found it" if it did exist?

It would look something like this:

for item in items_on_sale:


  if item == "knit dress":
    print("Found it")
This code goes through each item in items_on_sale and checks for a match. This is
all fine and dandy but what’s the downside?

Once "knit_dress" is found in the list items_on_sale, we don’t need to go through the


rest of the items_on_sale list. Unfortunately, our loop will keep running until we
reach the end of the list.

Since it’s only 5 elements long, iterating through the entire list is not a big
deal in this case but what if items_on_sale had 1000 items? What if it had 100,000
items? This would be a huge waste of time for our program!
Thankfully you can stop iteration from inside the loop by using break loop
control statement.

When the program hits a break statement it immediately terminates a loop. For


example:

items_on_sale = ["blue shirt", "striped socks", "knit dress", "red headband", "dinosaur
onesie"]

print("Checking the sale list!")

for item in items_on_sale:


  print(item)
  if item == "knit dress":
    break

print("End of search!")
This would produce the output:

Checking the sale list!


blue shirt
striped socks
knit dress
End of search!
When the loop entered the if statement and saw the break it immediately
ended the loop. We didn’t need to check the elements of "red
headband" or "dinosaur onesie" at all.

Now let’s break some loops!

Instructions

1.

You have a list of dog breeds you can adopt, dog_breeds_available_for_adoption.

Using a for loop, iterate through the dog_breeds_available_for_adoption list


and print() out each dog breed.

Use the <temporary variable> name of dog_breed in your loop declaration.


Checkpoint 2 Passed
Stuck? Get a hint

2.

Inside your for loop, after you print each dog breed, check if the current
element inside dog_breed is equal to dog_breed_I_want. If so, print "They have the dog I
want!"
Checkpoint 3 Passed

Stuck? Get a hint

3.

Add a break statement when your loop has found dog_breed_I_want so that the rest
of the list does not need to be checked once we have found our breed.
Checkpoint 4 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

In this exercise, a break statement is used as the last line in the for loop.
If there was any additional code in the for loop after the break, would it
execute?

2.

Why does my print statement not need to be indented?


Still have questions? View this exercise's thread in the Codecademy Forums.

9. loop control: continue


LOOPS

Loop Control: Continue

While the break control statement will come in handy, there are other situations
where we don’t want to end the loop entirely. What if we only want to skip the
current iteration of the loop?

Let’s take this list of integers as our example:

big_number_list = [1, 2, -1, 4, -5, 5, 2, -9]


What if we want to print out all of the numbers in a list, but only if they are
positive integers. We can use another common loop control statement
called continue.

for i in big_number_list:
  if i <= 0:
    continue
  print(i)
This would produce the output:

1
2
4
5
2
Notice a few things:

1. Similar to when we were using the break control statement,


our continue control statement is usually paired with some form of a
conditional (if/elif/else).
2. When our loop first encountered an element (-1) that met the conditions
of the if statement, it checked the code inside the block and saw
the continue. When the loop then encounters a continue statement it
immediately skips the current iteration and moves onto the next
element in the list (4).
3. The output of the list only printed positive integers in the list because
every time our loop entered the if statement and saw
the continue statement it simply moved to the next iteration of the list and
thus never reached the print statement.

Let’s continue learning about control statements with some exercises!

Instructions

1.

Your computer is the doorman at a bar in a country where the drinking age is
21.

Loop through the ages list. If an entry is less than 21, skip it and move to the
next entry. Otherwise, print() the age.
Checkpoint 2 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

How does the behavior of the continue statement differ from the break
statement?
Still have questions? View this exercise's thread in the Codecademy Forums.

10. nested loops


LOOPS

Nested Loops

Loops can be nested in Python, as they can with other programming


languages. We will find certain situations that require nested loops.

Suppose we are in charge of a science class, that is split into three project
teams:

project_teams = [["Ava", "Samantha", "James"], ["Lucille", "Zed"], ["Edgar",


"Gabriel"]]
Using a for or while loop can be useful here to get each team:

for team in project_teams:


  print(team)
Would output:

["Ava", "Samantha", "James"]


["Lucille", "Zed"]
["Edgar", "Gabriel"]
But what if we wanted to print each individual student? In this case we would
actually need to nest our loops to be able loop through each sub-list. Here is
what it would look like:

# Loop through each sublist


for team in project_teams:
  # Loop elements in each sublist
  for student in team:
    print(student)
This would output:

Ava
Samantha
James
Lucille
Zed
Edgar
Gabriel
Let’s practice writing a nested loop!

Instructions

1.

We have provided the list sales_data that shows the number of scoops sold for
different flavors of ice cream at three different locations: Scoopcademy,
Gilberts Creamery, and Manny’s Scoop Shop.

We want to sum up the total number of scoops sold across all three locations.
Start by defining a variable scoops_sold and set it to zero.
Checkpoint 2 Passed

2.

Loop through the sales_data list using the following guidelines:

1. For our temporary variable of the for loop, call it location.


2. print() out each location list.
Checkpoint 3 Passed

Stuck? Get a hint

3.

Within our sales_data loop, nest a secondary loop to go through


each location sublist element and add the element value to scoops_sold.

By the end, you should have the sum of every number in the sales_data nested
list.
Checkpoint 4 Passed

Stuck? Get a hint

4.

Print out the value of scoops_sold outside of the nested loop.


Checkpoint 5 Passed

Stuck? Get a hint


Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

This exercise shows the nested loop using the variable from the outer
loop. Does the nested loop always need to use the variable from the
outer loop?

2.

How does += work?

Still have questions? View this exercise's thread in the Codecademy Forums.

11. list comprehensions: introduction


LOOPS

List Comprehensions: Introduction

So far we have seen many of the ideas about using loops in our code. Python
prides itself on allowing programmers to write clean and elegant code. We
have already seen this with Python giving us the ability to
write while and for loops in a single line.
In this exercise, we are going to examine another way we can write elegant
loops in our programs using list comprehensions.

To start, let’s say we had a list of integers and wanted to create a list where
each element is doubled. We could accomplish this using a for loop and a new
list called doubled:

numbers = [2, -1, 79, 33, -45]


doubled = []

for number in numbers:


  doubled.append(number * 2)

print(doubled)
Would output:

[4, -2, 158, 66, -90]


Let’s see how we can use the power of list comprehensions to solve these
types of problems in one line. Here is our same problem but now written as a
list comprehension:

numbers = [2, -1, 79, 33, -45]


doubled = [num * 2 for num in numbers]
print(doubled)
Let’s break down our example in a more general way:

new_list = [<expression> for <element> in <collection>]


In our doubled example, our list comprehension:

1. Takes an element in the list numbers


2. Assigns that element to a variable called num (our <element>)
3. Applies the <expression> on the element stored in num and adds the result
to a new list called doubled
4. Repeats steps 1-3 for every other element in the numbers list
(our <collection>)

Our result would be the same:

[4, -2, 158, 66, -90]


Instructions

1.

We have been provided a list of grades in a physics class. Using a list


comprehension, create a new list called scaled_grades that scales the class grades
based on the highest score.

Since the highest score was a 90 we simply want to add 10 points to all the
grades in the list.
Checkpoint 2 Passed

Stuck? Get a hint

2.

Print scaled_grades.
Checkpoint 3 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

In this exercise, the variable from the list comprehension is used to


calculate a value. Is it possible to call a function using the variable?

2.

How can I practice outside Codecademy? (video)


3.

Doesn’t 9/5 need to be in parenthesis?

Still have questions? View this exercise's thread in the Codecademy Forums.

12. list comprehensions


LOOPS

List Comprehensions: Conditionals

List Comprehensions are very flexible. We even can expand our examples to
incorporate conditional logic.

Suppose we wanted to double only our negative numbers from our


previous numbers list.

We will start by using a for loop and a list only_negative_doubled:

numbers = [2, -1, 79, 33, -45]


only_negative_doubled = []

for num in numbers:


  if num < 0:
    only_negative_doubled.append(num * 2)

print(only_negative_doubled)
Would output:

[-2, -90]
Now, here is what our code would look like using a list comprehension:
numbers = [2, -1, 79, 33, -45]
negative_doubled = [num * 2 for num in numbers if num < 0]
print(negative_doubled)
Would output the same result:

[-2, -90]
In our negative_doubled example, our list comprehension:

1. Takes an element in the list numbers.


2. Assigns that element to a variable called num.
3. Checks if the condition num < 0 is met by the element stored in num. If so,
it goes to step 4, otherwise it skips it and goes to the next element in
the list.
4. Applies the expression num * 2 on the element stored in num and adds the
result to a new list called negative_doubled
5. Repeats steps 1-3 (and sometimes 4) for each remaining element in
the numbers list.

We can also use If-Else conditions directly in our comprehensions. For


example, let’s say we wanted to double every negative number but triple all
positive numbers. Here is what our code might look like:

numbers = [2, -1, 79, 33, -45]


doubled = [num * 2 if num < 0 else num * 3 for num in numbers ]
print(doubled)
Would output:

[6, -2, 237, 99, -90]


This is a bit different than our previous comprehension since the conditional if
num < 0 else num * 3 comes after the expression num * 2 but before our for keyword.

Let’s write our own list comprehensions with conditionals!

Instructions

1.

We have defined a list heights of visitors to a theme park. In order to ride the


Topsy Turvy Tumbletron roller coaster, you need to be above 161 centimeters.
Using a list comprehension, create a new list called can_ride_coaster that has every
element from heights that is greater than 161.
Checkpoint 2 Passed

Stuck? Get a hint

2.

Print can_ride_coaster.
Checkpoint 3 Passed

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

When using a list comprehension with an if , is it possible to have an


else clause?

2.

Do I need to initiate an empty list before list comprehension?

Still have questions? View this exercise's thread in the Codecademy Forums.

13. Review
LOOPS
Review

Good job! In this lesson, you learned

 How to write a for loop.


 How to use range in a loop.
 How to write a while loop.
 What infinite loops are and how to avoid them.
 How to control loops using break and continue.
 How to write elegant loops as list comprehensions.

Let’s get some more practice with these concepts!

Instructions

1.

Create a list called single_digits that consists of the numbers 0-9 (inclusive).


Checkpoint 2 Passed

Stuck? Get a hint

2.

Create a for loop that goes through single_digits and prints out each one.
Checkpoint 3 Passed

Stuck? Get a hint

3.

Before the loop, create a list called squares. Assign it to be an empty list to begin
with.
Checkpoint 4 Passed

Stuck? Get a hint

4.

Inside the loop that iterates through single_digits, append the squared value of
each element of single_digits to the list squares. You can do this before or after
printing the element.
Checkpoint 5 Passed

Stuck? Get a hint

5.
After the for loop, print out squares.
Checkpoint 6 Passed

Stuck? Get a hint

6.

Create the list cubes using a list comprehension on the single_digits list. Each


element of cubes should be an element of single_digits taken to the third power.
Checkpoint 7 Passed

Stuck? Get a hint

7.

Print cubes.

Good job!
Checkpoint 8 Passed

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

Can I have some more practice with an independent project on what I’ve
learned so far?

2.

I’ve heard “developer documentation” mentioned but what is that and


how/when/why would I use it? (video)
3.

Is it possible to have a for loop iterate over a list in reverse order without
changing the list?

Still have questions? View this exercise's thread in the Codecademy Forums.

II. loops- quiz


III. crly’s clippers
III. Carly’s clipper
LEARN PYTHON 3

Carly's Clippers

You are the Data Analyst at Carly’s Clippers, the newest hair salon on the
block. Your job is to go through the lists of data that have been collected in
the past couple of weeks. You will be calculating some important metrics that
Carly can use to plan out the operation of the business for the rest of the
month.

You have been provided with three lists:

 hairstyles:the names of the cuts offered at Carly’s Clippers.


 prices: the price of each hairstyle in the hairstyles list.
 last_week: the number of purchases for each hairstyle type in the last
week.

Each index in hairstyles corresponds to an associated index in prices and last_week.

For example, The hairstyle "bouffant" has an associated price of 30 from


the prices list, and was purchased 2 times in the last week as shown in
the last_week list. Each of these elements are in the first index of their respective
lists.

Let’s get started!

If you get stuck during this project or would like to see an experienced
developer work through it, click “Get Unstuck“ to see a project walkthrough
video.

Tasks

12/13 Complete

Mark the tasks as complete by checking them off


Prices and Cuts:
1.

Carly wants to be able to market her low prices. We want to find out what the
average price of a cut is.

First, let’s sum up all the prices of haircuts. Create a variable total_price, and set it
to 0.
Stuck? Get a hint
2.

Loop through the prices list and add each price to the variable total_price.


Stuck? Get a hint

3.

After your loop, create a variable called average_price that is the total_price divided


by the number of prices.

You can get the number of prices by using the len() function.


Stuck? Get a hint

4.

Print the value of average_price so the output looks like:

Average Haircut Price: <average_price>


Stuck? Get a hint

5.

That average price is more expensive than Carly thought it would be! She
wants to cut all prices by 5 dollars.

Use a list comprehension to make a list called new_prices, which has each


element in prices minus 5.
Stuck? Get a hint

6.

Print new_prices.
Stuck? Get a hint
Revenue:
7.

Carly really wants to make sure that Carly’s Clippers is a profitable endeavor.
She first wants to know how much revenue was brought in last week.

Create a variable called total_revenue and set it to 0.


8.
Use a for loop to create a variable i that goes from 0 to len(hairstyles)

Hint: You can use range() to do this!


Stuck? Get a hint

9.

Add the product of prices[i] (the price of the haircut at position i)


and last_week[i] (the number of people who got the haircut at position i)
to total_revenue at each step.
Stuck? Get a hint

10.

After your loop, print the value of total_revenue, so the output looks like:

Total Revenue: <total_revenue>


11.

Find the average daily revenue by dividing total_revenue by 7. Call this


number average_daily_revenue and print it out.
12.

Carly thinks she can bring in more customers by advertising all of the haircuts
she has that are under 30 dollars.

Use a list comprehension to create a list called cuts_under_30 that has the


entry hairstyles[i] for each i for which new_prices[i] is less than 30.

You can use range() in your list comprehension to make i go


from 0 to len(new_prices) - 1.
Stuck? Get a hint

13.

Print cuts_under_30
V. Functions
A. Introduction to functions
1/13.
INTRODUCTION TO FUNCTIONS

Introduction to Functions

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:

1. Establish your origin and destination


2. Calculate the distance/route
3. Return the best route to the user
We will perform these three steps every time users have to travel between two
points using our trip application. In our programs, we could rewrite the same
procedures over and over (and over) for each time we want to travel, but
there’s a better way! Python gives us a useful concept called functions.

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!

At the end of this lesson, you’ll know how to:

 Write a function and return values from it.


 Allow functions to take custom input.
 Experiment with how functions access our other python code.

And much more!

Instructions
Review the visual for the function navigation_steps().

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.

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Still have questions? View this exercise's thread in the Codecademy Forums.

2/13
INTRODUCTION TO 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:

1. Establish an origin and destination


2. Calculate the distance/route
3. Return the best route
If we were to convert our steps into Python code, a very simple version that
plans a trip between two popular New York tourist destinations might look
like this:

print("Setting the Empire State Building as the starting point and Times 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.")


Anytime we want to go between these two points we would need to run these
three print statements (for now we can assume the best route and time will
stay the same).

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!

For now, let’s gain an appreciation for functions.

Instructions

1.

Run the pre-written print() statements to see what they output.


Checkpoint 2 Passed

2.

Write the same set of print statements three more times. Run the code again
and see the output.
Checkpoint 3 Passed

Stuck? Get a hint

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.


Checkpoint 4 Passed

Concept Review
Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Still have questions? View this exercise's thread in the Codecademy Forums.

3/13
INTRODUCTION TO FUNCTIONS

Defining a Function

A function consists of many parts, so let’s first get familiar with its core - a
function definition.

Here’s an example of a function definition:

def function_name():
  # functions tasks go here
There are some key components we want to note here:

 The def keyword indicates the beginning of a function (also known as a


function header). The function header is followed by a name in
snake_case format that describes the task the function performs. It’s
best practice to give your functions a descriptive yet concise name.
 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.
 A colon : to mark the end of the function header.
 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 travel.py, we’ll write a function that prints the directions via subway from the
Empire State Building to Times Square.

First, define a function, directions_to_timesSq(). Leave the body of the function


empty for now.

Note: When we run the code, we will see an error: SyntaxError: unexpected EOF while
parsing. This will occur when we don’t populate a function with any statements.
We will populate it with code in the next step.

EOF stands for “End of File” — Python is telling you that it was expecting some
code in the body of the function, but it hit the end of the file first.
Checkpoint 2 Passed

Stuck? Get a hint

2.

Within the body of the function, use three print() statements to output the
following directions:
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
Remember, if you run your code, you shouldn’t see any output in the terminal
at this point. Check out the hint if you want to see how to see the output (we
will be doing it in the next section as well!)
Checkpoint 3 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Still have questions? View this exercise's thread in the Codecademy Forums.

4/13
INTRODUCTION TO FUNCTIONS

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 ( ).

Let’s revisit our directions_to_timesSq() function :

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:

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.
Note that you can only call a function after it has been defined in your code.

Now it’s your turn to call a function!

Instructions

1.

Call the directions_to_timesSq() function.

Click Run to see it execute and print out.


Checkpoint 2 Passed

Stuck? Get a hint

2.

Add an additional print statement to our directions_to_timesSq() function.

Have the statement print "Take lots of pictures!"

Run your code again and see how your output changes.


Checkpoint 3 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums
Still have questions? View this exercise's thread in the Codecademy Forums.

5/13
INTRODUCTION TO FUNCTIONS

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.

If we wanted to write another statement outside of trip_welcome(), we would


have to unindent the new line:

def trip_welcome():
  # Indented code is part of the function body
  print("Welcome to Tripcademy!")
  print("Let's get you to your destination.")

# Unindented code below is not part of the function body


print("Woah, look at the weather outside! Don't walk, take the train!")

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.

We would see the following output from this program:


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.

Let’s play around with indentation and the flow of execution!

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:

Looks great outside! Enjoy your trip.


Note: Don’t call your function just yet! We will do that in the next step.
Checkpoint 3 Passed

Stuck? Get a hint

3.
Oh no! It looks like some clouds came in and it started raining. Our users
shouldn’t go on a trip in the rain. In our weather_check() function add a
second print() statement under the first one which prints a warning message for
our travelers! It should print:

False Alarm, the weather changed! There is a thunderstorm approaching. Cancel your
plans and stay inside.
Checkpoint 4 Passed

Stuck? Get a hint

4.

Call the function weather_check().


Checkpoint 5 Passed

Stuck? Get a hint

5.

Unindent your final print statement in your weather_check() function. Run the


program again.

What is different?
Checkpoint 6 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Still have questions? View this exercise's thread in the Codecademy Forums.

6/13
INTRODUCTION TO FUNCTIONS

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 ( ).

Here is a function that defines a single parameter:

def my_function(single_parameter)
  # some code
In the context of our trip_welcome() function, it would look 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!

Create a function called generate_trip_instructions() that defines one parameter


called location.

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.
Checkpoint 2 Passed

Stuck? Get a hint

2.

generate_trip_instructions() should print out the following:


Looks like you are planning a trip to visit <location>
Where <location> will represent the location parameter.
Checkpoint 3 Passed

Stuck? Get a hint

3.

generate_trip_instructions() should also let our users know they can reach their
location using public transit.

Let’s have generate_trip_instructions()also print out the following on a new line:

You can use the public subway system to get to <location>


Where <location> will represent the location parameter.
Checkpoint 4 Passed

Stuck? Get a hint

4.

Time for some greenery! Let’s see what happens when we call the function
and input the argument "Central Park", a backyard wonder in the heart of New
York City.
Checkpoint 5 Passed

Stuck? Get a hint

5.

The day trip is over and we need to get back to the train station to head
home. Change the argument to "Grand Central Station" and call the function again.

What changed in the output?


Checkpoint 6 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Still have questions? View this exercise's thread in the Codecademy Forums.


7/13
INTRODUCTION TO FUNCTIONS

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:

def my_function(parameter1, parameter2, parameter3):


  # Some code
When we call our function, we will need to provide arguments for each of the
parameters we assigned in our function definition.

# Calling my_function
my_function(argument1, argument2)
For example take our trip application’s trip_welcome() function that has two
parameters:

def trip_welcome(origin, destination):


  print("Welcome to Tripcademy")
  print("Looks like you are traveling from " + origin)
  print("And you are heading to " + destination)
Our two parameters in this function are origin and destination. In order to properly
call our function, we need to pass argument values for both of them.

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!).

Our function call could look like:

trip_welcome("Prospect Park", "Atlantic Terminal")


In this call, the argument value of "Prospect Park" is assigned to be
the origin parameter, and the argument value of"Atlantic Terminal" is assigned to
the destination parameter.

The output would be:

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):

1. plane_ticket_price
2. car_rental_rate
3. hotel_rate
4. 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.
Checkpoint 2 Passed

Stuck? Get a hint

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.
Create new variable called car_rental_total that is the product
of car_rental_rate and trip_time.
Checkpoint 3 Passed

Stuck? Get a hint

3.

Next, we want to apply the same logic but for our hotel_rate.

Create new variable called hotel_total that is the product of hotel_rate and trip_time.

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! 💵
Checkpoint 4 Passed

Stuck? Get a hint

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.
Checkpoint 5 Passed

Stuck? Get a hint

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
Checkpoint 6 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums
Still have questions? View this exercise's thread in the Codecademy Forums.

8/13
INTRODUCTION TO FUNCTIONS

Types of Arguments

In Python, there are 3 different types of arguments we can give a function.

 Positional arguments: arguments that can be called by their position in


the function definition.
 Keyword arguments: arguments that can be called by their name.
 Default arguments: arguments that are given default values.
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 🚕.

def calculate_taxi_price(miles_to_travel, rate, discount):


  print(miles_to_travel * rate - discount )
In this function, miles_to_travel is positioned as the first parameter, rate is
positioned as the second parameter, and discount is the third. When we call our
function, the position of the arguments will be mapped to the positions
defined in the function declaration.

# 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.

calculate_taxi_price(rate=0.5, discount=10, miles_to_travel=100)


Lastly, sometimes we want to give our function arguments default values. We
can provide a default value to an argument by using the assignment operator
(=). This will happen in the function declaration rather than the function call.

Here is an example where the discount argument in


our calculate_taxi_price function will always have a default value of 10:

def calculate_taxi_price(miles_to_travel, rate, discount = 10):


  print(miles_to_travel * rate - discount )
When using a default argument, we can either choose to call the function
without providing a value for a discount (and thus our function will use the
default value assigned) or overwrite the default argument by providing our
own:

# Using the default value of 10 for discount.


calculate_taxi_price(10, 0.5)

# Overwriting the default value of 10 with 20


calculate_taxi_price(10, 0.5, 20)
Let’s practice using these different types of arguments!

Instructions

1.

Tripcademy (our trusty travel app) needs to allow passengers to plan a trip
(duh).

Write a function called trip_planner() that will have three


parameters: first_destination, second_destination and final_destination.

Give the final_destination parameter a default value of "Codecademy HQ".

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.
Checkpoint 2 Passed

Stuck? Get a hint

2.
First, we want to introduce the trip to users. Use print() in our function to
output Here is what your trip will look like!.
Checkpoint 3 Passed

Stuck? Get a hint

3.

In our function definition let’s provide an itinerary that will describe the
destinations our user will visit in order. Print a statement that follows this form:

First, we will stop in <first_destination>, then <second_destination>, and lastly


<final_destination>
An example call to our function using positional arguments:

trip_planner("London", "India", "New Zealand")


Should output:

Here is what your trip will look like!


First, we will stop in London, then India, and lastly New Zealand
To test out your function, call trip_planner() with the following values for the
parameters:

 first_destination: "France"
 second_destination: "Germany"
Checkpoint 4 Passed
 final_destination: "Denmark"

Stuck? Get a hint

4.

Call the function trip_planner() again with the following values for the parameters:

first_destination: "Denmark"

 second_destination: "France"
 final_destination: "Germany"
Note the difference in your output depending on the position of your
arguments.
Checkpoint 5 Passed

Stuck? Get a hint

5.
Call the function trip_planner() again using keyword arguments in this exact
order:

1. first_destination: "Iceland"
2. final_destination: "Germany"
Checkpoint 6 Passed
3. second_destination: "India"

Stuck? Get a hint

6.

Lastly, go ahead and call the function trip_planner() using only two positional


arguments to see the default argument in action:

1. first_destination: "Brooklyn"
Checkpoint 7 Passed
2. second_destination: "Queens"

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Still have questions? View this exercise's thread in the Codecademy Forums.

9/13
INTRODUCTION TO FUNCTIONS

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"

# Built-in function: len()


length_of_destination = len(destination_name)

# Built-in function: print()


print(length_of_destination)
Would output the value of length_of_destination:

28
Here we are using a total of two built-in functions in our example: print(),
and len().

And yes, if you’re wondering, that is a real railway station in India!

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
    https://docs.python.org/3.8/library/string

    The following documentation is automatically generated from the Python


    source files.  It may be incomplete, incorrect or include features that
    are considered implementation detail and may vary between Python
    implementations.  When in doubt, consult the module reference at the
    location listed above.
.....
Check out all the latest built-in functions in the official Python docs.

Let’s practice using a few of them. You will need to rely on the provided
Python documentation links to find your answers!

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.
Checkpoint 2 Passed

Stuck? Get a hint

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.
Checkpoint 3 Passed

Stuck? Get a hint

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.


Checkpoint 4 Passed
Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Still have questions? View this exercise's thread in the Codecademy Forums.

10/13
INTRODUCTION TO FUNCTIONS

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().

Take a look at another example:

budget = 1000

# Here we are using a default value for our parameter of `destination`


def trip_welcome(destination="California"):
    print(" Looks like you're going to " + destination)
    print(" Your budget for this trip is " + str(budget))

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.
Checkpoint 2 Passed

Stuck? Get a hint

2.

Looking at the error, it seems like the main issue is that favorite_locations is not
defined. Why would our program not be able to see our
beautiful favorite_locations variable?

Aha! It must be a scope issue. Fix the scope of favorite_locations so that both our
functions can access it.

Traceback (most recent call last):


File "travel.py", line 11, in <module>
show_favorite_locations()
File "travel.py", line 8, in show_favorite_locations
print("Your favorite locations are: " + favorite_locations)
NameError: name 'favorite_locations' is not defined
Checkpoint 3 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Still have questions? View this exercise's thread in the Codecademy Forums.

11/13
INTRODUCTION TO FUNCTIONS

Returns

At this point, our functions have been using print() to help us visualize the
output in our interpreter. Functions can also return a value to the program so
that this value can be modified or used later. We use the Python
keyword return to do this.

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.

def calculate_exchange_usd(us_dollars, exchange_rate):


  return us_dollars * exchange_rate

new_zealand_exchange = calculate_exchange_usd(100, 1.4)

print("100 dollars in US currency would give you " + str(new_zealand_exchange) + "


New Zealand dollars")
This would output:

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.

When there is a result from a function that is stored in a variable, it is called


a returned function value.

Let’s try to return some data in the exercises!

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.

We have provided some starting code to get started. Take a second to


understand the code and then click Run and take a look at the output.
Checkpoint 2 Passed
2.

Let’s create a new function called deduct_expense() that will take two parameters.

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.
Checkpoint 3 Passed

Stuck? Get a hint

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.
Checkpoint 4 Passed

Stuck? Get a hint

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().

Pass our current_budget variable as the first argument and the shirt_expense variable


as the second argument.
Checkpoint 5 Passed

Stuck? Get a hint

5.

Lastly, we want our users to see the remaining budget.

Call the provided print_remaining_budget() function, passing in new_budget_after_shirt as


the only argument.
Checkpoint 6 Passed

Stuck? Get a hint


6.

Great Job! This is the biggest program with functions we have built so far!
Take a second to review your code and click Run one last time when you are
ready to move on.
Checkpoint 7 Passed

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Still have questions? View this exercise's thread in the Codecademy Forums.

12/13
INTRODUCTION TO FUNCTIONS

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):

weather_data = ['Sunny', 'Sunny', 'Cloudy', 'Raining', 'Snowing']

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:
monday, tuesday, wednesday = threeday_weather_report(weather_data)

print(monday)
print(tuesday)
print(wednesday)
This will print:

Tomorrow the weather will be Sunny


The following day it will be Sunny
Two days from now it will be Cloudy
Let’s practice using multiple returns by returning to our previous code example.

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.
Checkpoint 2 Passed

2.

We want to be able to return the three most popular destinations from our


function top_tourist_locations_italy().

Add a line in the function top_tourist_locations_italy() that will return the values


of first, second, third in that exact order.
Checkpoint 3 Passed

Stuck? Get a hint

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.
Set the return of the function top_tourist_locations_italy() to be equal to three new
variables called most_popular1, most_popular2, and most_popular3 in that exact order.
Checkpoint 4 Passed

Stuck? Get a hint

4.

Use three print() statements to output the value of most_popular1, most_popular2,


and most_popular3.
Checkpoint 5 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Still have questions? View this exercise's thread in the Codecademy Forums.

13/13
INTRODUCTION TO FUNCTIONS

Review

Excellent work! 👏 In this lesson, you’ve covered a major fundamental


programming concept used in the majority of all programs to organize code
into reusable blocks. To recap, we explored:

 What problems arise in our programs without functions


 What functions are and how to write them
 How whitespace plays an important role in how a program will execute
our code and more importantly distinguish function code from non-
function code
 How to pass input values into our functions using parameters and
arguments
 The difference between built-in and user-defined functions and some
common built-in functions python offers
 How we can reuse function output with the return keyword, as well as
multiple returns.
 Where variables can be accessed in our programs that use functions

Let’s practice putting all these concepts together!

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.

Create a function called trip_planner_welcome() that takes one parameter


called name. The function should use print() to output a message like this:

Welcome to tripplanner v1.0 <Name Here>


Where <Name Here> represents the parameter variable of name we defined.

Call trip_planner_welcome(), passing your name as an argument.


Checkpoint 2 Passed

Stuck? Get a hint

2.

Next, we are going to define a function called estimated_time_rounded() that will


allow us to calculate a rounded time value based on a decimal for our user’s
trip.

An example call for this function will look like this:

estimated_time_rounded(2.5)
Where 2 represents 2 hours and .5 represents 30 minutes.
Define the function estimated_time_rounded() with a single parameter estimated_time.
The function should do two things:

1. Create a variable called rounded_time that is the result of calling


the round() built-in function on the parameter estimated_time.
2. Return rounded_time.

After the function definition, call estimated_time_rounded() with a decimal argument


and save the result to a variable called estimate. Since this amount represents a
time, be sure to use a positive number.
Checkpoint 3 Passed

Stuck? Get a hint

3.

Next, we are going to generate messages for a user’s planned trip.

Create a function called destination_setup() that will have four parameters in this


exact order:

1. origin
2. destination
3. estimated_time
4. 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.
Checkpoint 4 Passed

Stuck? Get a hint

4.

Next, we are going to write four print() statements in our function. The output


on this function call should look like this:

Your trip starts off in <origin>


And you are traveling to <destination>
You will be traveling by <mode_of_transport>
It will take approximately <estimated_time> hours
Each of these print() statements use a different parameter from our
function destination_setup().

Note: The estimated_time parameter will come in the form of an integer. Make


sure to use str() to convert the parameter in your print statement.

After the function definition, call destination_setup() with the following arguments:

 origin and destination should be string values representing the places you


will travel from and to
 Use the estimate you created earlier for estimated_time
 If you will be traveling by a mode other than Car, be sure to overwrite
the default value of mode_of_transport
Checkpoint 5 Passed

Stuck? Get a hint

5.

Great job! 👏

We have successfully finished our first version of the trip builder application.
Go ahead and try passing different values into your functions!
Checkpoint 6 Passed

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Still have questions? View this exercise's thread in the Codecademy Forums.

B. Introductions to functions
Quiz:
C. Getting ready for physics class
LEARN PYTHON 3

Getting Ready for Physics Class

You are a physics teacher preparing for the upcoming semester. You want to
provide your students with some functions that will help them calculate some
fundamental physical properties.

If you get stuck during this project or would like to see an experienced
developer work through it, click “Get Unstuck“ to see a project walkthrough
video.

Tasks

13/13 Complete
Mark the tasks as complete by checking them off
Turn up the Temperature
1.

Write a function called f_to_c that takes an input f_temp, a temperature in


Fahrenheit, and converts it to c_temp, that temperature in Celsius.

It should then return c_temp.

The equation you should use is:

Temp (C) = (Temp (F) - 32) * 5/9


Stuck? Get a hint

2.

Let’s test your function with a value of 100 Fahrenheit.

Define a variable f100_in_celsius and set it equal to the value of f_to_c with 100 as


an input.
Stuck? Get a hint

3.

Write a function called c_to_f that takes an input c_temp, a temperature in


Celsius, and converts it to f_temp, that temperature in Fahrenheit.

It should then return f_temp.

The equation you should use is:

Temp (F) = Temp (C) * (9/5) + 32


4.

Let’s test your function with a value of 0 Celsius.

Define a variable c0_in_fahrenheit and set it equal to the value of c_to_f with 0 as an


input.
Stuck? Get a hint
Use the Force
5.

Define a function called get_force that takes in mass and acceleration. It should


return mass multiplied by acceleration.
6.

Test get_force by calling it with the variables train_mass and train_acceleration.

Save the result to a variable called train_force and print it out.


Stuck? Get a hint

7.

Print the string “The GE train supplies X Newtons of force.”, with X replaced


by train_force.
8.

Define a function called get_energy that takes in mass and c.

c is
a constant that is usually set to the speed of light, which is roughly 3 x
10^8. Set c to have a default value of 3*10**8.

get_energy should return mass multiplied by c squared.


9.

Test get_energy by using it on bomb_mass, with the default value of c. Save the
result to a variable called bomb_energy.
Stuck? Get a hint

10.

Print the string “A 1kg bomb supplies X Joules.”, with X replaced by bomb_energy.


Do the Work
11.

Define a final function called get_work that takes in mass, acceleration, and distance.

Work is defined as force multiplied by distance. First, get


the force using get_force, then multiply that by distance. Return the result.
Stuck? Get a hint
12.

Test get_work by using it on train_mass, train_acceleration, and train_distance. Save the


result to a variable called train_work.
13.

Print the string "The GE train does X Joules of work over Y meters.", with X replaced
with train_work and Y replaced with train_distance.

D. Off-Platform Project: Reggie’s linear regressi


Off-Platform Project: Reggie's Linear Regression
In this project, you’ll combine your knowledge of lists, loops, and syntax to
help a mad scientist perform some calculations on his data.

Complete this project on your own computer. To do this, you’ll need to install
Python. Follow the directions below, if you’re interested.

Working on Your Computer

1. If you’ve never used the command line, we recommend taking the Learn


the Command Line course.

2. Install Python by following the directions in this article on Installing


Python.

3. Learn about Jupyter Notebooks, a cool way of combining Python code


with explanations or instruction in a web terminal.

4. Download the Linear Regression project. Unzip it by double-clicking on


it. In the terminal, navigate to the directory containing the project, and
type:
jupyter notebook
This should open a browser tab.
5. Click on Reggie_Linear_Regression_Skeleton.ipynb in the browser tab.
This will open up your Jupyter Notebook.

6. Follow the steps in the Jupyter Notebook. If you get stuck, you can look
at Reggie_Linear_Regression_Solution.ipynb for the answer.

VI. Python: Code Challenges (optional)


A. Python Code Challenges: Control flow
Python Code Challenges: Control Flow

Python Code Challenges involving Control Flow

This article will help you review Python functions by providing some code
challenges about control flow.

Some of these challenges are difficult! Take some time to think about them
before starting to code.

You might not get the solution correct on your first try — look at your output,
try to find where you’re going wrong, and iterate on your solution.

Finally, if you get stuck, use our solution code! If you “Check Answer” twice
with an incorrect solution, you should see an option to get our solution code.
However, truly investigate that solution — experiment and play with the
solution code until you have a good grasp of how it is working. Good luck!

Function Syntax

As a refresher, function syntax looks like this:

def some_function(some_input1, some_input2):


  # … do something with the inputs …
  return output

For example, a function that returns the sum of the first and last elements of a given list
might look like this:
def first_plus_last(lst):
  return lst[0] + lst[-1]
And this would produce output like:

>>> first_plus_last([1, 2, 3, 4])


5
>>> first_plus_last([8, 2, 5, -8])
0
>>> first_plus_last([-10, 2, 3, -4])
-14

Challenges

We’ve included 5 challenges below. Try to answer all of them and polish up your
problem-solving skills and your control flow expertise.

1. Large Power

For the first code challenge, we are going to create a method that tests whether the
result of taking the power of one number to another number provides an answer which
is greater than 5000. We will use a conditional statement to return True if the result is
greater than 5000 or return False if it is not. In order to accomplish this, we will need the
following steps:
1. Define the function to accept two input parameters called base and exponent
2. Calculate the result of base to the power of exponent
3. Use an if statement to test if the result is greater than 5000. If it is then
return True. Otherwise, return False

Coding question
Create a function named large_power() that takes two parameters named base and exponent.
If base raised to the exponent is greater than 5000, return True, otherwise return False
Hint
# Write your large_power function here:

def large_power(base, exponent):

  if base **exponent > 5000:

    return True

  else:
    return False

  

# Uncomment these function calls to test 

your large_power function:

print(large_power(2, 13))

# should print True

print(large_power(2, 12))

# should print False

This is how we solved it:

def large_power(base, exponent):


  if base ** exponent > 5000:
    return True
  else:
    return False
In this solution, we have an example of how the operation can be performed in the
condition of the if statement. This prevents us from needing to create an extra variable.
If the condition is true, then the indented code is executed which returns True, otherwise
the indented code in the else statement is executed.

2. Over Budget

Let’s say we are trying to save some money and we are watching our budget. We need
to make sure that the result of our spending is less than the total amount we have
allocated for each of the categories. Our function will accept a parameter
called budget which describes our spending limit. The next four parameters describe what
we are spending our money on. We need to sum all of our spendings and compare it to
the budget. If we have gone over budget, we will return True. Otherwise we return False.
Here are the steps we need:

1. Define the function to accept five parameters starting


with budget then food_bill, electricity_bill, internet_bill, and rent
2. Calculate the sum of the last four parameters
3. Use if and else statements to test if the budget is less than the sum of the
calculated sum from the previous step.
4. If the condition is true, return True otherwise return False
Coding question
Create Create a function called over_budget that has five parameters
named budget, food_bill, electricity_bill, internet_bill, and rent.
The function should return True if budget is less than the sum of the other four
parameters — you’ve gone over budget! Return False otherwise.
Make sure you are calculating the sum of the last four parameters! It will look
something like this: food_bill + electricity_bill + internet_bill + rent. If budget is less than the
result of the sum then return True, else return False

Hint
# Write your over_budget function he
def over_budget(budget, food_bill, 
electricity_bill, internet_bill, rent):
  if(budget < food_bill + 
electricity_bill + internet_bill + rent):
    return True
  else:
    return False
# Uncomment these function calls to test 
your over_budget function:
print(over_budget(100, 20, 30, 10, 40))
# should print False
print(over_budget(80, 20, 30, 10, 30))
# should print True

This is one way to solve it:

def over_budget(budget, food_bill, electricity_bill, internet_bill, rent):


  if (budget < food_bill + electricity_bill + internet_bill + rent):
    return True
  else:
    return False
Similarly to the last problem, we can perform the operations within the condition of
the if statement to prevent us from creating an extra variable. We calculate the sum and
compare it to budget at the same time and return True if the condition is met, otherwise
we return False.

3. Twice As Large
In this challenge, we will determine if one number is twice as large as another number.
To do this, we will compare the first number with two times the second number. Here
are the steps:

1. Define our function with two inputs num1 and num2

2. Multiply the second input by 2

3. Use an if statement to compare the result of the last calculation with the first
input
4. If num1 is greater then return True otherwise return False
Create a function named twice_as_large() that has two parameters
named num1 and num2.
Return True if num1 is more than double num2. Return False otherwise.
# Write your twice_as_large function here:
def twice_as_large(num1, num2):
  if(num1 > num2*2):
    return True
  else:
    return False
# Uncomment these function calls to test your twice_as_large function:
print(twice_as_large(10, 5))
# should print False
print(twice_as_large(11, 5))
# should print True

Here is this solution:

def twice_as_large(num1, num2):


  if num1 > 2 * num2:
    return True
  else:
    return False
In this function, we also performed the operation within the condition of
the if statement. The second input is multiplied by 2 and then compared to the first
input on the same line.

4. Divisible By Ten
To make things a bit more challenging, we are going to create a function that
determines whether or not a number is divisible by ten. A number is divisible by ten if
the remainder of the number divided by 10 is 0. Using this, we can complete this
function in a few steps:

1. Define the function header to accept one input num

2. Calculate the remainder of the input divided by 10 (use modulus)

3. Use an if statement to check if the remainder was 0. If the remainder was 0,


return True, otherwise, return False
Create a function called divisible_by_ten() that has one parameter named num.
The function should return True if num is divisible by 10, and False otherwise.
Consider using modulo operator % to check for divisibility.
# Write your divisible_by_ten() function here:
def divisible_by_ten(num):
  if(num%10==0):
    return True
  else:
    return False

# Uncomment these print() function calls to test your divisible_by_ten() functio
n:

print(divisible_by_ten(20))
# should print True
print(divisible_by_ten(25))
# should print False
Here’s one solution:

def divisible_by_ten(num):
  if (num % 10 == 0):
    return True
  else:
    return False
In this solution, we perform the modulus operation within the condition of the if
statement. We test if the result is equal to 0 and if it is, then we return True otherwise we
return False.
5. Not Sum To Ten

Finally, we are going to check if the summation of two inputs does not equal ten. Our
function will accept two inputs and add them together. If the two numbers added
together are not equal to ten, then we will return True, otherwise, we will return False.
Here is what we need to do:
1. Define the function to accept two parameters, num1 and num2

2. Add the two parameters together

3. Test if the result is not equal to 10

4. If the sum is not equal, return True, otherwise, return False

Create a function named not_sum_to_ten() that has two parameters


named num1 and num2.
Return True if num1 and num2 do not sum to 10. Return False otherwise.
# Write your not_sum_to_ten function here:
def not_sum_to_ten(num1,num2):
    if(num1+num2== 10):
      return False
    else:
      return True
# Uncomment these function calls to test your not_sum_to_ten function:
print(not_sum_to_ten(9, -1))
# should print True
print(not_sum_to_ten(9, 1))
# should print False
print(not_sum_to_ten(5,5))
# should print False
Here is how we solved this one:

def not_sum_to_ten(num1, num2):


  if (num1 + num2 != 10):
    return True
  else:
    return False
We begin by adding our parameters within the condition of the if statement. Next, we
use != to compare the sum to 10. If they are not equal then our function returns True,
otherwise it returns False.

B. Python Code Challenges: Control flow (advanced)


Python Code Challenges: Control Flow

Python Code Challenges involving Control Flow

This article will help you review Python functions by providing some code
challenges about control flow.

Some of these challenges are difficult! Take some time to think about them
before starting to code.

You might not get the solution correct on your first try — look at your output,
try to find where you’re going wrong, and iterate on your solution.

Finally, if you get stuck, use our solution code! If you “Check Answer” twice
with an incorrect solution, you should see an option to get our solution code.
However, truly investigate that solution — experiment and play with the
solution code until you have a good grasp of how it is working. Good luck!

Function Syntax

As a refresher, function syntax looks like this:


def some_function(some_input1, some_input2):
  # … do something with the inputs …
  return output
For example, a function that returns the sum of the first and last elements of a
given list might look like this:
def first_plus_last(lst):
  return lst[0] + lst[-1]
And this would produce output like:
>>> first_plus_last([1, 2, 3, 4])
5
>>> first_plus_last([8, 2, 5, -8])
0
>>> first_plus_last([-10, 2, 3, -4])
-14

Challenges

We’ve included 5 challenges below. Try to answer all of them and polish up
your problem-solving skills and your control flow expertise.

1. Large Power

For the first code challenge, we are going to create a method that tests
whether the result of taking the power of one number to another number
provides an answer which is greater than 5000. We will use a conditional
statement to return True if the result is greater than 5000 or return False if it is
not. In order to accomplish this, we will need the following steps:
1. Define the function to accept two input parameters
called base and exponent
2. Calculate the result of base to the power of exponent
3. Use an if statement to test if the result is greater than 5000. If it is then
return True. Otherwise, return False
Coding question

Create a function named large_power() that takes two parameters


named base and exponent.
If base raised to the exponent is greater than 5000, return True, otherwise return False
Hint

# Write your large_power function here:

def large_power(base, exponent):

  if base **exponent > 5000:

    return True

  else:

    return False

  
# Uncomment these function calls to test 

your large_power function:

print(large_power(2, 13))

# should print True

print(large_power(2, 12))

# should print False

This is how we solved it:


def large_power(base, exponent):
  if base ** exponent > 5000:
    return True
  else:
    return False
In this solution, we have an example of how the operation can be performed
in the condition of the if statement. This prevents us from needing to create an
extra variable. If the condition is true, then the indented code is executed
which returns True, otherwise the indented code in the else statement is
executed.

2. Over Budget

Let’s say we are trying to save some money and we are watching our budget.
We need to make sure that the result of our spending is less than the total
amount we have allocated for each of the categories. Our function will accept
a parameter called budget which describes our spending limit. The next four
parameters describe what we are spending our money on. We need to sum all
of our spendings and compare it to the budget. If we have gone over budget,
we will return True. Otherwise we return False. Here are the steps we need:
1. Define the function to accept five parameters starting
with budget then food_bill, electricity_bill, internet_bill, and rent

2. Calculate the sum of the last four parameters

3. Use if and else statements to test if the budget is less than the sum of the


calculated sum from the previous step.
4. If the condition is true, return True otherwise return False
Coding question

Create a function called over_budget that has five parameters


named budget, food_bill, electricity_bill, internet_bill, and rent.
The function should return True if budget is less than the sum of the other four
parameters — you’ve gone over budget! Return False otherwise.
Hint

# Write your over_budget function he

def over_budget(budget, food_bill, 

electricity_bill, internet_bill, rent):

  if(budget < food_bill + 

electricity_bill + internet_bill + rent):

    return True

  else:

    return False

# Uncomment these function calls to test 

your over_budget function:

print(over_budget(100, 20, 30, 10, 40))

# should print False

print(over_budget(80, 20, 30, 10, 30))

# should print True

This is one way to solve it:


def over_budget(budget, food_bill, electricity_bill, internet_bill, rent):
  if (budget < food_bill + electricity_bill + internet_bill + rent):
    return True
  else:
    return False
Similarly to the last problem, we can perform the operations within the
condition of the if statement to prevent us from creating an extra variable. We
calculate the sum and compare it to budget at the same time and return True if
the condition is met, otherwise we return False.

3. Twice As Large

In this challenge, we will determine if one number is twice as large as another


number. To do this, we will compare the first number with two times the
second number. Here are the steps:

1. Define our function with two inputs num1 and num2

2. Multiply the second input by 2

3. Use an if statement to compare the result of the last calculation with the
first input
4. If num1 is greater then return True otherwise return False
Coding question

Create a function named twice_as_large() that has two parameters


named num1 and num2.
Return True if num1 is more than double num2. Return False otherwise.
Hint

# Write your twice_as_large function here:

def twice_as_large(num1, num2):

  if(num1 > num2*2):

    return True

  else:

    return False

# Uncomment these function calls to test 

your twice_as_large function:

print(twice_as_large(10, 5))

# should print False
print(twice_as_large(11, 5))

# should print True

Here is this solution:


def twice_as_large(num1, num2):
  if num1 > 2 * num2:
    return True
  else:
    return False
In this function, we also performed the operation within the condition of
the if statement. The second input is multiplied by 2 and then compared to the
first input on the same line.

4. Divisible By Ten

To make things a bit more challenging, we are going to create a function that
determines whether or not a number is divisible by ten. A number is divisible
by ten if the remainder of the number divided by 10 is 0. Using this, we can
complete this function in a few steps:

1. Define the function header to accept one input num

2. Calculate the remainder of the input divided by 10 (use modulus)

3. Use an if statement to check if the remainder was 0. If the remainder was


0, return True, otherwise, return False
Coding question

Create a function called divisible_by_ten() that has one parameter named num.


The function should return True if num is divisible by 10, and False otherwise.
Consider using modulo operator % to check for divisibility.
Hint

# Write your divisible_by_ten() function 

here:

def divisible_by_ten(num):

  if(num%10==0):
    return True

  else:

    return False

# Uncomment these print() function calls 

to test your divisible_by_ten() function:

print(divisible_by_ten(20))

# should print True

print(divisible_by_ten(25))

# should print False

Run your code to check your answer

Here’s one solution:


def divisible_by_ten(num):
  if (num % 10 == 0):
    return True
  else:
    return False
In this solution, we perform the modulus operation within the condition of the
if statement. We test if the result is equal to 0 and if it is, then we
return True otherwise we return False.

5. Not Sum To Ten

Finally, we are going to check if the summation of two inputs does not equal
ten. Our function will accept two inputs and add them together. If the two
numbers added together are not equal to ten, then we will return True,
otherwise, we will return False. Here is what we need to do:
1. Define the function to accept two parameters, num1 and num2
2. Add the two parameters together

3. Test if the result is not equal to 10

4. If the sum is not equal, return True, otherwise, return False


Coding question

Create a function named not_sum_to_ten() that has two parameters


named num1 and num2.
Return True if num1 and num2 do not sum to 10. Return False otherwise.
Hint

# Write your not_sum_to_ten function here:

def not_sum_to_ten(num1,num2):

    if(num1+num2== 10):

      return False

    else:

      return True

# Uncomment these function calls to test 

your not_sum_to_ten function:

print(not_sum_to_ten(9, -1))

# should print True

print(not_sum_to_ten(9, 1))

# should print False

print(not_sum_to_ten(5,5))

# should print False

Here is how we solved this one:


def not_sum_to_ten(num1, num2):
  if (num1 + num2 != 10):
    return True
  else:
    return False
We begin by adding our parameters within the condition of the if statement.
Next, we use != to compare the sum to 10. If they are not equal then our
function returns True, otherwise it returns False.

C. Python Code Challenges: Lists


Python Code Challenges: Lists

Python Code Challenges involving Lists

This article will help you review Python functions by providing some code
challenges involving lists.

Some of these challenges are difficult! Take some time to think about them
before starting to code.

You might not get the solution correct on your first try — look at your output,
try to find where you’re going wrong, and iterate on your solution.

Finally, if you get stuck, use our solution code! If you “Check Answer” twice
with an incorrect solution, you should see an option to get our solution code.
However, truly investigate that solution — experiment and play with the
solution code until you have a good grasp of how it is working. Good luck!

Function Syntax

As a refresher, function syntax looks like this:


def some_function(some_input1, some_input2):
  # … do something with the inputs …
  return output
For example, a function that returns the sum of the first and last elements of a
given list might look like this:
def first_plus_last(lst):
  return lst[0] + lst[-1]
And this would produce output like:
>>> first_plus_last([1, 2, 3, 4])
5
>>> first_plus_last([8, 2, 5, -8])
0
>>> first_plus_last([-10, 2, 3, -4])
-14

Challenges

We’ve included 5 list challenges below. Try to answer all of them and polish up
your problem-solving skills and your list expertise

1. Append Size

For the first code challenge, we are going to calculate the length of a list and
then append the value to the end of the list. Here is what we need to do:

1. Define the function to accept one parameter for our list

2. Get the length of the list

3. Append the length of the list to the end of the list

4. Return the modified list

Coding question

Create a function called append_size that has one parameter named lst.


The function should append the size of lst (inclusive) to the end of lst. The
function should then return this new list.
For example, if lst was [23, 42, 108], the function should return [23, 42, 108, 3] because
the size of lst was originally 3.
Hint

5
6

#Write your function here

def append_size(lst):

  lst.append(len(lst))

  return lst

#Uncomment the line below when your 

function is done

print(append_size([23, 42, 108]))

Output:

Run

Check answer

Run your code to check your answer

Here is this solution:


def append_size(lst):
  lst.append(len(lst))
  return lst
We can get the length and append it at the same time by nesting the function
calls as shown in the solution. Afterward, we return the modified list.
2. Append Sum

Let’s create a function that calculates the sum of the last two elements of a list
and appends it to the end. After doing so, it will repeat this process two more
times and return the resulting list. You can choose to use a loop or manually
use three lines. Here are the steps we need:

1. Define the function to accept one parameter for our list of numbers

2. Add the last and second to last elements from our list together

3. Append the calculated value to the end of our list.

4. Repeat steps 2 and 3 two more times

5. Return the modified list

Coding question

Write a function named append_sum that has one parameter — a list named


named lst.
The function should add the last two elements of lst together and append the
result to lst. It should do this process three times and then return lst.
For example, if lst started as [1, 1, 2], the final result should be [1, 1, 2, 3, 5, 8].
Hint

#Write your function here
def append_sum(lst):

  for i in range(3):

    lst.append(lst[-1]+lst[-2])

  return lst

#Uncomment the line below when your 

function is done

print(append_sum([1, 1, 2]))

Output:

Run

Check answer

Run your code to check your answer

This is how we solved it:


def append_sum(lst):
  lst.append(lst[-1] + lst[-2])
  lst.append(lst[-1] + lst[-2])
  lst.append(lst[-1] + lst[-2])
  return lst
In our solution, we add the numbers and append the result in one line. We
add the last and second to last elements within the .append() function and we
repeat this line two more times. Remember that when we use negative indices,
it starts from the end of the list and goes towards the beginning of the list.
You could also use a loop to solve this instead of repeating the lines.

3. Larger List

Let’s say we are working with two conveyor belts that contain items
represented by a numerical ID. If one conveyor belt contains more items than
the other, then we need to return the ID of the last item on that belt. In the
case where they have the same number of items, return the last item from the
first conveyor belt. In our code, we can represent the belts using lists. Here are
the steps:

1. Define the function to accept two parameters for our two lists of
numbers

2. Check if the length of the first list is greater than or equal to the length
of the second list

3. If true, then return the last element from the first list. Otherwise, return
the last element from the second list

Coding question

Write a function named larger_list that has two parameters named lst1 and lst2.


The function should return the last element of the list that contains more
elements. If both lists are the same size, then return the last element of lst1.
Hint

7
8

#Write your function here

def larger_list(lst1, lst2):

  if len(lst1) >= len(lst2):

    return lst1[-1]

  return lst2[-1]

#Uncomment the line below when your 

function is done

print(larger_list([4, 10, 2, 5], [-10, 2, 

5, 10]))

Output:

Run

Check answer

Run your code to check your answer

Here is how we did it:


def larger_list(lst1, lst2):
  if len(lst1) >= len(lst2):
    return lst1[-1]
  else:
    return lst2[-1]
We start by comparing the lengths of each of the lists using the len() function.
This determines whether to return the last element of the first list or the
second list. Notice that we use >=. This way, we know what to do if the lists
have an equal length.
In order to get the last element, we get the element at the -1 index. The
negative index starts at the end of the list and works towards the start of the
list.

4. More Than N

Our factory produces a variety of different flavored snacks and we want to


check the number of instances of a certain type. We have a conveyor belt full
of different types of snacks represented by different numbers. Our function
will accept a list of numbers (representing the type of snack), a number for the
second parameter (the type of snack we are looking for), and another number
as the third parameter (the maximum number of that type of snack on the
conveyor belt). The function will return True if the snack we are searching for
appears more times than we provided as our third parameter. These are the
steps we need:

1. Define the function to accept three parameters, a list of numbers, a


number to look for, and a number for the number of instances

2. Count the number of occurrences of item (the second parameter)


in lst (the first parameter)
3. If the number of occurrences is greater than n (the third parameter),
return True. Otherwise, return False
Coding question

Create a function named more_than_n that has three parameters named lst, item,


and n.
The function should return True if item appears in the list more than n times. The
function should return False otherwise.
Hint

2
3

10

#Write your function here

def more_than_n(lst, item, n):

  if lst.count(item) > n:

    return True

  return False

#Uncomment the line below when your 

function is done

print(more_than_n([2, 4, 6, 2, 3, 2, 1, 2]

, 2, 3))

Output:

 
Run

Check answer

Run your code to check your answer

Here is one way to do it:


def more_than_n(lst, item, n):
  if lst.count(item) > n:
    return True
  else:
    return False
We use the count() function to count the number of times item appears in lst. You
could also do this manually by looping through lst and incrementing a variable
every time you see item. We then compare the result to n.

5. Combine Sort

Finally, let’s create a function that combines two different lists together and
then sorts them. To do this we can combine the lists with an operation and
then sort using a function call. Here are the steps we need to use:

1. Define the function to accept two parameters, one for each list.

2. Combine the two lists together

3. Sort the result

4. Return the sorted and combined list

Coding question

Write a function named combine_sort that has two parameters named lst1 and lst2.


The function should combine these two lists into one new list and sort the
result. Return the new sorted list.

Hint
1

#Write your function here

def combine_sort(lst1, lst2):

   sort = lst1+lst2

   sort.sort()

   return sort

#Uncomment the line below when your 

function is done

print(combine_sort([4, 10, 2, 5], [-10, 

2, 5, 10]))

Output:

Run

Check answer
Run your code to check your answer

Here is how we did it:


def combine_sort(lst1, lst2):
  unsorted = lst1 + lst2
  sortedList = sorted(unsorted)
  return sortedList
We start by combining the two lists together using + in order to get a new list.
Next, in order to sort them, we use the sorted() function which returns a new
sorted version of the list.

D. Python Code Challenges: Lists (Advanced)


ython Code Challenges: Lists (Advanced)

Difficult Python Code Challenges involving Lists

This article will help you review Python functions by providing some code
challenges involving lists.

Some of these challenges are difficult! Take some time to think about them
before starting to code.

You might not get the solution correct on your first try — look at your output,
try to find where you’re going wrong, and iterate on your solution.

Finally, if you get stuck, use our solution code! If you “Check Answer” twice
with an incorrect solution, you should see an option to get our solution code.
However, truly investigate that solution — experiment and play with the
solution code until you have a good grasp of how it is working. Good luck!

Function Syntax

As a refresher, function syntax looks like this:


def some_function(some_input1, some_input2):
  # … do something with the inputs …
  return output
For example, a function that returns the sum of the first and last elements of a
given list might look like this:
def first_plus_last(lst):
  return lst[0] + lst[-1]
And this would produce output like:
>>> first_plus_last([1, 2, 3, 4])
5
>>> first_plus_last([8, 2, 5, -8])
0
>>> first_plus_last([-10, 2, 3, -4])
-14

Challenges

We’ve included 5 list challenges below. Try to answer all of them and polish up
your problem-solving skills and your list expertise!

1. Every Three Numbers

Let’s start our challenging problems with a function that creates a list of
numbers up to 100 in increments of 3 starting from a number that is passed to
the function as an input parameter. Here is what we need to do:

1. Define the function to accept one parameter for our starting number

2. Calculate the numbers between the starting number and 100 while
incrementing by 3

3. Store the numbers in a list

4. Return the list

Coding question

Create a function called every_three_nums that has one parameter named start.


The function should return a list of every third number
between start and 100 (inclusive). For example, every_three_nums(91) should return
the list [91, 94, 97, 100]. If start is greater than 100, the function should return an
empty list.
Hint

#Write your function here

def every_three_nums(start):

  new = list(range(start,101,3))

  return new

#Uncomment the line below when your 

function is done

print(every_three_nums(91))

Output:

 
Run

Check answer

Run your code to check your answer

Here is what we did:


def every_three_nums(start):
  return list(range(start, 101, 3))
We can write the body of this function in one line by nesting
the range() function inside of the list() function. The range function accepts the
starting number, the ending number (exclusive), and the amount to increment
by.

2. Remove Middle

Our next function will remove all elements from a list with an index within a
certain range. The function will accept a list, a starting index, and an ending
index. All elements with an index between the starting and ending index
should be removed from the list. Here are the steps:

1. Define the function to accept three parameters: the list, the starting
index, and the ending index

2. Get all elements before the starting index

3. Get all elements after the ending index

4. Combine the two partial lists into the result

5. Return the result

Coding question

Create a function named remove_middle which has three parameters


named lst, start, and end.
The function should return a list where all elements in lst with an index
between start and end (inclusive) have been removed.
For example, the following code should return [4, 23, 42] because elements at
indices 1, 2, and 3 have been removed:
remove_middle([4, 8 , 15, 16, 23, 42], 1, 3)
Hint

#Write your function here

def remove_middle(lst, start, end):

  return lst[:start]+lst[end+1:]

  

#Uncomment the line below when your 

function is done

print(remove_middle([4, 8, 15, 16, 23, 42]

, 1, 3))

Output:

 
Run

Check answer

Run your code to check your answer

Here is what we did:


def remove_middle(lst, start, end):
  return lst[:start] + lst[end+1:]
This can be solved using one line of code if you combine and slice the lists at
the same time. Slicing allows us to get the segments of the list before and
after the index range and the operation + allows us to combine them together.

3. More Frequent Item

Let’s go back to our factory example. We have a conveyor belt of items where
each item is represented by a different number. We want to know, out of two
items, which one shows up more on our belt. To solve this, we can use a
function with three parameters. One parameter for the list of items, another
for the first item we are comparing, and another for the second item. Here are
the steps:

1. Define the function to accept three parameters: the list, the first item,
and the second item

2. Count the number of times item1 shows up in our list


3. Count the number of times item2 shows up in our list
4. Return the item that appears more frequently in lst — if both items show
up the same number of times, return item1
Coding question

Create a function named more_frequent_item that has three parameters


named lst, item1, and item2.
Return either item1 or item2 depending on which item appears more often in lst.
If the two items appear the same number of times, return item1.
Hint

#Write your function here

def more_frequent_item(lst, item1, item2):

  if lst.count(item1) >= lst.count(item2):

    return item1

  else:

    return item2

#Uncomment the line below when your 

function is done

print(more_frequent_item([2, 3, 3, 2, 3, 

2, 3, 2, 3], 2, 3))

Output:

 
Run

Check answer

Run your code to check your answer

Here is this solution:


def more_frequent_item(lst, item1, item2):
  if lst.count(item1) >= lst.count(item2):
    return item1
  else:
    return item2
We use the count() function to find the number of occurrences for each item.
We then compare the counts against each other to find the item which
appears the most in the list. The item with the most appearances is returned
by the function.

4. Double Index

Our next function will double a value at a given position. We will provide a list
and an index to double. This will create a new list by replacing the value at the
index provided with double the original value. If the index is invalid then we
should return the original list. Here is what we need to do:

1. Define the function to accept two parameters, one for the list and
another for the index of the value we are going to double

2. Test if the index is invalid. If it’s invalid then return the original list

3. If the index is valid then get all values up to the index and store it as a
new list

4. Append the value at the index times 2 to the new list

5. Add the rest of the list from the index onto the new list
6. Return the new list

Coding question

Create a function named double_index that has two parameters: a list


named lst and a single number named index.
The function should return a new list where all elements are the same as
in lst except for the element at index. The element at index should be double the
value of the element at index of the original lst.
If index is not a valid index, the function should return the original list.
For example, the following code should return [1,2,6,4] because the element at
index 2 has been doubled:
double_index([1, 2, 3, 4], 2)
After writing your function, un-comment the call to the function that we’ve
provided for you to test your results.

Hint

10

11

#Write your function here

def double_index(lst, index):

  if index >= len(lst):
    return lst

  else:

    new_lst=lst[:index]

    new_lst.append(lst[index]*2)

    new_lst=new_lst + lst[index+1:]

    return new_lst

#Uncomment the line below when your 

function is done

print(double_index([3, 8, -10, 12], 2))

Output:

Run

Check answer

Run your code to check your answer

Here is one way to do it:


def double_index(lst, index):
  # Checks to see if index is too big
  if index >= len(lst):
    return lst
  else:
    # Gets the original list up to index
    new_lst = lst[0:index]
# Adds double the value at index to the new list
  new_lst.append(lst[index]*2)
  #  Adds the rest of the original list
  new_lst = new_lst + lst[index+1:]
  return new_lst
Note that this solution is careful not to modify the original input list. If we
were to simply use lst[index] = lst[index] * 2 then the list that was passed into the
function would be modified outside of the function as well. Creating a new list
and writing the values to it prevents this from happening. We use slicing to
extract the values before and after the index and we append the modified
value at the index to our new list.

5. Middle Item

For the final code challenge, we are going to create a function that finds the
middle item from a list of values. This will be different depending on whether
there are an odd or even number of values. In the case of an odd number of
elements, we want this function to return the exact middle value. If there is an
even number of elements, it returns the average of the middle two elements.
Here is what we need to do:

1. Define the function to accept one parameter for our list of numbers

2. Determine if the length of the list is even or odd

3. If the length is even, then return the average of the middle two numbers

4. If the length is odd, then return the middle number

Coding question

Create a function called middle_element that has one parameter named lst.


If there are an odd number of elements in lst, the function should return the
middle element. If there are an even number of elements, the function should
return the average of the middle two elements.
Hint

3
4

10

#Write your function here

def middle_element(lst):

  if len(lst)%2!=0:

    return lst[int(len(lst)/2)]

  else:

   sum = (lst[int(len(lst)/2)] + lst[int 

(len(lst)/2-1)])

   return sum/2

#Uncomment the line below when your 

function is done

print(middle_element([5, 2, -10, -4, 4, 5]

))

Output:

 
Run

Check answer

Run your code to check your answer

Here is how we solved it:


def middle_element(lst):
  if len(lst) % 2 == 0:
    sum = lst[int(len(lst)/2)] + lst[int(len(lst)/2) - 1]
    return sum / 2
  else:
    return lst[int(len(lst)/2)]
We used modulus to determine if the list had an even or odd number of
elements. After determining this, for an odd number of elements, we calculate
the middle index and return the middle element from the list. For an even
number of elements, we calculate the index of the element close to the middle
and the other element close to the middle (by subtracting 1 from the middle
calculation). We get the values at those indices and calculate the average.

Note that the math to find the middle index is a bit tricky. In some cases, when
we divide by 2, we would get a double. For example, if our list had 3 items in it,
then 3/2 would give us 1.5. The middle index should be 1, so in order to go
from 1.5 to 1, we cast 1.5 as an int. In total, this is int(len(lst)/2).

E. Python Code Challenges: Loops


Python Code Challenges: Loops

Python Code Challenges involving loops.

This lesson will help you review Python loops by providing some challenge
exercises involving loops.
Some of these challenges are difficult! Take some time to think about them
before starting to code.

You might not get the solution correct on your first try — look at your output,
try to find where you’re going wrong, and iterate on your solution.

Finally, if you get stuck, use our solution code! If you “Check Answer” twice
with an incorrect solution, you should see an option to get our solution code.
However, truly investigate that solution — experiment and play with the
solution code until you have a good grasp of how it is working. Good luck!

Function and Loop Syntax

As a refresher, function syntax looks like this:


def some_function(some_input1, some_input2):
  … do something with the inputs …
  return output
For example, a function that prints all odd numbers in a list would look like
this:
def odd_nums(lst):
  for item in lst:
    if item % 2 == 1:
      print(item)
And this would produce output like:
>>> odd_nums([4, 7, 9, 10, 13])
7
9
13

Challenges

We’ve included 5 challenges below. Try to answer all of them and polish up
your problem-solving skills and your loop expertise.

1. Divisible By Ten

Let’s start our code challenges with a function that counts how many numbers
are divisible by ten from a list of numbers. This function will accept a list of
numbers as an input parameter and use a loop to check each of the numbers
in the list. Every time a number is divisible by 10, a counter will be
incremented and the final count will be returned. These are the steps we need
to complete this:

1. Define the function to accept one input parameter called nums

2. Initialize a counter to 0

3. Loop through every number in nums

4. Within the loop, if any of the numbers are divisible by 10, increment our
counter

5. Return the final counter value

Coding question

Create a function named divisible_by_ten() that takes a list of numbers


named nums as a parameter.
Return the count of how many numbers in the list are divisible by 10.

Hint

10

11
#Write your function here

def divisible_by_ten(nums):

  count=0 

  for i in nums:

    if i%10 ==0:

       count += 1

  return count

#Uncomment the line below when your 

function is done

print(divisible_by_ten([20, 25, 30, 35, 

40]))

Output:

Run

Check answer

Run your code to check your answer

Let’s see how we solved it:


def divisible_by_ten(nums):
  count = 0
  for number in nums:
    if (number % 10 == 0):
      count += 1
  return count
In this solution, we defined the function and set up our counter. We use
a for loop to iterate through each number and check if it is divisible by ten. If a
number is divisible by another number then the remainder should be zero, so
we use modulus. After the loop has finished, we return our count.

2. Greetings

You are invited to a social gathering, but you are tired of greeting everyone
there. Luckily we can create a function to accomplish this task for us. In this
challenge, we will take a list of names and prepend the string 'Hello, ' before
each name. This will require a few steps:
1. Define the function to accept a list of strings as a single parameter
called names

2. Create a new list of strings

3. Loop through each name in names


4. Within the loop, concatenate 'Hello, ' and the current name together and
append this new string to the new list of strings

5. Afterwards, return the new list of strings

Coding question

Create a function named add_greetings() which takes a list of strings


named names as a parameter.
In the function, create an empty list that will contain each greeting. Add the
string 'Hello, ' in front of each name in names and append the greeting to the list.
Return the new list containing the greetings.

Hint

2
3

#Write your function here

def add_greetings(names):

  new_lst=[]

  for i in names:

    new_lst.append('Hello, ' + i)

  return new_lst

#Uncomment the line below when your 

function is done

print(add_greetings(["Owen", "Max", 

"Sophie"]))

Output:

 
Run

Check answer

Run your code to check your answer

This is one way to solve it:


def add_greetings(names):
  new_list = []
  for name in names:
    new_list.append("Hello, " + name)
  return new_list
First, we set up our function to accept the list of strings and we initialized a
new list of strings to hold our greetings. We iterate through each name and
we append and concatenate the strings at the same time within our loop.
Finally, we return the list containing all of our eloquent greetings.

3. Delete Starting Even Numbers

Let’s try a tricky challenge involving removing elements from a list. This
function will repeatedly remove the first element of a list until it finds an odd
number or runs out of elements. It will accept a list of numbers as an input
parameter and return the modified list where any even numbers at the
beginning of the list are removed. To do this, we will need the following steps:

1. Define our function to accept a single input parameter lst which is a list


of numbers

2. Loop through every number in the list if there are still numbers in the list
and if we haven’t hit an odd number yet

3. Within the loop, if the first number in the list is even, then remove the
first number of the list

4. Once we hit an odd number or we run out of numbers, return the


modified list

Coding question

Write a function called delete_starting_evens() that has a parameter named lst.


The function should remove elements from the front of lst until the front of the
list is not even. The function should then return lst.
For example if lst started as [4, 8, 10, 11, 12, 15], then delete_starting_evens(lst) should
return [11, 12, 15].
Make sure your function works even if every element in the list is even!

Hint

#Write your function here

def delete_starting_evens(lst):

  while (len(lst) > 0) and (lst[0] % 2 == 

0):

    lst = lst[1:]

  return lst

#Uncomment the lines below when your 

function is done

print(delete_starting_evens([4, 8, 10, 

11, 12, 15]))
print(delete_starting_evens([4, 8, 10]))

Output:

Run

Check answer

Run your code to check your answer

This is the way we solved it:


def delete_starting_evens(lst):
  while (len(lst) > 0 and lst[0] % 2 == 0):
    lst = lst[1:]
  return lst
After defining our method, we use a while loop to keep iterating as long as
some provided conditions are true. We provide two conditions for
the while loop to continue. We will keep iterating as long as there is at least one
number left in the list len(lst) > 0 and if the first element in the list is even lst[0] % 2
== 0. If both of these conditions are true, then we replace the list with every
element except for the first one using lst[1:]. Once the list is empty or we hit an
odd number, the while loop terminates and we return the modified list.

4. Odd Indices

This next function will give us the values from a list at every odd index. We will
need to accept a list of numbers as an input parameter and loop through the
odd indices instead of the elements. Here are the steps needed:

1. Define the function header to accept one input which will be our list of
numbers
2. Create a new list which will hold our values to return

3. Iterate through every odd index until the end of the list

4. Within the loop, get the element at the current odd index and append it
to our new list

5. Return the list of elements which we got from the odd indices.

Coding question

Create a function named odd_indices() that has one parameter named lst.


The function should create a new empty list and add every element
from lst that has an odd index. The function should then return this new list.
For example, odd_indices([4, 3, 7, 10, 11, -2]) should return the list [3, 10, -2].
Hint

10

#Write your function here

def odd_indices(lst):

  new_lst =[]
  for i in range(len(lst)):

     if i%2==1:

       new_lst.append(lst[i])

  return new_lst

#Uncomment the line below when your 

function is done

print(odd_indices([4, 3, 7, 10, 11, -2]))

Output:

Run

Check answer

Run your code to check your answer

Here is this solution:


def odd_indices(lst):
  new_lst = []
  for index in range(1, len(lst), 2):
    new_lst.append(lst[index])
  return new_lst
In our solution, we iterate through a range of values. The function range(1, len(lst),
2) returns a list of numbers starting at 1, ending at the length of len, and
incrementing by 2. This causes the loop to iterate through every odd number
until the last index of our list of numbers. Using this, we can simply append
the element at whatever index we are at since we know that using our range we
will be iterating through only odd indices.
Another way to do this would be to iterate through all indices and use an if
statement to see if the index you’re currently looking at is odd.

5. Exponents

In this challenge, we will be using nested loops in order to raise a list of


numbers to the power of a list of other numbers. What this means is that for
every number in the first list, we will raise that number to the power of every
number in the second list. If you provide the first list with 2 elements and the
second list with 3 numbers, then there will be 6 final answers. Let’s look at the
steps we need:

1. Define the function to accept two lists of numbers, bases and powers

2. Create a new list that will contain our answers

3. Create a loop that iterates through every base in bases


4. Within that loop, create another loop that iterates through every power
in power

5. Within that nested loop, append the result of the current base raised to
the current power.

6. After all iterations of both loops are complete, return the list of answers

Coding question

Create a function named exponents() that takes two lists as parameters


named bases and powers. Return a new list containing every number in
bases raised to every number in powers.
For example, consider the following code.
exponents([2, 3, 4], [1, 2, 3])
the result would be the list [2, 4, 8, 3, 9, 27, 4, 16, 64]. It would first add two to the
first. Then two to the second. Then two to the third, and so on.
Hint
1

#Write your function here

def exponents(bases, powers):

  new_lst=[]

  for i in bases:

    for n in powers:

      new_lst.append(i**n)

  return new_lst

#Uncomment the line below when your 

function is done

print(exponents([2, 3, 4], [1, 2, 3]))

Output:

 
Run

Check answer

Run your code to check your answer

Here is how we solved this one:


def exponents(bases, powers):
  new_lst = []
  for base in bases:
    for power in powers:
      new_lst.append(base ** power)
  return new_lst
As you can see in this solution, we used two nested for loops so that, for every
base, we iterate through every power. This allows us to raise each base to
every single power in our list and append the answers to our new list. Finally,
we return the list of answers.

F. Python Code Challenges: Loops (Advanced)


Python Code Challenges: Loops (Advanced)

Difficult Python Code Challenges involving Loops

This lesson will help you review Python loops by providing some challenge
exercises involving loops.

Some of these challenges are difficult! Take some time to think about them
before starting to code.

You might not get the solution correct on your first try — look at your output,
try to find where you’re going wrong, and iterate on your solution.

Finally, if you get stuck, use our solution code! If you “Check Answer” twice
with an incorrect solution, you should see an option to get our solution code.
However, truly investigate that solution — experiment and play with the
solution code until you have a good grasp of how it is working. Good luck!

Function and Loop Syntax

As a refresher, function syntax looks like this:


def some_function(some_input1, some_input2):
  … do something with the inputs …
  return output
For example, a function that prints all odd numbers in a list would look like
this:
def odd_nums(lst):
  for item in lst:
    if item % 2 == 1:
      print(item)
And this would produce output like:
>>> odd_nums([4, 7, 9, 10, 13])
7
9
13

Challenges

We’ve included 5 challenges below. Try to answer all of them and polish up
your problem-solving skills and your loop expertise.

1. Larger Sum

We are going to start our advanced challenge problems by calculating which


list of two inputs has the larger sum. We will iterate through each of the list
and calculate the sums, afterwards we will compare the two and return which
one has a greater sum. Here are the steps we need:

1. Define the function to accept two input parameters: lst1 and lst2

2. Create two variables to record the two sums

3. Loop through the first list and add up all of the numbers
4. Loop through the second list and add up all of the numbers

5. Compare the first and second sum and return the list with the greater
sum

Coding question

Create a function named larger_sum() that takes two lists of numbers as


parameters named lst1 and lst2.
The function should return the list whose elements sum to the greater
number. If the sum of the elements of each list are equal, return lst1.
Hint

10

11

12

13

14

15

#Write your function here

def larger_sum(lst1, lst2):
  sum_lst1=0

  sum_lst2=0

  for lst_1 in lst1:

    sum_lst1+=lst_1

  for lst_2 in lst2:

    sum_lst2 += lst_2

  if sum_lst1 >= sum_lst2:

    return lst1

  else:

    return lst2

#Uncomment the line below when your 

function is done

print(larger_sum([1, 9, 5], [2, 3, 7]))

Output:

Run

Check answer

Run your code to check your answer

Here’s one way to do it:


def larger_sum(lst1, lst2):
  sum1 = 0
  sum2 = 0
  for number in lst1:
    sum1 += number
  for number in lst2:
    sum2 += number
  if sum1 >= sum2:
    return lst1
  else:
    return lst2
In this solution, we manually iterate through each element in each list and
calculate our sums. We then return the list with the greater sum and break the
tie by returning lst1. You can also try solving this problem using
the sum() function in python. The body of this function could also be
condensed into one line of code if you want an additional challenge!

2. Over 9000

We are constructing a device that is able to measure the power level of our
coding abilities and according to the device, it will be impossible for our
power levels to be over 9000. Because of this, as we iterate through a list of
power values we will count up each of the numbers until our sum reaches a
value greater than 9000. Once this happens, we should stop adding the
numbers and return the value where we stopped. In order to do this, we will
need the following steps:

1. Define the function to accept a list of numbers

2. Create a variable to keep track of our sum

3. Iterate through every element in our list of numbers

4. Within the loop, add the current number we are looking at to our sum

5. Still within the loop, check if the sum is greater than 9000. If it is, end the
loop

6. Return the value of the sum when we ended our loop

Coding question
Create a function named over_nine_thousand() that takes a list of numbers
named lst as a parameter.
The function should sum the elements of the list until the sum is greater
than 9000. When this happens, the function should return the sum. If the sum of
all of the elements is never greater than 9000, the function should return total
sum of all the elements. If the list is empty, the function should return 0.
For example, if lst was [8000, 900, 120, 5000], then the function should return 9020.
Hint

10

11

12

13

#Write your function here

def over_nine_thousand(lst):

  sum_lst = 0

  if len(lst) > 0:

   for item in lst:

     sum_lst +=item
     if sum_lst > 9000:

      break

  return sum_lst

#Uncomment the line below when your 

function is done

print(over_nine_thousand([8000, 900, 120, 

5000]))

Output:

Run

Check answer

Run your code to check your answer

Here is this solution:


def over_nine_thousand(lst):
  sum = 0
  for number in lst:
    sum += number
    if (sum > 9000):
      break
  return sum
Our solution follows a similar pattern to some of the other code challenges,
except that we have a condition where we end early. In the case where we
reach a sum greater than 9000, we can use the break keyword to exit our loop.
This will continue to execute the code outside of our loop, which in this case,
returns the sum that we found.

3. Max Num

Here is a more traditional coding problem for you. This function will be used
to find the maximum number in a list of numbers. This can be accomplished
using the max() function in python, but as a challenge, we are going to
manually implement this function. Here is what we need to do:
1. Define the function to accept a list of numbers called nums

2. Set our default maximum value to be the first element in the list

3. Loop through every number in the list of numbers

4. Within the loop, if we find a number greater than our starting maximum,
then replace the maximum with what we found.

5. Return the maximum number

Coding question

Create a function named max_num() that takes a list of numbers named nums as a


parameter.
The function should return the largest number in nums
Hint

5
6

#Write your function here

def max_num(nums ):

  maxx = max(list(nums))

  return maxx

#Uncomment the line below when your 

function is done

print(max_num([50, -10, 0, 75, 20]))

Output:

Run

Check answer

Run your code to check your answer

Here is one way to solve this:


def max_num(nums):
  maximum = nums[0]
  for number in nums:
    if number > maximum:
      maximum = number
  return maximum
There are a few different ways to accomplish this task, but the way we did it
was to check every element in the list and see if there is one bigger than what
we currently think is the biggest. If there is a bigger one, then replace it. We
keep replacing the number until the largest number has been found.
4. Same Values

In this challenge, we need to find the indices in two equally sized lists where
the numbers match. We will be iterating through both of them at the same
time and comparing the values, if the numbers are equal, then we record the
index. These are the steps we need to accomplish this:

1. Define our function to accept two lists of numbers

2. Create a new list to store our matching indices

3. Loop through each index to the end of either of our lists

4. Within the loop, check if our first list at the current index is equal to the
second list at the current index. If so, append the index where they
matched

5. Return our list of indices

Coding question

Write a function named same_values() that takes two lists of numbers of equal


size as parameters.
The function should return a list of the indices where the values were equal
in lst1 and lst2.
For example, the following code should return [0, 2, 3]
same_values([5, 1, -10, 3, 3], [5, 10, -10, 3, 5])
Hint

5
6

10

11

12

#Write your function here

def same_values(lst1, lst2):

  new_lst=[]

  for i in range(len(lst1)):

      if lst1[i]==lst2[i]:

        new_lst.append(i)

      else:

        continue

  return new_lst

#Uncomment the line below when your 

function is done

print(same_values([5, 1, -10, 3, 3], [5, 

10, -10, 3, 5]))

Output:
 

Run

Check answer

Run your code to check your answer

Here’s how we did it:


def same_values(lst1, lst2):
  new_lst = []
  for index in range(len(lst1)):
    if lst1[index] == lst2[index]:
      new_lst.append(index)
  return new_lst
In this solution, we used a loop that iterates using the range of the len of our list.
This generates the indices we need to iterate through. Note that we assume
the lists are of equal size. We then access the element at the current index
from each list using lst1[index] and lst2[index]. If they are equal we add the index to
the new list. Finally, we return the results.

5. Reversed List

For the final challenge, we are going to test two lists to see if the second list is
the reverse of the first list. There are a few different ways to approach this, but
we are going to try a method that iterates through each of the values in one
direction for the first list and compares them against the values starting from
the other direction in the second list. Here is what you need to do:

1. Define a function that has two input parameters for our lists

2. Loop through every index in one of the lists from beginning to end

3. Within the loop, compare the element in the first list at the current index
against the element at the second list’s last index minus the current
index. If there was a mismatch, then the lists aren’t reversed and we can
return False
4. If the loop ended successfully, then we know the lists are reversed and
we can return True.
Coding question

Create a function named reversed_list() that takes two lists of the same size as


parameters named lst1 and lst2.
The function should return True if lst1 is the same as lst2 reversed. The function
should return False otherwise.
For example, reversed_list([1, 2, 3], [3, 2, 1]) should return True.
Hint

#Write your function here

def  reversed_list(lst1, lst2):

  for i in range(len(lst1)):

    if lst1[i] != lst2[-i - 1]:

      return False

  return True

#Uncomment the lines below when your 
function is done

print(reversed_list([1, 2, 3], [3, 2, 1]))

print(reversed_list([1, 5, 3], [3, 2, 1]))

Output:

Run

Check answer

Run your code to check your answer

Here is one way to do it:


def reversed_list(lst1, lst2):
  for index in range(len(lst1)):
    if lst1[index] != lst2[len(lst2) - 1 - index]:
      return False
  return True
In this code, we iterate through each of the indices for the entire length of
either of the lists (since we assume the lengths are equal) and we perform a
comparison on each of the elements. We get the element at the current index
from our first list with lst1[index] and we test it against the last index of the
second list minus the current index len(lst2) - 1 – index.
That math is a little complicated — it helps to look at a concrete example. If
we are given a list of 5 elements, the valid indices are 0 to 4. Because of this,
the last index in the second list is len(lst2) - 1, or 5 - 1 = 4. Now in order to get the
inverse of the position we are at in the first list, we subtract the index we are at
from the end of the second list. So on the first pass, we’ll compare the element
at position 0 to the element at position 5 - 1 - 0 = 4. On the next pass, we’ll
compare the element at position 1 to the element at position 5 - 1 - 1 = 3, and so
on.
If any of the two elements are not equal then we know that the second list is
not the reverse of the first list and we return False. If we made it to the end
without a mismatch then we can return True since the second list is the reverse
of the first. You could also try simplifying this code by using the python
function reversed() or other methods that you will learn later on such as ‘slicing’.

G. Python Code Challenges: Functions


Python Code Challenges: Functions

Python Code Challenges involving functions.

This article will help you review Python functions by providing some code
challenges.

Some of these challenges are difficult! Take some time to think about them
before starting to code.

You might not get the solution correct on your first try — look at your output,
try to find where you’re going wrong, and iterate on your solution.

Finally, if you get stuck, use our solution code! If you “Check Answer” twice
with an incorrect solution, you should see an option to get our solution code.
However, truly investigate that solution — experiment and play with the
solution code until you have a good grasp of how it is working. Good luck!

Function Syntax

As a refresher, function syntax looks like this:


def some_function(some_input1, some_input2):
  # … do something with the inputs …
  return output
For example, a function that returns the sum of the first and last elements of a
given list might look like this:
def first_plus_last(lst):
  return lst[0] + lst[-1]
And this would produce output like:
>>> first_plus_last([1, 2, 3, 4])
5
>>> first_plus_last([8, 2, 5, -8])
0
>>> first_plus_last([-10, 2, 3, -4])
-14

Challenges

We’ve included 5 challenges below. Try to answer all of them and polish up
your problem-solving skills and your function expertise.

1. Tenth Power

Let’s create some functions which can help us solve math problems! For this
first function, we are going to take the tenth power of a number. In order to
do this we need to do three things:

1. Set up the function header for tenth_power which accepts one parameter

2. Take the tenth power of the input value

3. Return the result

Coding question

Write a function named tenth_power() that has one parameter named num.


The function should return num raised to the 10th power.
Hint

5
6

10

# Write your tenth_power function here:

def tenth_power(num):

  return num**10

# Uncomment these function calls to test 

your tenth_power function:

print(tenth_power(1))

# 1 to the 10th power is 1

print(tenth_power(0))

# 0 to the 10th power is 0

print(tenth_power(2))

# 2 to the 10th power is 1024

Output:

Run

Check answer
Run your code to check your answer

Let’s go over this solution:


def tenth_power(num):
  return num ** 10
This is one way to solve this problem using two lines of code.

The first line is the function header which uses def to define the function
followed by the function name. Within the parentheses we include num which is
our formal parameter. Because of this, num is the variable name for the value
we pass into this function.
On our next line, we use return to show that this function is going to return a
value when it is called. Next to the return keyword, we define what value is
going to be returned. Since we need the tenth power of our input value, we
can use the power operator in python which is **. Using this knowledge, in
order to get the tenth power of our input value, we use num ** 10.

2. Square Root

Another useful function for solving math problems is the square root function.
We can create this using similar steps from the last problem. The code will
look very similar. We need to:

1. Set up the function header for square_root which accepts one parameter

2. Take the square root of the input value

3. Return the result

Coding question

Write a function named square_root() that has one parameter named num.


Use exponents (**) to return the square root of num.
Hint

3
4

# Write your square_root function here:

def square_root(num):

  return num**0.5

# Uncomment these function calls to test 

your square_root function:

print(square_root(16))

# should print 4

print(square_root(100))

# should print 10

Output:

Run

Check answer

Run your code to check your answer

Let’s go over one possible solution:


def square_root(num):
  return num ** 0.5
As you can see, this solution is very similar to the last problem. In this case, the
only changes we need are the function name and changing the power value to
0.5. We define the function called square_root with one parameter. We then take
the one half power of the input value which is mathematically the same as
taking the square root and return it.

3. Win Percentage

Next, we will create a function which calculates the percentage of games won.
In order to do this, we will need to know how many total games there were
and divide the number of wins by the total number of games. For this
function, there will be two input parameters, the number of wins and the
number of losses. We also need to make sure that we return the result as a
percentage (in the range of 0 to 100). In order to create this method we need
the following steps:

1. Define the function header with two parameters, wins and losses

2. Calculate the total number of games using the number of wins and
losses

3. Get the ratio of winning using the number of wins out of the total
number of games.

4. Convert the ratio to a percentage

5. Return the percentage

Coding question

Create a function called win_percentage() that takes two parameters


named wins and losses.
This function should return out the total percentage of games won by a team
based on these two numbers.

Hint
1

# Write your win_percentage function here:

def win_percentage(wins, loses):

  return wins/(wins+loses)*100

# Uncomment these function calls to test 

your win_percentage function:

print(win_percentage(5, 5))

# should print 50

print(win_percentage(10, 0))

# should print 100

Output:

Run
Check answer

Run your code to check your answer

Let’s go over how we completed this function:


def win_percentage(wins, losses):
  total_games = wins + losses
  ratio_won = wins / total_games
  return ratio_won * 100
First, we defined our function with two parameters, one for games won and
one for games lost. Next, we calculated the total number of games using the
number of wins + losses. After that, we use calculate the ratio of wins out of
the total number of games by dividing wins by our total_games variable. Since this
gives us a ratio and we want it in percentage form, we multiply the answer by
100 and return it.

4. Average

Let’s create a function which takes the average of two numbers. These two
numbers will be the input of the function and the output will be the average
of the two. In order to do this, we need to do a few steps:

1. Define the function with two input parameters, num1 and num2

2. Calculate the sum of the two numbers

3. Divide the sum by the number of inputs to the function

4. Return the answer

Coding question

Write a function named average() that has two parameters named num1 and num2.


The function should return the average of these two numbers.

Hint

2
3

# Write your average function here:

def average(num1, num2):

  return (num1+num2)/2

# Uncomment these function calls to test 

your average function:

print(average(1, 100))

# The average of 1 and 100 is 50.5

print(average(1, -1))

# The average of 1 and -1 is 0

Output:

Run

Check answer

Run your code to check your answer


Let’s look at this solution:
def average(num1, num2):
  return (num1 + num2) / 2
In this solution, we defined the function with two parameters one line and
returned the average on the next line. When returning the value, we used
parentheses around the addition to cause the two numbers to be added
together first before dividing by two.

5. Remainder

For the final challenge in this group, we are going to take the remainder of
two numbers while performing other mathematical operations on them. We
are going to multiply the numerator by 2 and divide the denominator by 2.
After the two values have been modified, we will divide them and return the
remainder. In order to do this we will need to:

1. Define the function to accept two parameters

2. Multiply the first input value by 2

3. Divide the second input value by 2

4. Calculate the remainder of the modified first input value divided by the
modified second input value (using modulus)

5. Return the answer

Coding question

Write a function named remainder() that has two parameters


named num1 and num2.
The function should return the remainder of twice num1 divided by half of num2.
Hint

3
4

# Write your remainder function here:

def remainder(num1, num2):

  return (num1*2)%(num2/2)

# Uncomment these function calls to test 

your remainder function:

print(remainder(15, 14))

# should print 2

print(remainder(9, 6))

# should print 0

Output:

Run

Check answer

Run your code to check your answer

Let’s go over how we did it:


def remainder(num1, num2):
  return (2 * num1) % (num2 / 2)
Our solution It shortened to use only two lines of code. The first line defines
the function with two input parameters. The second line performs the two
mathematical operations on either side of the modulus within parenthesis.
This causes the two calculations to be performed before taking the remainder
of the left side divided by the right side.

H. Python Code Challenges: Functions (Advanced)


Python Code Challenges: Functions (Advanced)

Difficult Python Code Challenges involving Functions

This article will help you review Python functions by providing some code
challenges involving functions.

Some of these challenges are difficult! Take some time to think about them
before starting to code.

You might not get the solution correct on your first try — look at your output,
try to find where you’re going wrong, and iterate on your solution.

Finally, if you get stuck, use our solution code! If you “Check Answer” twice
with an incorrect solution, you should see an option to get our solution code.
However, truly investigate that solution — experiment and play with the
solution code until you have a good grasp of how it is working. Good luck!

Function Syntax

As a refresher, function syntax looks like this:


def some_function(some_input1, some_input2):
  # … do something with the inputs …
  return output
For example, a function that returns the sum of the first and last elements of a
given list might look like this:
def first_plus_last(lst):
  return lst[0] + lst[-1]
And this would produce output like:
>>> first_plus_last([1, 2, 3, 4])
5
>>> first_plus_last([8, 2, 5, -8])
0
>>> first_plus_last([-10, 2, 3, -4])
-14

Challenges

We’ve included 5 challenges below. Try to answer all of them and polish up
your problem-solving skills!

1. First Three Multiples

Let’s start by creating a function which both prints and returns values. For this
function, we are going to print out the first three multiples of a number and
return the third multiple. This means that we are going to print 1, 2, and 3
times the input number and then return the value of 3 times the input
number. For this, we are going to need a few steps:

1. Define the function header to accept one input parameter called num


2. Print out 1 times num
3. Print out 2 times num
4. Print out 3 times num
5. Return the value of 3 times num
Coding question

Write a function named first_three_multiples() that has one parameter named num.


This function should print the first three multiples of num. Then, it should return
the third multiple.
For example, first_three_multiples(7) should print 7, 14, and 21 on three different lines,
and return 21.
Hint

2
3

# Write your first_three_multiples 

function here

def first_three_multiples(num):

  print( str(num) + ", "+ str(2*num)+ ", "

+ str(3*num))

  return 3*num

# Uncomment these function calls to test 

your first_three_multiples function:

first_three_multiples(10)

# should print 10, 20, 30, and return 30

first_three_multiples(0)

# should print 0, 0, 0, and return 0

Output:

 
Run

Check answer

Run your code to check your answer

Let’s go over how we answered it:


def first_three_multiples(num):
  print(num)
  print(num * 2)
  print(num * 3)
  return num * 3
In this solution, we start by defining the function header with an input. We
then use the next three lines to print the result of multiplying the input value
by one, two, and three. Finally, we return the result of multiplying the input
value by 3.

2. Tip

Let’s say we are going to a restaurant and we decide to leave a tip. We can
create a function to easily calculate the amount to tip based on the total cost
of the food and a percentage. This function will accept both of those values as
inputs and return the amount of money to tip. In order to do this, we will need
a few steps:

1. Define the function to accept the total cost of the food called total and
the percentage to tip as percentage

2. Calculate the tip amount by multiplying the total and percentage and
dividing by 100

3. Return the tip amount

Coding question

Create a function called tip() that has two parameters named total and percentage.


This function should return the amount you should tip given a total and the
percentage you want to tip.

Hint

# Write your tip function here:

def tip(total, percentage):

    tip_amount= total*percentage/100

    return tip_amount

# Uncomment these function calls to test 

your tip function:

print(tip(10, 25))

# should print 2.5

print(tip(0, 100))

# should print 0.0
Output:

Run

Check answer

Run your code to check your answer

Lets go over this solution:


def tip(total, percentage):
  tip_amount = (total * percentage) / 100
  return tip_amount
In this solution, we defined the function with two parameters and then used
them to calculate the tip amount. We multiplied the input values together and
divided by 100 since the second input is in percentage form and we want a
monetary amount. Lastly, we returned the calculated tip value.

3. Bond, James Bond

It’s time to re-create a famous movie scene through code. Our function is
going to concatenate strings together in order to replace James Bond’s name
with whatever name we want. The input to our function will be two strings,
one for a first name and another for a last name. The function will return a
string consisting of the famous phrase but replaced with our inputs. To
accomplish this, we need to:

1. Define the function to accept two parameters, first_name and last_name


2. Concatenate the string ', ' on to the last_name
3. Concatenate the first_name on to the result of the previous step

4. Concatenate a space on to the result

5. Concatenate the last_name again to the result


6. Return the final string

Coding question

Write a function named introduction() that has two parameters


named first_name and last_name.
The function should return the last_name, followed by a comma, a
space, first_name another space, and finally last_name.
Hint

# Write your introduction function here:

def introduction(first_name , last_name):

  return last_name +", "+ first_name +" "

+ last_name

# Uncomment these function calls to test 

your introduction function:

print(introduction("James", "Bond"))

# should print Bond, James Bond

print(introduction("Maya", "Angelou"))

# should print Angelou, Maya Angelou
Output:

Run

Check answer

Run your code to check your answer

Let’s go over how we did it:


def introduction(first_name, last_name):
  return last_name + ", " + first_name + " " + last_name
First, we defined the method to accept the first and last names. On the next
line, we performed all of the concatenations at once by adding the comma,
spaces, and names in the correct order. We also returned the result on the
same line.

4. Dog Years

Let’s create a function which calculates a dog’s age in dog years! This function
will accept the name of the dog and the age in human years. It will calculate
the age of the dog in dog years and return a string describing the dog’s age.
This will require a few steps:

1. Define the function called dog_years to accept two parameters: name and age

2. Calculate the age of the dog in dog years

3. Concatenate the string with the dog’s name and age in dog years

4. Return the resulting string


Coding question

Some say that every one year of a human’s life is equivalent to seven years of
a dog’s life. Write a function named dog_years() that has two parameters
named name and age.
The function should compute the age in dog years and return the following
string:
"{name}, you are {age} years old in dog years"
Test this function with your name and your age!

Hint

# Write your dog_years function here:

def dog_years(name, age):

  return name + ", you are "+ str(age*7)+ 

" years old in dog years"

# Uncomment these function calls to test 

your dog_years function:

print(dog_years("Lola", 16))

# should print "Lola, you are 112 years 

old in dog years"
print(dog_years("Baby", 0))

# should print "Baby, you are 0 years old 

in dog years"

Output:

Run

Check answer

Run your code to check your answer

Let’s look at this solution:


def dog_years(name, age):
  return name+", you are "+str(age * 7)+" years old in dog years"
In this solution we used two lines of code to accomplish this task. The first line
defines the function with the two inputs and the second line concatenates the
string while also performing the calculation. We used str(age * 7) to convert the
number to a string, and since that function call returns a string, we can
concatenate it in-line with the rest of the string.

5. All Operations

For the final code challenge, we are going to perform multiple mathematical
operations on multiple inputs to the function. We will begin with adding the
first two inputs, then we will subtract the third and fourth inputs. After that, we
will multiply the first result and the second result. In the end, we will return the
remainder of the previous result divided by the first input. We will also print
each of the steps. The steps needed to complete this are:
1. Define the function to accept four inputs: a, b, c, and d
2. Print and store the result of a + b
3. Print and store the result of c - d

4. Print and store the first result times the second result

5. Return the previous result modulo a


Coding question

Create a function named lots_of_math(). This function should have four


parameters named a, b, c, and d. The function should print 3 lines and return 1
value.
First, print the sum of a and b.
Second, print c minus d.
Third, print the first number printed, multiplied by the second number
printed.

Finally, return the third number printed modulo a.


Hint

# Write your lots_of_math function here:

def lots_of_math(a, b, c, d):

  print(a+b, c-d, (a+b)*(c-d))
  return (a+b) * (c-d) %a

# Uncomment these function calls to test 

your lots_of_math function:

print(lots_of_math(1, 2, 3, 4))

# should print 3, -1, -3, 0

print(lots_of_math(1, 1, 1, 1))

# should print 2, 0, 0, 0

Output:

Run

Check answer

Run your code to check your answer

Here is the way we did it:


def lots_of_math(a, b, c, d):
  first = a + b
  second = c - d
  third = first * second
  fourth = third % a
  print(first)
  print(second)
  print(third)
  return fourth
After defining the function, we store each result into its own variable
for first and second. We then use these two variables in the calculation
for third and we use the value of third to get fourth. Afterwards, we print the first
three variables and return the fourth one.

VII. Strings
A. introduction to strings
10/12.
INTRODUCTION TO STRINGS

Strings and Conditionals (Part One)

Now that we are iterating through strings, we can really explore the potential
of strings. When we iterate through a string we do something with each
character. By including conditional statements inside of these iterations, we
can start to do some really cool stuff.

Take a look at the following code:

favorite_fruit = "blueberry"
counter = 0
for character in favorite_fruit:
  if character == "b":
    counter = counter + 1
print(counter)
This code will count the number of bs in the string “blueberry” (hint: it’s two).
Let’s take a moment and break down what exactly this code is doing.

First, we define our string, favorite_fruit, and a variable called counter, which we set


equal to zero. Then the for loop will iterate through each character
in favorite_fruit and compare it to the letter b.

Each time a character equals b the code will increase the variable counter by one.
Then, once all characters have been checked, the code will print the counter,
telling us how many bs were in “blueberry”. This is a great example of how
iterating through a string can be used to solve a specific application, in this
case counting a certain letter in a word.

Instructions

1.

Write a function called letter_check that takes two inputs, word and letter.

This function should return True if the word contains the letter and False if it does


not.
Checkpoint 2 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

Within a for loop, does every if statement need an else?

2.

Why doesn’t else: return False work?


3.

How does the indentation level of return False change the code?

Still have questions? View this exercise's thread in the Codecademy Forums.


11/12:
INTRODUCTION TO STRINGS

Strings and Conditionals (Part Two)

There’s an even easier way than iterating through the entire string to
determine if a character is in a string. We can do this type of check more
efficiently using in. in checks if one string is part of another string.

Here is what the syntax of in looks like:

letter in word
Here, letter in word is a boolean expression that is True if the string letter is in the
string word. Here are some examples:

print("e" in "blueberry")
# => True
print("a" in "blueberry")
# => False
In fact, this method is more powerful than the function you wrote in the last
exercise because it not only works with letters, but with entire strings as well.

print("blue" in "blueberry")
# => True
print("blue" in "strawberry")
# => False

Instructions

1.
Write a function called contains that takes two
arguments, big_string and little_string and returns True if big_string contains little_string.

For example contains("watermelon", "melon") should return True and contains("watermelon",


"berry") should return False.
Checkpoint 2 Passed

2.

Write a function called common_letters that takes two


arguments, string_one and string_two and then returns a list with all of the letters
they have in common.

The letters in the returned list should be unique. For example,

common_letters("banana", "cream")
should return ['a'].
Checkpoint 3 Passed

Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

How to avoid duplicate letters?

2.

I tried to brute force the solution, does this work?


3.

Can the in operator be used to get the specific index of duplicate


characters?

Still have questions? View this exercise's thread in the Codecademy Forums.

12/12:
INTRODUCTION TO STRINGS

Review

Great work! I hope you are now starting to see the potential of strings and
how they can be used to solve a huge variety of problems.

In this lesson you learned:

 A string is a list of characters.


 A character can be selected from a string using its index string_name[index].
These indices start at 0.
 A ‘slice’ can be selected from a string. These can be between two indices
or can be open-ended, selecting all of the string from a point.
 Strings can be concatenated to make larger strings.
 len() can be used to determine the number of characters in a string.
 Strings can be iterated through using for loops.
 Iterating through strings opens up a huge potential for applications,
especially when combined with conditional statements.

Let’s put your new skills to the test!

Instructions
1.

Copeland’s Corporate Company has finalized what they want their username


and temporary password creation to be and have enlisted your help, once
again, to build the function to generate them. In this exercise, you will create
two functions, username_generator and password_generator.

Let’s start with username_generator. Create a function called username_generator take


two inputs, first_name and last_name and returns a username. The username should
be a slice of the first three letters of their first name and the first four letters of
their last name. If their first name is less than three letters or their last name is
less than four letters it should use their entire names.

For example, if the employee’s name is Abe Simpson the function should


generate the username AbeSimp.
2.

Great work! Now for the temporary password, they want the function to take
the input user name and shift all of the letters by one to the right, so the last
letter of the username ends up as the first letter and so forth. For example, if
the username is AbeSimp, then the temporary password generated should
be pAbeSim.

Start by defining the function password_generator so that it takes one


input, username and in it define an empty string named password.
3.

Inside password_generator create a for loop that iterates through the indices


username by going from 0 to len(username).

To shift the letters right, at each letter the for loop should add the previous
letter to the string password.
Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!
Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

What are some important differences between a string and a list?

2.

Are strings actually immutable?

Still have questions? View this exercise's thread in the Codecademy Forums.

B. introduction to strings
C. String methods
1/13. Introduction
STRING METHODS

Introduction

Do you have a gigantic string that you need to parse for information? Do you
need to sanitize a users input to work in a function? Do you need to be able to
generate outputs with variable values? All of these things can be
accomplished with string methods!
Python comes with built-in string methods that gives you the power to
perform complicated tasks on strings very quickly and efficiently. These string
methods allow you to change the case of a string, split a string into many
smaller strings, join many small strings together into a larger string, and allow
you to neatly combine changing variables with string outputs.

In the previous lesson, you worked with len(), which was a function that


determined the number of characters in a string. This, while similar, was NOT a
string method. String methods all have the same syntax:

string_name.string_method(arguments)
Unlike len(), which is called with a string as its argument, a string method is
called at the end of a string and each one has its own method specific
arguments.

Instructions

The diagram shows all of the string methods you can expect to learn in this
lesson. Take a quick look at them and then let’s get started!

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

Can we call more than one string method in a single statement?

Still have questions? View this exercise's thread in the Codecademy Forums.


2/13. Formatting Methods
STRING METHODS

Formatting Methods

There are three string methods that can change the casing of a string. These
are .lower(), .upper(), and .title().

 .lower() returns the string with all lowercase characters.


 .upper() returns the string with all uppercase characters.
 .title() returns the string in title case, which means the first letter of each
word is capitalized.

Here’s an example of .lower() in action:

favorite_song = 'SmOoTH'
favorite_song_lowercase = favorite_song.lower()
print(favorite_song_lowercase)
# => 'smooth'
Every character was changed to lowercase! It’s important to remember that
string methods can only create new strings, they do not change the original
string.

print(favorite_song)
# => 'SmOoTH'
See, it’s still the same! These string methods are great for sanitizing user input
and standardizing the formatting of your strings.

Instructions

1.

You’re a programmer working for an organization that is trying to digitize and


store poetry called Preserve the Verse.

You’ve been given two strings, the title of a poem and its author, and have
been asked to reformat them slightly to fit the conventions of the
organization’s database.
Make poem_title have title case and save it to poem_title_fixed.
Checkpoint 2 Passed

2.

Print poem_title and poem_title_fixed.

How did the string change?


Checkpoint 3 Passed

3.

The organization’s database also needs the author’s name to be uppercase


only.

Make poem_author uppercase and save it to poem_author_fixed.


Checkpoint 4 Passed

4.

Print poem_author and poem_author_fixed.

Again, how did the string change?


Checkpoint 5 Passed

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

Do these methods affect special characters?

Still have questions? View this exercise's thread in the Codecademy Forums.


3/13. Splitting Strings
Splitting Strings

.upper(), .lower(),
and .title() all are performed on an existing string and produce a
string in return. Let’s take a look at a string method that returns a different
object entirely!

.split() is
performed on a string, takes one argument, and returns a list of
substrings found between the given argument (which in the case of .split() is
known as the delimiter). The following syntax should be used:

string_name.split(delimiter)
If you do not provide an argument for .split() it will default to splitting at
spaces.

For example, consider the following strings:

man_its_a_hot_one = "Like seven inches from the midday sun"


print(man_its_a_hot_one.split())
# => ['Like', 'seven', 'inches', 'from', 'the', 'midday', 'sun']
.split returned a list with each word in the string. Important to note: if we
run .split() on a string with no spaces, we will get the same string in return.

Instructions

1.

In the code editor is a string of the first line of the poem Spring Storm by
William Carlos Williams.

Use .split() to create a list called line_one_words that contains each word in this line


of poetry.

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!
Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

If we run .split() without an argument, what happens to consecutive


whitespaces?

2.

What does the delimiter do?

Still have questions? View this exercise's thread in the Codecademy Forums.

4/13. Splitting Strings II


Splitting Strings II

If we provide an argument for .split() we can dictate the character we want our


string to be split on. This argument should be provided as a string itself.

Consider the following example:

greatest_guitarist = "santana"
print(greatest_guitarist.split('n'))
# => ['sa', 'ta', 'a']
We provided 'n' as the argument for .split() so our string “santana” got split at
each 'n' character into a list of three strings.

What do you think happens if we split the same string at 'a'?


print(greatest_guitarist.split('a'))
# => ['s', 'nt', 'n', '']
Notice that there is an unexpected extra '' string in this list. When you split a
string on a character that it also ends with, you’ll end up with an empty string
at the end of the list.

You can use any string as the argument for .split(), making it a versatile and


powerful tool.

Instructions

1.

Your boss at the Poetry organization sent over a bunch of author names that
he wants you to prepare for importing into the database. Annoyingly, he sent
them over as a long string with the names separated by commas.

Using .split() and the provided string, create a list called author_names containing


each individual author name as it’s own string.
2.

Great work, but now it turns out they didn’t want poet’s first names (why
didn’t they just say that the first time!?)

Create another list called author_last_names that only contains the last names of


the poets in the provided string.
Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.
How does split() work for arguments longer than a single character?

2.

How to select only last names? (Solution Explanation)

3.

How should I use .split() to remove commas between names?

Still have questions? View this exercise's thread in the Codecademy Forums.

5/13. Splitting Strings III


STRING METHODS

Splitting Strings III

We can also split strings using escape sequences. Escape sequences are used to
indicate that we want to split by something in a string that is not necessarily a
character. The two escape sequences we will cover here are

 \n Newline
 \t Horizontal Tab

Newline or \n will allow us to split a multi-line string by line breaks and \t will


allow us to split a string by tabs. \t is particularly useful when dealing with
certain datasets because it is not uncommon for data points to be separated
by tabs.

Let’s take a look at an example of splitting by an escape sequence:

smooth_chorus = \
"""And if you said, "This life ain't good enough."
I would give my world to lift you up
I could change my life to better suit your mood
Because you're so smooth"""

chorus_lines = smooth_chorus.split('\n')

print(chorus_lines)
This code is splitting the multi-line string at the newlines ( \n) which exist at the
end of each line and saving it to a new list called chorus_lines. Then it
prints chorus_lines which will produce the output

['And if you said, "This life ain\'t good enough."', 'I would give my world to lift you
up', 'I could change my life to better suit your mood', "Because you're so smooth"]
The new list contains each line of the original string as its own smaller string.
Also, notice that Python automatically escaped the ' character in the first line
and adjusted to double quotation marks to allow the apostrophe on last line
when it created the new list.

Instructions

1.

The organization has sent you over the full text for William Carlos Williams
poem Spring Storm. They want you to break the poem up into its individual
lines.

Create a list called spring_storm_lines that contains a string for each line of Spring


Storm.
Stuck? Get a hint

Concept Review
Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

What other escape sequences are there?

2.

What does the backslash in the variable declaration mean? (= \)

Still have questions? View this exercise's thread in the Codecademy Forums.

6/13. Joining Strings


Joining Strings

Now that you’ve learned to break strings apart using .split(), let’s learn to put
them back together using .join(). .join() is essentially the opposite of .split(),
it joins a list of strings together with a given delimiter. The syntax of .join() is:

'delimiter'.join(list_you_want_to_join)
Now this may seem a little weird, because with .split() the argument was the
delimiter, but now the argument is the list. This is because join is still a string
method, which means it has to act on a string. The string .join() acts on is the
delimiter you want to join with, therefore the list you want to join has to be
the argument.
This can be a bit confusing, so let’s take a look at an example.

my_munequita = ['My', 'Spanish', 'Harlem', 'Mona', 'Lisa']


print(' '.join(my_munequita))
# => 'My Spanish Harlem Mona Lisa'
We take the list of strings, my_munequita, and we joined it together with our
delimiter, ' ', which is a space. The space is important if you are trying to build a
sentence from words, otherwise, we would have ended up with:

print(''.join(my_munequita))
# => 'MySpanishHarlemMonaLisa'

Instructions

1.

You’ve been provided with a list of words from the first line of Jean Toomer’s
poem Reapers.

Use .join() to combine these words into a sentence and save that sentence as
the string reapers_line_one.
Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

If you do a join() after a split() using the same delimiter, does this result
in the original string?
Still have questions? View this exercise's thread in the Codecademy Forums.

7/13. Joining Strings II


Joining Strings II

In the last exercise, we joined together a list of words using a space as the
delimiter to create a sentence. In fact, you can use any string as a delimiter to
join together a list of strings. For example, if we have the list

santana_songs = ['Oye Como Va', 'Smooth', 'Black Magic Woman', 'Samba Pa Ti',
'Maria Maria']
We could join this list together with ANY string. One often used string is a
comma , because then we can create a string of comma separated variables, or
CSV.

santana_songs_csv = ','.join(santana_songs)
print(santana_songs_csv)
# => 'Oye Como Va,Smooth,Black Magic Woman,Samba Pa Ti,Maria Maria'
You’ll often find data stored in CSVs because it is an efficient, simple file type
used by popular programs like Excel or Google Spreadsheets.

You can also join using escape sequences as the delimiter. Consider the
following example:

smooth_fifth_verse_lines = ['Well I\'m from the barrio', 'You hear my rhythm on your
radio', 'You feel the turning of the world so soft and slow', 'Turning you \'round
and \'round']

smooth_fifth_verse = '\n'.join(smooth_fifth_verse_lines)

print(smooth_fifth_verse)
This code is taking the list of strings and joining them using a newline \n as the
delimiter. Then it prints the result and produces the output:

Well I'm from the barrio


You hear my rhythm on your radio
You feel the turning of the world so soft and slow
Turning you 'round and 'round

Instructions

1.

You’ve been given a list, winter_trees_lines, that contains all the lines to William
Carlos Williams poem, Winter Trees. You’ve been asked to join together the
strings in the list together into a single string that can be used to display the
full poem. Name this string winter_trees_full.

Print your result to the terminal. Make sure that each line of the poem appears
on a new line in your string.
Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

What if the strings in the list contain the delimiter?

Still have questions? View this exercise's thread in the Codecademy Forums.

8/13. .strip()
.strip()
When working with strings that come from real data, you will often find that
the strings aren’t super clean. You’ll find lots of extra whitespace, unnecessary
linebreaks, and rogue tabs.

Python provides a great method for cleaning strings: .strip(). Stripping a string


removes all whitespace characters from the beginning and end. Consider the
following example:

featuring = "           rob thomas                 "


print(featuring.strip())
# => 'rob thomas'
All the whitespace on either side of the string has been stripped, but the
whitespace in the middle has been preserved.

You can also use .strip() with a character argument, which will strip that
character from either end of the string.

featuring = "!!!rob thomas       !!!!!"


print(featuring.strip('!'))
# => 'rob thomas       '
By including the argument '!' we are able to strip all of the ! characters from
either side of the string. Notice that now that we’ve included an argument we
are no longer stripping whitespace, we are ONLY stripping the argument.

Instructions

1.

They sent over another list containing all the lines to the Audre Lorde
poem, Love, Maybe. They want you to join together all of the lines into a single
string that can be used to display the poem again, but this time, you’ve
noticed that the list contains a ton of unnecessary whitespace that doesn’t
appear in the actual poem.

First, use .strip() on each line in the list to remove the unnecessary whitespace
and save it as a new list love_maybe_lines_stripped.
Stuck? Get a hint

2.
.join() thelines in love_maybe_lines_stripped together into one large multi-line
string, love_maybe_full, that can be printed to display the poem.

Each line of the poem should show up on its own line.


3.

Print love_maybe_full.

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

How to add strings to a list?

2.

List has no attribute: strip? (try a for loop)

3.

My list has every letter separated instead of each line?


Still have questions? View this exercise's thread in the Codecademy Forums.

9/13. Replace
Replace

The next string method we will cover is .replace(). Replace takes two arguments
and replaces all instances of the first argument in a string with the second
argument. The syntax is as follows

string_name.replace(substring_being_replaced, new_substring)
Great! Let’s put it in context and look at an example.

with_spaces = "You got the kind of loving that can be so smooth"


with_underscores = with_spaces.replace(' ', '_')
print(with_underscores)
# 'You_got_the_kind_of_loving_that_can_be_so_smooth'
Here we used .replace() to change every instance of a space in the string above
to be an underscore instead.

Note that in this example, we used a single character, but these substrings can
be multiple characters long!

Instructions

1.

The poetry organization has sent over the bio for Jean Toomer as it currently
exists on their site. Notice that there was a mistake with his last name and all
instances of Toomer are lacking one o.

Use .replace() to change all instances of Tomer in the bio to Toomer. Save the
updated bio to the string toomer_bio_fixed.

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!
Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

Does the character being replaced in .replace() have to be nonempty?

Still have questions? View this exercise's thread in the Codecademy Forums.

10/13. .find()
.find()

Another interesting string method is .find(). .find() takes a string as an argument


and searching the string it was run on for that string. It then returns the
first index value where that string is located.

Here’s an example:

print('smooth'.find('t'))
# => '4'
We searched the string 'smooth' for the string 't' and found that it was at the
fourth index spot, so .find() returned 4.

You can also search for larger strings, and .find() will return the index value of
the first character of that string.

print("smooth".find('oo'))
# => '2'
Notice here that 2 is the index of the first o.

Instructions

1.
In the code editor is the first line of Gabriela Mistral’s poem God Wills It.

At what index place does the word “disown” appear? Save that index place to
the variable disown_placement.

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

How can I find all indices where a substring appears in a string?

2.

What causes .find() to return -1?

Still have questions? View this exercise's thread in the Codecademy Forums.

11/13. .format()
.format()

Python also provides a handy string method for including variables in strings.
This method is .format(). .format() takes variables as an argument and includes
them in the string that it is run on. You include {} marks as placeholders for
where those variables will be imported.

Consider the following function:

def favorite_song_statement(song, artist):


  return "My favorite song is {} by {}.".format(song, artist)
The function favorite_song_statement takes two arguments, song and artist, then
returns a string that includes both of the arguments and prints a sentence.
Note: .format() can take as many arguments as there are {} in the string it is run
on, which in this case is two.

Here’s an example of the function being run:

print(favorite_song_statement("Smooth", "Santana"))
# => "My favorite song is Smooth by Santana."
Now you may be asking yourself, I could have written this function using
string concatenation instead of .format(), why is this method better? The answer
is legibility and reusability. It is much easier to picture the end
result .format() than it is to picture the end result of string concatenation and
legibility is everything. You can also reuse the same base string with different
variables, allowing you to cut down on unnecessary, hard to interpret code.

Instructions

1.

Write a function called poem_title_card that takes two inputs: the first input


should be title and the second poet. The function should use .format() to return
the following string:

The poem "[TITLE]" is written by [POET].


For example, if the function is given the inputs

poem_title_card("I Hear America Singing", "Walt Whitman")


It should return the string

The poem "I Hear America Singing" is written by Walt Whitman.


Stuck? Get a hint
Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

Can we provide any input type to the format() method?

2.

What are the backslashes in the string?

3.

What are good reasons to use string formatting?

Still have questions? View this exercise's thread in the Codecademy Forums.

12/13. Format() II
.format() II
.format() can
be made even more legible for other people reading your code by
including keywords. Previously, with .format(), you had to make sure that your
variables appeared as arguments in the same order that you wanted them to
appear in the string, which added unnecessary complications when writing
code.

By including keywords in the string, and in the arguments, you can remove
that ambiguity. Let’s look at an example.

def favorite_song_statement(song, artist):


  return "My favorite song is {song} by {artist}.".format(song=song, artist=artist)
Now it is clear to anyone reading the string what it is supposed to return, they
don’t even need to look at the arguments of .format() in order to get a clear
understanding of what is supposed to happen. You can even reverse the order
of artist and song in the code above and it will work the same way.

For example, if the arguments of .format() are in a different order, the code will
still work since the keywords are present:

def favorite_song_statement(song, artist):


  # this will have the same output as the above example
  return "My favorite song is {song} by {artist}.".format(artist=artist, song=song)
This makes writing AND reading the code much easier.

Instructions

1.

The function poem_description is supposed to use .format() to print out some quick


information about a poem, but it seems to be causing some errors currently.

Fix the function by using keywords in the .format() method.


2.

Run poem_description with the following arguments and save the results to the


variable my_beard_description:

author = "Shel Silverstein"


title = "My Beard"
original_work = "Where the Sidewalk Ends"
publishing_date = "1974"

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

Can we utilize both keyword and positional arguments in the format()


method?

2.

Do we need to define the variables seperately?

Still have questions? View this exercise's thread in the 

13/13. Review
Review

Excellent work! This lesson has shown you the vast variety of string methods
and their power. Whatever the problem you are trying to solve, if you are
working with strings then string methods are likely going to be part of the
solution.
Over this lesson you’ve learned:

 .upper(), .title(),
and .lower() adjust the casing of your string.
 .split() takes a string and creates a list of substrings.
 .join() takes a list of strings and creates a string.
 .strip() cleans off whitespace, or other noise from the beginning and end
of a string.
 .replace() replaces all instances of a character/string in a string with
another character/string.
 .find() searches a string for a character/string and returns the index value
that character/string is found at.
 .format() allows you to interpolate a string with variables.

Well I’ve been stringing you along for long enough, let’s get some more
practice in!

Instructions

1.

Preserve the Verse has one final task for you. They have delivered you a string
that contains a list of poems, titled highlighted_poems, they want to highlight on
the site, but they need your help to parse the string into something that can
display the name, title, and publication date of the highlighted poems on the
site.

First, start by printing highlighted_poems to the terminal and see how it displays.


2.

The information for each poem is separated by commas, and within this
information is the title of the poem, the author, and the date of publication.

Start by splitting highlighted_poems at the commas and saving it


to highlighted_poems_list.
Stuck? Get a hint

3.

Print highlighted_poems_list, how does the structure of the data look now?


4.

Notice that there is inconsistent whitespace in highlighted_poems_list. Let’s clean


that up.

Start by creating a new empty list, highlighted_poems_stripped.

Then, iterate through highlighted_poems_list using a for loop and for each poem


strip away the whitespace and append it to your new
list, highlighted_poems_stripped.
Stuck? Get a hint

5.

Print highlighted_poems_stripped.

Looks good! All the whitespace is cleaned up.


6.

Next we want to break up all the information for each poem into it’s own list,
so we end up with a list of lists.

Create a new empty list called highlighted_poems_details.


7.

Iterate through highlighted_poems_stripped and split each string around


the : characters and append the new lists into highlighted_poems_details.
8.

Great! Now we want to separate out all of the titles, the poets, and the
publication dates into their own lists.

Create three new empty lists, titles, poets, and dates.


9.

Iterate through highlighted_poems_details and for each list in the list append the


appropriate elements into the lists titles, poets, and dates.
For example, for the poem The Shadow (1915) by William Carlos Williams your
code should be adding "The Shadow" to titles, "William Carlos Williams" to poets,
and "1915" to dates.
10.

Finally, write a for loop that uses .format() to print out the following string for
each poem:

The poem TITLE was published by POET in DATE.

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

What other string methods are there?

2.

How can we reference the right index if all our lists are separate? (step
10)

3.

What if I use += instead of append?


Still have questions? View this exercise's thread in the Codecademy Forums.

D. String methods
E. Thread shed
Thread Shed

You’ve recently been hired as a cashier at the local sewing hobby


shop, Thread Shed. Some of your daily responsibilities involve tallying the
number of sales during the day, calculating the total amount of money made,
and keeping track of the names of the customers.

Unfortunately, the Thread Shed has an extremely outdated register system


and stores all of the transaction information in one huge unwieldy string
called daily_sales.

All day, for each transaction, the name of the customer, amount spent, types
of thread purchased, and the date of sale is all recorded in this same string.
Your task is to use your Python skills to iterate through this string and clean
up each transaction and store all the information in easier-to-access lists.

If you get stuck during this project or would like to see an experienced
developer work through it, click “Get Unstuck“ to see a project walkthrough
video.

Tasks

22/22 Complete

Mark the tasks as complete by checking them off


Break up `daily_sales` in easy to understand lists `customers`, `sales`, and
`thread_sold`.
1.
First, take a minute to inspect the string daily_sales in the code editor.

How is each transaction stored? How is each piece of data within the
transaction stored?

Start thinking about how we can split up this string into its individual pieces of
data.
2.

It looks like each transaction is separated from the next transaction by a ,, and
then each piece of data within a transaction is separated by the artifact ;,;.

If we want to split up daily_sales into a list of individual transactions, we are


going to want to split by ,, but first, we need to replace the artifact ;,; to
something without a comma, so we don’t split any transactions themselves.

Replace all the instances of ;,; in daily_sales with some other character and save
the result to daily_sales_replaced.
Stuck? Get a hint

3.

Now we can split the string into a list of each individual transaction.

Split daily_sales_replaced around commas and save it to a new list daily_transactions.


Stuck? Get a hint

4.

Print daily_transactions.

How does it look?


5.

Our next step is to split each individual transaction into a list of its data points.

First, define an empty list daily_transactions_split


6.
Now, iterate through daily_transactions (remember, this is a list of strings
currently), and for each transaction, split the string around whatever character
you replaced the ;,; artifacts with in Step 2.

Append each of these split strings (which are lists now) to our new
list daily_transactions_split.
Stuck? Get a hint

7.

Print daily_transactions_split.

How’s it looking?
8.

It looks like each data item has inconsistent whitespace around it. First, define
an empty list transactions_clean.

Now, Iterate through daily_transactions_split and for each transaction iterate


through the different data points and strip off any whitespace.

Add each of these cleaned up transactions to the new list transactions_clean.


Stuck? Get a hint

9.

Print transactions_clean.

If you performed the last step correctly, you shouldn’t see any unnecessary
whitespace.
10.

Create three empty lists. customers, sales, and thread_sold. We are going to collect


the individual data points for each transaction in these lists.
11.

Now, iterate through transactions_clean and for each transaction:

1. Append the customers name to customers.


2. Append the amount of the sale to sales.
3. Append the threads sold to thread_sold.

12.

Print customers, sales, and thread_sold to make sure each list is what you are


expected.
Determine the total value of the days sales.
13.

Now we want to know how much Thread Shed made in a day.

First, define a variable called total_sales and set it equal to 0.


14.

Now, consider the list sales. It is a list of strings that we want to sum. In order


for us to sum these values, we will have to remove the $, and set them equal to
floats.

Iterate through sales and for each item, strip off the $, set it equal to a float, and
add it to total_sales
15.

Print total_sales.

How much did we make today?


How much thread of any specific color was sold?
16.

Finally, we want to determine how many of each color thread we sold today.
Let’s start with a single color, and then we’ll generalize it.

First, print out thread_sold and inspect it.


17.

We see that thread_sold is a list of strings, some are single colors and some are
multiple colors separated by the & character.

The end product we want here is a list that contains an item for each color
thread sold, so no strings that have multiple colors in them.
First, define an empty list thread_sold_split.
18.

Next, iterate through thread_sold. For each item, check if it is a single color or
multiple colors. If it is a single color, append that color to thread_sold_split.

If it is multiple colors, first split the string around the & character and then add
each color individually to thread_sold_split.
19.

Great, now we have a list thread_sold_split that contains an entry with the color of


every thread sold today.

Define a function called color_count that takes one argument, color. The function


should iterate through thread_sold_split and count the number of times the item is
equal to argument, color. Then, it should return this count.
20.

Test your new function by running color_count('white').

Your function should return 28.


21.

Define a list called colors that stores all of the colored threads that Thread


Shed offers:

colors = ['red', 'yellow', 'green', 'white', 'black', 'blue', 'purple']


22.

Now, using the string method .format() and the function color_count(), iterate


through the list colors and print a sentence that says how many threads of each
color were sold today.

F. Off-platform project: Coded correspondence


VI. Modules
A. Modules in python
1/6. Modules Python Introduction
Modules Python Introduction

In the world of programming, we care a lot about making code reusable. In


most cases, we write code so that it can be reusable for ourselves. But
sometimes we share code that’s helpful across a broad range of situations.

In this lesson, we’ll explore how to use tools other people have built in Python
that are not included automatically for you when you install Python. Python
allows us to package code into files or sets of files called modules.

A module is a collection of Python declarations intended broadly to be used


as a tool. Modules are also often referred to as “libraries” or “packages” — a
package is really a directory that holds a collection of modules.

Usually, to use a module in a file, the basic syntax you need at the top of that
file is:

from module_name import object_name


Often, a library will include a lot of code that you don’t need that may slow
down your program or conflict with existing code. Because of this, it makes
sense to only import what you need.

One common library that comes as part of the Python Standard Library
is datetime. datetime helps you work with dates and times in Python.

Let’s get started by importing and using the datetime module. In this case, you’ll
notice that datetime is both the name of the library and the name of the object
that you are importing.

Instructions

1.

In script.py import the datetime type from the datetime library.


Checkpoint 2 Passed

2.
Create a variable current_time and set it equal to datetime.now().
Checkpoint 3 Passed

3.

Print out current_time.
Checkpoint 4 Passed

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

How can we see all the objects and functions in a module?

2.

Why doesn’t datetime.now() match with the current time?

Still have questions? View this exercise's thread in the Codecademy Forums.

2/6. Modules Python Random


Modules Python Random

datetime is
just the beginning. There are hundreds of Python modules that you
can use. Another one of the most commonly used is random which allows you to
generate numbers or select items at random.
With random, we’ll be using more than one piece of the module’s functionality,
so the import syntax will look like:

import random
We’ll work with two common random functions:

 random.choice() which takes a list as an argument and returns a number


from the list
 random.randint() which
takes two numbers as arguments and generates a
random number between the two numbers you passed in

Let’s take randomness to a whole new level by picking a random number from
a list of randomly generated numbers between 1 and 100.

Instructions

1.

In script.py import the random library.
Stuck? Get a hint

2.

Create a variable random_list and set it equal to an empty list


3.

Turn the empty list into a list comprehension that uses random.randint() to


generate a random integer between 1 and 100 (inclusive) for each number
in range(101).
Stuck? Get a hint

4.

Create a new variable randomer_number and set it equal


to random.choice() with random_list as an argument.
5.

Print randomer_number out to see what number was picked!

Concept Review
Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

What other useful methods does the random module provide?

2.

When do we need from and import vs just import?

3.

What does random.randint() do?

Still have questions? View this exercise's thread in the Codecademy Forums.

3/6. Modules Python Namespaces


Modules Python Namespaces
Notice that when we want to invoke the randint() function we call random.randint().
This is default behavior where Python offers a namespace for the module. A
namespace isolates the functions, classes, and variables defined in the module
from the code in the file doing the importing. Your local namespace,
meanwhile, is where your code is run.

Python defaults to naming the namespace after the module being imported,
but sometimes this name could be ambiguous or lengthy. Sometimes, the
module’s name could also conflict with an object you have defined within your
local namespace.

Fortunately, this name can be altered by aliasing using the as keyword:

import module_name as name_you_pick_for_the_module


Aliasing is most often done if the name of the library is long and typing the
full name every time you want to use one of its functions is laborious.

You might also occasionally encounter import *. The * is known as a “wildcard”


and matches anything and everything. This syntax is considered dangerous
because it could pollute our local namespace. Pollution occurs when the same
name could apply to two possible things. For example, if you happen to have a
function floor() focused on floor tiles, using from math import * would also import a
function floor() that rounds down floats.

Let’s combine your knowledge of the random library with another fun library


called matplotlib, which allows you to plot your Python code in 2D.

You’ll use a new random function random.sample() that takes a range and a number


as its arguments. It will return the specified number of random numbers from
that range.

#random.sample takes a list and randomly selects k items from it


new_list = random.sample(list, k)
#for example:
nums = [1, 2, 3, 4, 5]
sample_nums = random.sample(nums, 3)
print(sample_nums) # 2, 5, 1
Instructions

1.

Below import codecademylib3_seaborn, import pyplot from the module matplotlib with the


alias plt.
Stuck? Get a hint

2.

Import random below the other import statements. It’s best to keep all imports
at the top of your file.
3.

Create a variable numbers_a and set it equal to the range of numbers 1 through


12 (inclusive).
4.

Create a variable numbers_b and set it equal to a random sample of twelve


numbers within range(1000).

Feel free to print numbers_b to see your random sample of numbers.


5.

Now let’s plot these number sets against each other using plt. Call plt.plot() with
your two variables as its arguments.
6.

Now call plt.show() and run your code!

You should see a graph of random numbers displayed. You’ve used two
Python modules to accomplish this (random and matplotlib).

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums
Here are some helpful links to the top questions asked by coders about this
exercise:

1.

What happens if I import an module or function that conflicts with an


object defined in my local namespace?

2.

What is the codecademylib3_seaborn module?

Still have questions? View this exercise's thread in the Codecademy Forums.

4/6. Modules Python Decimals


Modules Python Decimals

Let’s say you are writing software that handles monetary transactions. If you
used Python’s built-in floating-point arithmetic to calculate a sum, it would
result in a weirdly formatted number.

cost_of_gum = 0.10
cost_of_gumdrop = 0.35

cost_of_transaction = cost_of_gum + cost_of_gumdrop


# Returns 0.44999999999999996
Being familiar with rounding errors in floating-point arithmetic you want to
use a data type that performs decimal arithmetic more accurately. You could
do the following:
from decimal import Decimal

cost_of_gum = Decimal('0.10')
cost_of_gumdrop = Decimal('0.35')

cost_of_transaction = cost_of_gum + cost_of_gumdrop


# Returns 0.45 instead of 0.44999999999999996
Above, we use the decimal module’s Decimal data type to add 0.10 with 0.35.
Since we used the Decimal type the arithmetic acts much more as expected.

Usually, modules will provide functions or data types that we can then use to
solve a general problem, allowing us more time to focus on the software that
we are building to solve a more specific problem.

Ready, set, fix some floating point math by using decimals!

Instructions

1.

Run your code to see the weird floating point math that occurs.
2.

In script.py import Decimal from the decimal module.
3.

Use Decimal to make two_decimal_points only have two decimals points


and four_decimal_points to only have four decimal points.
Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:
1.

Can we perform calculations between Decimal objects and other values?

2.

How can we control the rounding of our equation?

Still have questions? View this exercise's thread in the Codecademy Forums.

5/6. Modules Python Files and Scope


Modules Python Files and Scope

You may remember the concept of scope from when you were learning about
functions in Python. If a variable is defined inside of a function, it will not be
accessible outside of the function.

Scope also applies to classes and to the files you are working within.

Files have scope? You may be wondering.

Yes. Even files inside the same directory do not have access to each other’s
variables, functions, classes, or any other code. So if I have a
file sandwiches.py and another file hungry_people.py, how do I give my
hungry people access to all the sandwiches I defined?

Well, files are actually modules, so you can give a file access to another file’s
content using that glorious import statement.
With a single line of from sandwiches import sandwiches at the top
of hungry_people.py, the hungry people will have all the sandwiches they
could ever want.

Instructions

1.

Tab over to library.py and define a function always_three() with no parameters


that returns 3.
Stuck? Get a hint

2.

Call your always_three() function in script.py. Check out that error message you


get in the output terminal and the consequences of file scope.
3.

Resolve the error with an import statement at the top of script.py that


imports your function from library. Run your code and watch import do its magic!
Stuck? Get a hint

Concept Review

Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!

Community Forums

Here are some helpful links to the top questions asked by coders about this
exercise:

1.

Do imported files always have to be in the same directory?

Still have questions? View this exercise's thread in the Codecademy Forums.


6/6. Modules Python Review
Modules Python Review
You’ve learned:

 what modules are and how they can be useful


 how to use a few of the most commonly used Python libraries
 what namespaces are and how to avoid polluting your local namespace
 how scope works for files in Python

Programmers can do great things if they are not forced to constantly reinvent
tools that have already been built. With the power of modules, we can import
any code that someone else has shared publicly.

In this lesson, we covered some of the Python Standard Library, but you can
explore all the modules that come packaged with every installation of Python
at the Python Standard Library documentation.

This is just the beginning. Using a package manager (like conda or pip3), you
can install any modules available on the Python Package Index.

The sky’s the limit!


B. Learn Python: Datetimes
Video:
- Học về cách sử dụng hàm datetime():
+ import module datetime và sử dụng:
from datetime import datetime
birthday = datetime(2001, 11, 1, 4, 44, 44) #gán đối tượng datetime cho biến
birthday với các argument tương ứng ( năm, tháng, ngày, giờ, phút, giây)
birthday.year # in ra năm
birthday.month #phương thức
birthday.weekday() # in ra chỉ mục của ngày trong 1 tuần
>> 3 #Thứ 4 – Wednesday
birthday.now() # trả về ngày giờ hiện tại
# ta có thể dùng toán tử trừ cho đối tượng datetime, say,

C. Learn Python: pipenv

You might also like