Learn Python 3
Learn Python 3
my_name = "Codecademy"
print("Hello and welcome " + my_name + "!")
Output:
1/15
# This variable will be used to count the number of times anyone tweets the word persnickety
persnickety_count = 0
# This code will calculate the likelihood that it will rain tomorrow
complicated_rain_calculation_for_tomorrow()
Ignore a line of code and see how a program will run without it:
# useful_value = old_sloppy_code()
useful_value = new_clean_code()
Instructions
1. Documentation is an important step in programming. Write a comment describing the
first program you want to write!
2/15
In the above example, we direct our program to print() an excerpt from a notable book. The
printed words that appear as a result of the print() function are referred to as output. The
output of this example program would be:
Instructions
1. Print the distinguished greeting “Hello world!”
Fullscreen Code Editor
print('Hello, world!')
Output:
Hello, world!
3/15
print('Luiz')
print("Luiz F")
Output:
Luiz
Luiz F
4/15
In the above example, we store the message “Hello there” in a variable called
message_string. Variables can’t have spaces or symbols in their names other than an
underscore (_). They can’t begin with numbers but they can have numbers after the first letter
(e.g., cool_variable_5 is OK).
It’s no coincidence we call these creatures “variables”. If the context of a program changes,
we can update a variable but perform the same logical process on it.
# Greeting
message_string = "Hello there"
print(message_string)
# Farewell
message_string = "Hasta la vista"
print(message_string)
Above, we create the variable message_string, assign a welcome message, and print the
greeting. After we greet the user, we want to wish them goodbye. We then update
message_string to a departure message and print that out.
Instructions
1. Update the variable meal to reflect each meal of the day before we print it.
Fullscreen Code Editor
# We've defined the variable "meal" here to the name of the food we ate
for breakfast!
meal = "An english muffin"
# Printing out breakfast
print("Breakfast:")
print(meal)
# Now update meal to be lunch!
meal = "Brown beens with rice"
# Printing out lunch
print("Lunch:")
print(meal)
# Now update "meal" to be dinner
meal = "Bread with botter"
# Printing out dinner
print("Dinner:")
print(meal)
Output:
Breakfast:
An english muffin
Lunch:
Brown beens with rice
Dinner:
Bread with botter
5/15
6/15
an_int = 2
a_float = 2.1
print(an_int + 3)
# Output: 5
Above we defined an integer and a float as the variables an_int and a_float. We printed out
the sum of the variable an_int with the number 3. We call the number 3 here a literal,
meaning it’s actually the number 3 and not a variable with the number 3 assigned to it.
Floating-point numbers can behave in some unexpected ways due to how computers store
them. For more information on floating-point numbers and Python, review Python’s
documentation on floating-point limitations.
Instructions
1. A recent movie-going experience has you excited to publish a review. You rush
out of the cinema and hastily begin programming to create your movie-review
website: The Big Screen’s Greatest Scenes Decided By A Machine.
Create the following variables and assign integer numbers to them: release_year and runtime.
2. Now, create the variable rating_out_of_10 and assign it a float number between
one and ten.
7/15
# Prints "500"
print(573 - 74 + 1)
# Prints "50"
print(25 * 2)
# Prints "2.0"
print(10 / 5)
Notice that when we perform division, the result has a decimal place. This is because Python
converts all ints to floats before performing division. In older versions of Python (2.7 and
earlier) this conversion did not happen, and integer division would always round down to the
nearest integer.
Division can throw its own special error: ZeroDivisionError. Python will raise this error when
attempting to divide by 0.
Mathematical operations in Python follow the standard mathematical order of operations.
Instructions
1. Print out the result of this equation: 25 * 68 + 13 / 28
Fullscreen Code Editor
eq = 25 * 68 + 13 / 28
print(eq)
Output:
1700.4642857142858
8/15
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)
# Prints "8.0"
print(coffee_price * number_of_coffees)
# Prints "2.0"
print(coffee_price)
# Prints "4"
print(number_of_coffees)
We create two variables and assign numeric values to them. Then we perform a calculation on
them. This doesn’t update the variables! When we update the coffee_price variable and
perform the calculations again, they use the updated values for the variable!
Instructions
1. You’ve decided to get into quilting! To calculate the number of squares you’ll need for
your first quilt let’s create two variables: quilt_width and quilt_length. Let’s make this
first quilt 8 squares wide and 12 squares long.
2. Print out the number of squares you’ll need to create the quilt!
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?
Fullscreen Code Editor
#You’ve decided to get into quilting! To calculate the number of squares
quilt_length = 12
squares = quilt_width * quilt_length
print(squares)
#It turns out that quilt required a little more material than you have on
squares = quilt_width * quilt_length
quilt_width = 8
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
#Print out the number of squares you’ll need to create the quilt!
hand! Let’s only make the quilt 8 squares long.
print(squares)
quilt_length = 8
# How many squares will you need for this quilt instead?
Output:
96
64
9/15
# 8 squared, or 64
print(8 ** 2)
# 9 * 9 * 9, 9 cubed, or 729
print(9 ** 3)
Here, we compute some simple exponents. We calculate 2 to the 10th power, 8 to the 2nd
power, 9 to the 3rd power, and 4 to the 0.5th power.
Instructions
1. You really like how the square quilts from last exercise came out, and decide that all
quilts that you make will be square from now on.
Using the exponent operator, print out how many squares you’ll need for a 6x6 quilt, a 7x7
quilt, and an 8x8 quilt.
2. Your 6x6 quilts have become so popular that 6 people have each requested 6 quilts.
Print out how many total tiles you would need to make 6 6x6 quilts for 6 people.
Fullscreen Code Editor
Output:
36
49
64
1296
10/15
Here, we use the modulo operator to find the remainder of division operations. We see that 29
% 5 equals 4, 32 % 3 equals 2, and 44 % 2 equals 0.
Let’s look at another example to get a better idea of how modulo is useful in programming:
print(3 % 3) # Prints 0
print(4 % 3) # Prints 1
print(5 % 3) # Prints 2
print(6 % 3) # Prints 0
print(7 % 3) # Prints 1
In each of these modulo operations, 3 is the divisor. Since 3 / 3 equals 1 with no remainder,
the result of the first modulo operation is 0. Note that as the dividend increases by 1, the
remainder also increases by 1, until we reach the next number that is evenly divisible by 3 —
this creates a pattern that repeats contiuously as the dividend increases by 1!
Because of this, the modulo operator is useful in programming when we want to perform an
action every nth time something occurs. Imagine you own a small café and would like for
every 7th customer to receive a survey. If every customer transaction is numbered in the
order they occur, you can determine which customers should receive the survey by
calculating transaction_number % 7 — if the result is 0, hand out the survey!
Instructions
1. You are starting a new campaign for your online shop where every 10th customer gets
10% off their next order. To easily calculate this, you decide that order numbers
divisible by 10 will receive the coupon.
Here comes the first order of the day, #269!
Create a new variable, first_order_remainder and set it equal to 269 modulo 10.
Then, print out first_order_remainder to find out if that customer will receive a discount.
2. Look at the printed value of first_order_remainder. Was the remainder 0, meaning that
the customer should receive a coupon for this order?
Create a new variable called first_order_coupon and assign to it a value of "yes" if the order
should get a coupon. Otherwise, give first_order_coupon the value of "no".
Extra Guidance
If two numbers are divisible, the remainder will be 0. In this case, if the remainder is 0, then
the order number is divisible by 10, and that order should receive a coupon.
3. Here comes the second order of the day, #270! Let’s see if they will get a discount!
Find the remainder by calculating 270 modulo 10 and store the result in a new variable
named second_order_remainder.
Then, print out second_order_remainder.
4. Based on the printed value of second_order_remainder, should the customer receive a
coupon for this order?
Create a new variable named second_order_coupon and give it a value of "yes" if the order
should get a coupon. Otherwise, give second_order_coupon the value of "no".
Fullscreen Code Editor
first_order_remainder = 269 % 10
print(first_order_remainder)
if first_order_remainder == 0:
first_order_coupon = "yes"
else:
first_order_coupon = "no"
second_order_remainder = 270 % 10
print(second_order_remainder)
if second_order_remainder == 0:
second_order_coupon = "yes"
else:
second_order_coupon = "no"
Output:
9
0
11/15
In this sample of code, we create two variables that hold strings and then concatenate them.
But we notice that the result was missing a space between the two, let’s add the space in-
between using the same concatenation operator!
# Concatenating an integer with strings is possible if we turn the integer into a string first
full_birthday_string = birthday_string + str(age) + birthday_string_2
# Prints "I am 10 years old today!"
print(full_birthday_string)
Using str() we can convert variables that are not strings to strings and then concatenate
them. But we don’t need to convert a number to a string for it to be an argument to a print
statement.
Instructions
1. Concatenate the strings and save the message they form in the variable message.
Now uncomment the print statement and run your code to see the result in the terminal!
Fullscreen Code Editor
12/15
Above, we keep a running count of the number of miles a person has gone hiking over time.
Instead of recalculating from the start, we keep a grand total and update it when we’ve gone
hiking further.
The plus-equals operator also can be used for string concatenation, like so:
We create the social media caption for the photograph of nature we took on our hike, but then
update the caption to include important social media tags we almost forgot.
Instructions
1. We’re doing a little bit of online shopping and find a pair of new sneakers. Right before
we check out, we spot a nice sweater and some fun books we also want to purchase!
Use the += operator to update the total_price to include the prices
of nice_sweater and fun_books.
The prices (also included in the workspace) are:
o new_sneakers = 50.00
o nice_sweater = 39.00
o fun_books = 20.00
Fullscreen Code Editor
total_price = 0
new_sneakers = 50.00
total_price += new_sneakers
nice_sweater = 39.00
fun_books = 20.00
# Update total_price here:
total_price += nice_sweater
total_price += fun_books
print("The total price is", total_price)
Output:
13/15
leaves_of_grass = """
Poets to come! orators, singers, musicians to come!
Not to-day is to justify me and answer what I am for,
But you, a new brood, native, athletic, continental, greater than
before known,
Arouse! for you must justify me.
"""
In the above example, we assign a famous poet’s words to a variable. Even though the quote
contains multiple linebreaks, the code works!
If a multi-line string isn’t assigned a variable or used in an expression it is treated as a
comment.
Instructions
1. Assign the string
14/15
my_age = 40
half_my_age = my_age / 2
greeting = "Olá!!!"
name = "Luiz"
greeting_with_name = name + ", " + greeting
print(greeting_with_name)
Output:
Luiz, Olá!!!
15/15
User Input
How to assign variables with user input.
So far, we’ve covered how to assign variables values directly in a Python file. However, we
often want a user of a program to enter new information into the program.
How can we do this? As it turns out, another way to assign a value to a variable is through
user input.
While we output a variable’s value using print(), we assign information to a variable
using input(). The input() function requires a prompt message, which it will print out for the
user before they enter the new information. For example:
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:
>>> 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.
Control Flow: Introduction to Control Flow
Introduction to Control Flow
Imagine waking up in the morning.
You wake up and think, “Ugh. Is it a weekday?”
If so, you have to get up and get dressed and get ready for work or school. If not, you can
sleep in a bit longer and catch a couple extra Z’s. But alas, it is a weekday, so you are up and
dressed and you go to look outside, “What’s the weather like? Do I need an umbrella?”
These questions and decisions control the flow of your morning, each step and result is a
product of the conditions of the day and your surroundings. Your computer, just like you, goes
through a similar flow every time it executes code. A program will run (wake up) and start
moving through its checklists, is this condition met, is that condition met, okay let’s execute
this code and return that value.
This is the control flow of your program. In Python, your script will execute from the top down,
until there is nothing left to run. It is your job to include gateways, known as conditional
statements, to tell the computer when it should execute certain blocks of code. If these
conditions are met, then run this function.
Over the course of this lesson, you will learn how to build conditional statements using
boolean expressions, and manage the control flow in your code.
1/12
Today is a weekday.
This expression can be true - if today is Tuesday, for example - or false if it’s a weekend. There
are no other options, we know the answer is verifiable, and it does not rely on an opinion.
Now, consider the following phrase:
Yes, this is a Boolean expression since the answer can only be true or false and it is verifiable.
Even though the statement itself is false (Sunday starts with the letter ‘S’ and not ‘C’), it is
still a Boolean expression.
2/12