0% found this document useful (0 votes)
6 views18 pages

Learn Python 3

Notes from Codecademy course Python

Uploaded by

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

Learn Python 3

Notes from Codecademy course Python

Uploaded by

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

Learn Python 3

Hello World: Welcome


Welcome
Python is a programming language. Like other languages, it gives us a way to communicate
ideas. In the case of a programming language, these ideas are “commands” that people use
to communicate with a computer!
We convey our commands to the computer by writing them in a text file using a programming
language. These files are called programs. Running a program means telling a computer to
read the text file, translate it to the set of operations that it understands, and perform those
actions.
Instructions
Change Codecademy to your name in the script to the right. Run the code to see what it does!
Fullscreen Code Editor

my_name = "Codecademy"
print("Hello and welcome " + my_name + "!")

Output:

Hello and welcome Luiz!

1/15

Hello World: Comments


Comments
Ironically, the first thing we’re going to do is show how to tell a computer to ignore a part of a
program. Text written in a program but not run by the computer is called a comment. Python
interprets anything after a # as a comment.
Comments can:
 Provide context for why something is written the way it is:

# This variable will be used to count the number of times anyone tweets the word persnickety
persnickety_count = 0

 Help other people reading the code understand it faster:

# This code will calculate the likelihood that it will rain tomorrow
complicated_rain_calculation_for_tomorrow()

 Ignore a line of code and see how a program will run without it:
# useful_value = old_sloppy_code()
useful_value = new_clean_code()

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

2/15

Hello World: Print


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

# from Mary Shelley's Frankenstein


print("There is something at work in my soul, which I do not understand.")

In the above example, we direct our program to print() an excerpt from a notable book. The
printed words that appear as a result of the print() function are referred to as output. The
output of this example program would be:

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

Instructions
1. Print the distinguished greeting “Hello world!”
Fullscreen Code Editor

print('Hello, world!')

Output:

Hello, world!

3/15

Hello World: Strings


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.
2. If your print statement uses double-quotes ", change them to single-quotes '. If it uses
single-quotes ', change them to double-quotes ".
Fullscreen Code Editor

print('Luiz')
print("Luiz F")

Output:

Luiz
Luiz F

4/15

Hello World: Variables


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

message_string = "Hello there"


# Prints "Hello there"
print(message_string)

In the above example, we store the message “Hello there” in a variable called
message_string. Variables can’t have spaces or symbols in their names other than an
underscore (_). They can’t begin with numbers but they can have numbers after the first letter
(e.g., cool_variable_5 is OK).
It’s no coincidence we call these creatures “variables”. If the context of a program changes,
we can update a variable but perform the same logical process on it.

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

# Farewell
message_string = "Hasta la vista"
print(message_string)

Above, we create the variable message_string, assign a welcome message, and print the
greeting. After we greet the user, we want to wish them goodbye. We then update
message_string to a departure message and print that out.
Instructions
1. Update the variable meal to reflect each meal of the day before we print it.
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

Hello World: Errors


Errors
Humans are prone to making mistakes. Humans are also typically in charge of creating
computer programs. To compensate, programming languages attempt to understand and
explain mistakes made in their programs.
Python refers to these mistakes as errors and will point to the location where an error
occurred with a ^ character. When programs throw errors that we didn’t expect to encounter
we call those errors bugs. Programmers call the process of updating the program so that it no
longer produces unexpected errors debugging.
Two common errors that we encounter while writing Python are SyntaxError and NameError.
 SyntaxError means there is something wrong with the way your program is written —
punctuation that does not belong, a command where it is not expected, or a missing
parenthesis can all trigger a SyntaxError.
 A NameError occurs when the Python interpreter sees a word it does not recognize.
Code that contains something that looks like a variable but was never defined will
throw a NameError.
Instructions
1. You might encounter a SyntaxError if you open a string with a single quote and end it
with double quotes. Update the string so that it starts and ends with the same
punctuation.
You might encounter a NameError if you try to print a single word string but fail to put any
quotes around it. Python expects the word of your string to be defined elsewhere but can’t
find where it’s defined. Add quotes to either side of the string to squash this bug.
Update the malformed strings in the workspace to all be strings.
Fullscreen Code Editor

