Khóa Học Python
Khóa Học Python
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.
2.
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:
# 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
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.
2.
3.
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:
Instructions
1.
Print the distinguished greeting “Hello world!”
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.
2.
How can I use quotes inside of a string?
3.
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
Try running your code again after switching the type of quote-marks. Is
anything different about the output?
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.
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 (=).
# 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.
2.
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.
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.
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.
2.
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.
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.
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.
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.
# 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.
Instructions
1.
Print out the result of this equation: 25 * 68 + 13 / 28
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. 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)
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.
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 **.
# 8 squared, or 64
print(8 ** 2)
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
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.
3.
In this exercise, the exponent operator is used for positive exponents.
Does exponentiation work with negative exponents as well?
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.
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
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.
2.
3.
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).
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.
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.
3.
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.
The plus-equals operator also can be used for string concatenation, like so:
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!
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.
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!
Instructions
1.
Assign the string
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.
2.
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!
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
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.
3.
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.
Block Letters
ASCII art is a graphic design technique that uses computers for presentation
and consists of pictures pieced together from individual characters.
Tasks
5/5 Complete
Take a look at the complete alphabet and find your initials. Notice how each
block letter is 7x5 and formed by the letter itself.
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.
3.
Output your first initial as a block letter. There are a few ways to do this!
4.
Don’t forget to check off all the tasks before moving on.
Sample solutions:
initials.py
snowman.py
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
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.
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.
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.
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.
V.
Make the Most of Your Codecademy Membership
Mobile App
Keep practicing and stay sharp as you go with our mobile app
on iOS and Android.
Workspaces
Cheatsheets
Docs
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.
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.
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.
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.
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.
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
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.
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 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
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.
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
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.
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.
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:
Statement one:
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.
2.
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
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?
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.
Equals: ==
Not equals: !=
These operators compare two items and return True or False if they are equal or
not.
2 != 4 # True
3 == 5 # False
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:
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.
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!”
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.
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.
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.
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
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
Update the program with a second if statement so it checks for Angela’s user name as well and
prints
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?
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:
1.
Create an if statement that checks if x and y are equal, print the string below if
so:
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.
2.
Do I need to be utilizing return or print?
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.
and
or
not
and combines
two boolean expressions and evaluates as True if both its
components are True, but False otherwise.
Instructions
1.
Set the variables statement_one and statement_two equal to the results of the
following boolean expressions:
Statement one:
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.
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.
2.
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.
Instructions
1.
Set the variables statement_one and statement_two equal to the results of the
following boolean expressions:
Statement one:
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).
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 ?
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.
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:
Instructions
1.
Set the variables statement_one and statement_two equal to the results of the
following boolean expressions:
Statement one:
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.
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.
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.
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:
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.
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.
Instructions
1.
Calvin Coolidge’s Cool College has noticed that students prefer to get letter
grades.
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.
3.
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:
Instructions
Write a space.py program that helps Codey keep track of their target weight
by:
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.
3.
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.
Tasks
15/15 Complete
2.
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.
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!
7.
Then, continue writing elif statements for each of the remaining phrases for the
values 3 to 9.
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.
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:
10.
11.
Run your program several times to see that it’s working as expected.
Stuck? Get a hint
Optional Challenges
12.
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:
We can address this by printing out just the question, such that it looks like
the following:
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!
Don’t forget to check off all the tasks before moving on.
Sample solutions:
magic8.py
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.
Ground Shipping
Drone Shipping
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.
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:
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:
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?
Sample solutions:
shipping.py
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:
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.
Instructions
Concept Review
Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!
Community Forums
Instructions
1.
Examine the existing list heights in your code editor.
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.
3.
Instead of storing each student’s height, we can make a list that contains their
names:
Instructions
1.
Add any additional string to the end of the list ints_and_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.
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.
Instructions
1.
Create an empty list and call it my_empty_list. Don’t put anything in the list just yet.
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.
For this exercise, are there any other options for creating an 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.
print(append_example)
Will output:
Instructions
Concept Review
Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!
Community Forums
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"]
Instructions
1.
Jiho works for a gardening store called Petal Power. Jiho keeps a record of
orders in a list called orders.
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?
print(items_sold)
Would output:
my_list = [1, 2, 3]
my_list + 4
we will get the following error:
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".
Concept Review
Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!
Community Forums
Python lists are zero-indexed. This means that the first element in a list has
index 0, rather than 1.
Element Index
"Juan" 0
"Zofia" 1
"Amare" 2
"Ezio" 3
"Ananya" 4
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
print(employees[8])
What happens? Why?
Checkpoint 3 Passed
In the line of code that you pasted, change 8 to an index that exists so that
you don’t get an IndexError.
Concept Review
Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!
Community Forums
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.
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.
Concept Review
Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!
Community Forums
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.
garden[2] = "Strawberries"
print(garden)
Will output:
garden[-1] = "Raspberries"
print(garden)
Will output:
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
Concept Review
Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!
Community Forums
shopping_line.remove("Chris")
print(shopping_line)
If we examine shopping_line, we can see that it now doesn’t contain "Chris":
# Create a list
shopping_line = ["Cole", "Kip", "Chris", "Sylvana", "Chris"]
# Remove a element
shopping_line.remove("Chris")
print(shopping_line)
Will output:
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"
"Orange", "Apple", "Mango", "Broccoli", "Mango"
Note: Our second store is going to need two orders of mangos so the value is
duplicated.
Let’s see what happens when we try to remove an item that does not exist.
Concept Review
Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!
Community Forums
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:
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
"Aaron" is 15
"Dhruti" is 16
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.
Can a list variable contain items which are also lists of data?
#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]
Instructions
1.
We want to have a way to store all of our classroom test score data.
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!
# 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:
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
Modify the list using double brackets [][] to make the change. Use positive
indices.
Concept Review
Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!
Community Forums
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
Fill our new list preferred_size with the following data, containing the preferred
sizes for Ainsley, Ben, and Chani:
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.
Expedited
Name Size
Shipping
"Ainsley" "Small" True
"Ben" "Large" False
"Medium
"Chani"
" True
"Medium
"Depak"
" False
Change the data value for "Chani"‘s shipping preference to False in our two-
dimensional list to reflect the change.
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
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?
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
Create a list called subjects and fill it with the classes you are taking:
"physics"
"calculus"
"poetry"
"history"
2.
98
97
85
88
3.
"calculus" 97
"poetry" 85
"history" 88
4.
Print gradebook.
Your grade for your computer science class just came in! You got a perfect
score, 100!
6.
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.
You also have your grades from last semester, stored in last_semester_gradebook.
Now that we know how to create and access list data, we can start to explore
additional ways of working with lists.
Here is a preview:
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.
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:
For this example, we can assume that "Karla" is the front of the line and the rest
of the elements are behind her.
store_line.insert(2, "Vikor")
print(store_line)
Would output:
Instructions
2.
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 would like to put "Pineapple" in the front of the list so it is the first item
customers see in the display window.
Note: For this list, the front will be the element at index 0
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
removed_element = cs_topics.pop()
print(cs_topics)
print(removed_element)
Would output:
cs_topics.pop(2)
print(cs_topics)
Would output:
Instructions
1.
Check out the current list of topics we will be studying in our code editor.
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.
3.
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
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().
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.
print(list(my_range))
Would output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Let’s try out using range()!
Instructions
1.
2.
Concept Review
Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!
Community Forums
[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:
[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).
Instructions
1.
Starts at 5
Has a difference of 3 between each item
Ends before 15
Checkpoint 2 Passed
Stuck? Get a hint
2.
Starts at 0
Has a difference of 5 between each item
Ends before 40
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
Length
Often, we’ll need to find the number of items in a list, usually called its length.
my_list = [1, 2, 3, 4, 5]
print(len(my_list))
Would output:
5
Let’s find the length of various lists!
Instructions
1.
2.
Use print() to examine long_list_len.
Checkpoint 3 Passed
3.
4.
Use print() to examine big_range_length.
Checkpoint 5 Passed
5.
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?
Slicing Lists I
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.
2.
3.
Create a new list called middle that contains the middle two items ( ["pants",
"pants"] ) from suitcase.
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 is the end index one higher than the index we want?
Slicing Lists II
Slicing syntax in Python is very flexible. Let’s look at a few more problems we
can tackle with slicing.
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:
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.
print(fruits[:-1])
Would output:
Instructions
1.
2.
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?
Counting in a List
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.
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
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
names.sort()
print(names)
Would output:
.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:
1.
Use .sort() to sort addresses.
Checkpoint 2 Passed
2.
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
4.
5.
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.
2.
3.
Sorting Lists II
print(names)
Would output:
Instructions
1.
2.
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
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.
2.
Select the first element in inventory. Save it to a variable called first.
Checkpoint 3 Passed
3.
4.
5.
6.
7.
Remove the 5th element in the inventory. Save the value to a variable
called removed_item.
Checkpoint 8 Passed
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.
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.
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
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"
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
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.
5.
6.
Use the existing data about the pizza toppings and prices to create a new two-
dimensional list called pizza_and_prices.
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.
9.
10.
A man walks into the pizza store and shouts “I will have your MOST
EXPENSIVE pizza!”
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.
[2.5, "peppers"]
Add the new peppers pizza topping to our list pizza_and_prices.
13.
Three mice walk into the store. They don’t have much money (they’re mice),
but they do each want different pizzas.
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.
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)
Would output:
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
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
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
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:
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.
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.
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.
Before we work with any collection, let’s examine the general structure of
a for loop:
milk
sugar
vanilla extract
dough
chocolate
Some things to note about for loops:
Temporary Variables:
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:
Instructions
1.
2.
3.
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.
2.
Often we won’t be iterating through a specific list (or any collection), but
rather only want to perform a certain action multiple times.
To create arbitrary collections of any length, we can pair our for loops with the
trusty Python built-in function range().
six_steps = range(6)
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.
Instructions
1.
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() ?
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.
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.
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!".
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!
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:
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.
length = len(ingredients)
index = 0
milk
sugar
vanilla extract
dough
chocolate
Let’s use a while loop to iterate through some lists!
Instructions
1.
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.
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.
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:
Concept Review
Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!
Community 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:
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.
Instructions
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.)
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.
2.
3.
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.
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?
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.
items_on_sale = ["blue shirt", "striped socks", "knit dress", "red headband", "dinosaur
onesie"]
print("End of search!")
This would produce the output:
Instructions
1.
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
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
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.
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?
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:
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
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.
Nested Loops
Suppose we are in charge of a science class, that is split into three project
teams:
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.
3.
By the end, you should have the sum of every number in the sales_data nested
list.
Checkpoint 4 Passed
4.
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.
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:
print(doubled)
Would output:
1.
Since the highest score was a 90 we simply want to add 10 points to all the
grades in the list.
Checkpoint 2 Passed
2.
Print scaled_grades.
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.
2.
List Comprehensions are very flexible. We even can expand our examples to
incorporate conditional logic.
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:
Instructions
1.
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.
2.
13. Review
LOOPS
Review
Instructions
1.
2.
Create a for loop that goes through single_digits and prints out each one.
Checkpoint 3 Passed
3.
Before the loop, create a list called squares. Assign it to be an empty list to begin
with.
Checkpoint 4 Passed
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
5.
After the for loop, print out squares.
Checkpoint 6 Passed
6.
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.
Is it possible to have a for loop iterate over a list in reverse order without
changing the list?
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.
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
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.
3.
4.
5.
That average price is more expensive than Carly thought it would be! She
wants to cut all prices by 5 dollars.
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.
9.
10.
After your loop, print the value of total_revenue, so the output looks like:
Carly thinks she can bring in more customers by advertising all of the haircuts
she has that are under 30 dollars.
13.
Print cuts_under_30
V. Functions
A. Introduction to functions
1/13.
INTRODUCTION TO FUNCTIONS
Introduction to Functions
Let’s imagine we were building an application to help people plan trips! When
using a trip planning application we can say a simple procedure could look
like this:
Functions are a convenient way to group our code into reusable blocks. A
function contains a sequence of steps that can be performed repeatedly
throughout a program without having to repeat the process of writing the
same code again.
In this lesson, we are going to explore the idea of a function by slowly building
out a Python program for our trip planning steps!
Instructions
Review the visual for the function navigation_steps().
Concept Review
Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!
Community 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:
print("Setting the Empire State Building as the starting point and Times Square as our
destination.")
If our program now had 100 new people trying to find the best directions
between the Empire State Building and Times Square, we would need to run
each of our three print statements 100 times!
Now, if you’re thinking about using a loop here, your intuition would be totally
right! Unfortunately, we won’t be always traveling between the same two
locations which means a loop won’t be as effective when we want to
customize a trip. We will address this in the upcoming sections!
Instructions
1.
2.
Write the same set of print statements three more times. Run the code again
and see the output.
Checkpoint 3 Passed
3.
Hopefully now you have some perspective about your life without 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
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.
def function_name():
# functions tasks go here
There are some key components we want to note here:
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.
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
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
Concept Review
Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!
Community 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 ( ).
def directions_to_timesSq():
print("Walk 4 mins to 34th St Herald Square train station.")
print("Take the Northbound N, Q, R, or W train 1 stop.")
print("Get off the Times Square 42nd Street stop.")
To call our function, we must type out the function’s name followed by a pair
of parentheses and no indentation:
directions_to_timesSq()
Calling the function will execute the print statements within the body (from the
top statement to the bottom statement) and result in the following output:
Instructions
1.
Call the directions_to_timesSq() function.
2.
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
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).
def trip_welcome():
# Indented code is part of the function body
print("Welcome to Tripcademy!")
print("Let's get you to your destination.")
trip_welcome()
Our trip_welcome() function steps will not print Woah, look at the weather outside! Don't
walk, take the train! on our function call. The print() statement was unindented to
show it was not a part of the function body but rather a separate statement.
Woah, look at the weather outside! Don't walk, take the train! was
printed before
the print() statements from the function trip_welcome().
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.
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:
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
4.
5.
What is different?
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
6/13
INTRODUCTION TO FUNCTIONS
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.
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 argument is the data that is passed in when we call the function and
assigned to the parameter name.
Let’s write a function with parameters and call the function with an argument
to see it all in action!
Instructions
1.
We want to create a program that allows our users to generate the directions
for their upcoming trip!
Note: Since we did not define any code in our function yet, we will receive an
error in our output terminal. Don’t worry, we will be filling in the code in the
next step.
Checkpoint 2 Passed
2.
3.
generate_trip_instructions() should also let our users know they can reach their
location using public transit.
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
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.
Concept Review
Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!
Community Forums
Multiple Parameters
Using a single parameter is useful but functions let us use as many parameters
as we want! That way, we can pass in more than one input to our functions.
We can write a function that takes in more than one parameter by using
commas:
# Calling my_function
my_function(argument1, argument2)
For example take our trip application’s trip_welcome() function that has two
parameters:
The ordering of your parameters is important as their position will map to the
position of the arguments and will determine their assigned value in the
function body (more on this in the next exercise!).
Welcome to Tripcademy
Looks like you are traveling from Prospect Park
And you are heading to Atlantic Terminal
Let’s practice writing and calling a multiple parameter function!
Instructions
1.
Our travel application users want to calculate the total expenses they may
have to incur on a trip.
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
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
3.
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
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
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
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
# 100 is miles_to_travel
# 10 is rate
# 5 is discount
calculate_taxi_price(100, 10, 5)
Alternatively, we can use Keyword Arguments where we explicitly refer to what
each argument is assigned to in the function call. Notice in the code example
below that the arguments do not follow the same order as defined in the
function declaration.
Instructions
1.
Tripcademy (our trusty travel app) needs to allow passengers to plan a trip
(duh).
Note: Since we did not define any code in our function yet, we will receive an
error in our output terminal. Don’t worry, we will be filling in the code in the
next step.
Checkpoint 2 Passed
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
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_destination: "France"
second_destination: "Germany"
Checkpoint 4 Passed
final_destination: "Denmark"
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
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"
6.
1. first_destination: "Brooklyn"
Checkpoint 7 Passed
2. second_destination: "Queens"
Concept Review
Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!
Community Forums
9/13
INTRODUCTION TO FUNCTIONS
There are two distinct categories for functions in the world of Python. What we
have been writing so far in our exercises are called User Defined Functions -
functions that are written by users (like us!).
There is another category called Built-in functions - functions that come built
into Python for us to use. Remember when we were using print or str? Both of
these functions are built into the language for us, which means we have been
using built-in functions all along!
There are lots of different built-in functions that we can use in our programs.
Take a look at this example of using len() to get the length of a string:
destination_name = "Venkatanarasimharajuvaripeta"
28
Here we are using a total of two built-in functions in our example: print(),
and len().
There are even more obscure ones like help() where Python will print a link to
documentation for us and provide some details:
help("string")
Would output (shortened for readability):
NAME
string - A collection of string constants.
MODULE REFERENCE
https://docs.python.org/3.8/library/string
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.
T-shirt: 9.75
Shorts: 15.50
Mug: 5.99
Poster: 2.00
Print max_price.
Checkpoint 2 Passed
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
3.
Concept Review
Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!
Community Forums
10/13
INTRODUCTION TO FUNCTIONS
Variable Access
def trip_welcome(destination):
print(" Looks like you're going to the " + destination + " today. ")
What if we wanted to access the variable destination outside of the function?
Could we use it? Take a second to think about what the following program will
output, then check the result below!
def trip_welcome(destination):
print(" Looks like you're going to the " + destination + " today. ")
print(destination)
Output Results
We call the part of a program where destination can be accessed its scope.
The scope of destination is only inside the trip_welcome().
budget = 1000
print(budget)
trip_welcome()
Our output would be:
1000
Looks like you're going to California
Your budget for this trip is 1000
Here we are able to access the budget both inside the trip_welcome function as
well as our print() statement. If a variable lives outside of any function it can be
accessed anywhere in the file.
We will be exploring the concept of scope more after this entire lesson but for
now, let’s play around!
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
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.
Concept Review
Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!
Community 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.
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.
Instructions
1.
Our travel application is getting really popular. Some of our users have posted
on social media that it would be useful if our application could help them
track their budget during trips. We want to help them track their starting
budget and let them know how much they have left after an expense.
The first parameter will be budget and the second parameter will be expense. Our
function will be taking in a budget value as well as the expense we want to
subtract.
We will want our function to return the budget minus the expense our
travelers are incurring.
Checkpoint 3 Passed
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
4.
5.
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
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):
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:
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.
3.
4.
Concept Review
Want to quickly review some of the concepts you’ve been learning? Take a
look at this material's cheatsheet!
Community Forums
13/13
INTRODUCTION TO FUNCTIONS
Review
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.
2.
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:
3.
1. origin
2. destination
3. estimated_time
4. mode_of_transport
4.
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
B. Introductions to functions
Quiz:
C. Getting ready for physics class
LEARN PYTHON 3
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.
2.
3.
7.
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.
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 "The GE train does X Joules of work over Y meters.", with X replaced
with train_work and Y replaced with train_distance.
Complete this project on your own computer. To do this, you’ll need to install
Python. Follow the directions below, if you’re interested.
6. Follow the steps in the Jupyter Notebook. If you get stuck, you can look
at Reggie_Linear_Regression_Solution.ipynb for the answer.
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
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:
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
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:
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
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:
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
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:
# 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
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
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
# 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
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
# 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
3. Twice As Large
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
# 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
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:
# 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
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
# 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
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
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:
Coding question
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
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
Coding question
#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
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
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
4. More Than N
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
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.
Coding question
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
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
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!
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
Coding question
#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
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
Coding question
#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
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
#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
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
5. Add the rest of the list from the index onto the new list
6. Return the new list
Coding question
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
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
3. If the length is even, then return the average of the middle two numbers
Coding question
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
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).
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!
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:
2. Initialize a counter to 0
4. Within the loop, if any of the numbers are divisible by 10, increment our
counter
Coding question
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
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
Coding question
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
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:
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
Coding question
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
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
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
5. Exponents
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
#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
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!
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
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
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
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:
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
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
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
4. Within the loop, if we find a number greater than our starting maximum,
then replace the maximum with what we found.
Coding question
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
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:
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
Coding question
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
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
#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
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
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:
Coding question
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
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:
Coding question
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
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:
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.
Coding question
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
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:
Coding question
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
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:
4. Calculate the remainder of the modified first input value divided by the
modified second input value (using modulus)
Coding question
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
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
Challenges
We’ve included 5 challenges below. Try to answer all of them and polish up
your problem-solving skills!
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:
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
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
Coding question
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
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:
Coding question
# 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
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:
3. Concatenate the string with the dog’s name and age in dog years
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
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
# 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
VII. Strings
A. introduction to strings
10/12.
INTRODUCTION TO STRINGS
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.
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.
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.
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.
2.
How does the indentation level of return False change the code?
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.
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.
2.
common_letters("banana", "cream")
should return ['a'].
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.
2.
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.
Instructions
1.
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.
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.
2.
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.
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.
Formatting Methods
There are three string methods that can change the casing of a string. These
are .lower(), .upper(), and .title().
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’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.
3.
4.
Print poem_author and poem_author_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.
.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.
Instructions
1.
In the code editor is a string of the first line of the poem Spring Storm by
William Carlos Williams.
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.
2.
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.
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.
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!?)
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.
3.
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
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.
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.
2.
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.
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.
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:
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.
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.
You can also use .strip() with a character argument, which will strip that
character from either end of the string.
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.
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.
2.
3.
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.
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.
10/13. .find()
.find()
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.
2.
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.
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.
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.
2.
3.
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.
For example, if the arguments of .format() are in a different order, the code will
still work since the keywords are present:
Instructions
1.
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.
2.
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.
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.
3.
5.
Print highlighted_poems_stripped.
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.
Great! Now we want to separate out all of the titles, the poets, and the
publication dates into their own lists.
Finally, write a for loop that uses .format() to print out the following string for
each poem:
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.
2.
How can we reference the right index if all our lists are separate? (step
10)
3.
D. String methods
E. Thread shed
Thread Shed
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
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 ;,;.
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.
4.
Print daily_transactions.
Our next step is to split each individual transaction into a list of its data points.
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.
9.
Print transactions_clean.
If you performed the last step correctly, you shouldn’t see any unnecessary
whitespace.
10.
12.
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.
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.
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.
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.
Usually, to use a module in a file, the basic syntax you need at the top of that
file is:
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.
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.
2.
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:
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.
4.
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.
2.
3.
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.
1.
2.
Import random below the other import statements. It’s best to keep all imports
at the top of your file.
3.
Now let’s plot these number sets against each other using plt. Call plt.plot() with
your two variables as its arguments.
6.
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.
2.
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_gum = Decimal('0.10')
cost_of_gumdrop = Decimal('0.35')
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.
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.
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.
2.
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.
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.
2.
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.
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.