print('This message has mismatched quote marks!")


print(Abracadabra)

6/15

Hello World: Numbers


Numbers
Computers can understand much more than just strings of text. Python has a few numeric
data types. It has multiple ways of storing numbers. Which one you use depends on your
intended purpose for the number you are saving.
An integer, or int, is a whole number. It has no decimal point and contains all counting
numbers (1, 2, 3, …) as well as their negative counterparts and the number 0. If you were
counting the number of people in a room, the number of jellybeans in a jar, or the number of
keys on a keyboard you would likely use an integer.
A floating-point number, or a float, is a decimal number. It can be used to represent fractional
quantities as well as precise measurements. If you were measuring the length of your
bedroom wall, calculating the average test score of a seventh-grade class, or storing a
baseball player’s batting average for the 1998 season you would likely use a float.
Numbers can be assigned to variables or used literally in a program:

an_int = 2
a_float = 2.1

print(an_int + 3)
# Output: 5

Above we defined an integer and a float as the variables an_int and a_float. We printed out
the sum of the variable an_int with the number 3. We call the number 3 here a literal,
meaning it’s actually the number 3 and not a variable with the number 3 assigned to it.
Floating-point numbers can behave in some unexpected ways due to how computers store
them. For more information on floating-point numbers and Python, review Python’s
documentation on floating-point limitations.
Instructions
1. A recent movie-going experience has you excited to publish a review. You rush
out of the cinema and hastily begin programming to create your movie-review
website: The Big Screen’s Greatest Scenes Decided By A Machine.
Create the following variables and assign integer numbers to them: release_year and runtime.
2. Now, create the variable rating_out_of_10 and assign it a float number between
one and ten.

Fullscreen Code Editor

# Define the release and runtime integer variables below:


release_year = 1
runtime = 1
# Define the rating_out_of_10 float variable below:
rating_out_of_10 = float(8)

7/15

Hello World: Calculations


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

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

# Prints "50"
print(25 * 2)

# Prints "2.0"
print(10 / 5)

Notice that when we perform division, the result has a decimal place. This is because Python
converts all ints to floats before performing division. In older versions of Python (2.7 and
earlier) this conversion did not happen, and integer division would always round down to the
nearest integer.
Division can throw its own special error: ZeroDivisionError. Python will raise this error when
attempting to divide by 0.
Mathematical operations in Python follow the standard mathematical order of operations.
Instructions
1. Print out the result of this equation: 25 * 68 + 13 / 28
Fullscreen Code Editor

eq = 25 * 68 + 13 / 28
print(eq)

Output:

1700.4642857142858

8/15

Hello World: Changing Numbers


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

coffee_price = 1.50
number_of_coffees = 4

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

# Updating the price


coffee_price = 2.00

# Prints "8.0"
print(coffee_price * number_of_coffees)
# Prints "2.0"
print(coffee_price)
# Prints "4"
print(number_of_coffees)

We create two variables and assign numeric values to them. Then we perform a calculation on
them. This doesn’t update the variables! When we update the coffee_price variable and
perform the calculations again, they use the updated values for the variable!
Instructions
1. You’ve decided to get into quilting! To calculate the number of squares you’ll need for
your first quilt let’s create two variables: quilt_width and quilt_length. Let’s make this
first quilt 8 squares wide and 12 squares long.
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

Hello World: Exponents


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

# 2 to the 10th power, or 1024


print(2 ** 10)

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

# 9 * 9 * 9, 9 cubed, or 729
print(9 ** 3)

# We can even perform fractional exponents


# 4 to the half power, or 2
print(4 ** 0.5)

Here, we compute some simple exponents. We calculate 2 to the 10th power, 8 to the 2nd
power, 9 to the 3rd power, and 4 to the 0.5th power.
Instructions
1. You really like how the square quilts from last exercise came out, and decide that all
quilts that you make will be square from now on.
Using the exponent operator, print out how many squares you’ll need for a 6x6 quilt, a 7x7
quilt, and an 8x8 quilt.
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

# Calculation of squares for:


# 6x6 quilt
quilt_6 = 6 * 6
# 7x7 quilt
quilt_7 = 7 * 7
# 8x8 quilt
quilt_8 = 8 * 8
# How many squares for 6 people to have 6 quilts each that are 6x6?
people_6 = 6 ** 4
print(quilt_6)
print(quilt_7)
print(quilt_8)
print(people_6)

Output:

36
49
64
1296

10/15

Hello World: Modulo


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 two
numbers are divisible, then the result of the modulo operation will be 0.

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


print(29 % 5)

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


print(32 % 3)

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


# Prints 0
print(44 % 2)

Here, we use the modulo operator to find the remainder of division operations. We see that 29
% 5 equals 4, 32 % 3 equals 2, and 44 % 2 equals 0.
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

Hello World: Concatenation


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

greeting_text = "Hey there!"


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

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


print(full_text)

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

full_text = greeting_text + " " + question_text

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


print(full_text)

Now the code prints the message we expected.


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

birthday_string = "I am "


age = 10
birthday_string_2 = " years old today!"

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

# If we just want to print an integer


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

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


print(birthday_string, age, birthday_string_2)

Using str() we can convert variables that are not strings to strings and then concatenate
them. But we don’t need to convert a number to a string for it to be an argument to a print
statement.
Instructions
1. Concatenate the strings and save the message they form in the variable message.
Now uncomment the print statement and run your code to see the result in the terminal!
Fullscreen Code Editor

string1 = "The wind, "


string2 = "which had hitherto carried us along with amazing rapidity, "
string3 = "sank at sunset to a light breeze; "
string4 = "the soft air just ruffled the water and "
string5 = "caused a pleasant motion among the trees as we approached the
shore, "
string6 = "from which it wafted the most delightful scent of flowers and
hay."
# Define message below:
message = string1 + string2 + string3 + string4 + string5 + string6
print(message)

12/15

Hello World: Plus Equals


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

# First we have a variable with a number saved


number_of_miles_hiked = 12

# Then we need to update that variable


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

# The new value is the old value


# Plus the number after the plus-equals
print(number_of_miles_hiked)
# Prints 14

Above, we keep a running count of the number of miles a person has gone hiking over time.
Instead of recalculating from the start, we keep a grand total and update it when we’ve gone
hiking further.
The plus-equals operator also can be used for string concatenation, like so:

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

# Almost forgot the hashtags!


hike_caption += " #nofilter"
hike_caption += " #blessed"

We create the social media caption for the photograph of nature we took on our hike, but then
update the caption to include important social media tags we almost forgot.
Instructions
1. We’re doing a little bit of online shopping and find a pair of new sneakers. Right before
we check out, we spot a nice sweater and some fun books we also want to purchase!
Use the += operator to update the total_price to include the prices
of nice_sweater and fun_books.
The prices (also included in the workspace) are:
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:

The total price is 109.0

13/15

Hello World: Multi-line Strings


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

leaves_of_grass = """
Poets to come! orators, singers, musicians to come!
Not to-day is to justify me and answer what I am for,
But you, a new brood, native, athletic, continental, greater than
before known,
Arouse! for you must justify me.
"""

In the above example, we assign a famous poet’s words to a variable. Even though the quote
contains multiple linebreaks, the code works!
If a multi-line string isn’t assigned a variable or used in an expression it is treated as a
comment.
Instructions
1. Assign the string

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


should you not speak to me?
And why should I not speak to you?

to the variable to_you.


Fullscreen Code Editor

# Assign the string here


to_you = """
Stranger, if you passing meet me and desire to speak to me, why
should you not speak to me?
And why should I not speak to you?
"""
print(to_you)

14/15

Hello World: Review


Review
In this lesson, we accomplished a lot of things! We instructed our computers to print
messages, we stored these messages as variables, and we learned to update those messages
depending on the part of the program we were in. We performed mathematical calculations
and explored some of the mathematical expressions that Python offers us. We learned
about errors and other valuable skills that will continue to serve us as we develop our
programming skills.
Good job!
Here are a few more resources to add to your toolkit:
 Codecademy Docs: Python
 Codecademy Workspaces: Python
Make sure to bookmark these links so you have them at your disposal.
Instructions
1. Create variables:
my_age
half_my_age
greeting
name
greeting_with_name
Assign values to each using your knowledge of division and concatenation!
Fullscreen Code Editor

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:

likes_snakes = input("Do you like snakes? ")

In the example above, the following would occur:


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

favorite_flightless_bird = input("What is your favorite flightless bird?")

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.
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

Control Flow: Boolean Expressions


Boolean Expressions
To build control flow in our program, we need to be able to check whether a condition is true
or not. For this, we use Boolean expressions.
A Boolean expression is a statement that can either be true or false. The statement must be
answered by true or false only, and it must be verifiable with evidence. It cannot rely on
interpretation or opinion.
To understand this, let’s go back to the ‘waking up’ example. The first question, “Is today a
weekday?” can be written as a Boolean expression shown below:

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:

Friday is the best day of the week.

Is this a Boolean expression?


No, this statement is an opinion and is subjective. Someone might say that “Wednesday is the
best day.” and their statement would be no less true or false than the one above.
How about the following phrase:

Sunday starts with the letter 'C.'

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

You might also like