KEMBAR78
Yoyoyoyoyoyoyoyy | PDF | Numbers | Python (Programming Language)
0% found this document useful (0 votes)
103 views188 pages

Yoyoyoyoyoyoyoyy

broooooooooo

Uploaded by

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

Yoyoyoyoyoyoyoyy

broooooooooo

Uploaded by

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

From zero to python hero

Byte by Byte :

Pyth n
Edition
By : Batoul Yaz

Including visual
studio tips

Yazbek_batoul batoyaz
Table of Content:
1.Chapter 1 : Setting Up 3
2.Chapter 2 : “Hello World” 7
3.Chapter 3 :Initials 10
4.Chapter 4 : Data Types 15

5.Chapter 5 : Operators 20
6.Chapter 6 : Inputs 27
7.Chapter 7 : Control Flow 35
8.Chapter 8 : Loops 57
9.Checkpoint Project 72

10.Chapter 9 : Lists 76

11.Chapter 10 : Functions 101

12.Chapter 11 : Classes and Objects 126


13.Chapter 12 : Modules 150
14.Chapter 13 : Final Project 174
15.Chapter 14 : Visual Studio Tips 184
16.Chapter 15 : Authors message 187
01.
Setting
Up
# Python
Welcome to the first chapter of The Legend
of Python!
The programming language we are learning
is called Python, created by a developer
named Guido van Rossum in the early 90s.

Python is designed to be easy for us to read,


which makes it the perfect coding language for
beginners.
It's also super versatile and used in the
following areas:
•Data analysis & visualization
•Artificial intelligence (AI)
•Machine learning (ML)
•Web development
•And more!
Set Up Your Local Development Environment with
Python

All the code we write in this course


will be in Python files, with
the .py extension. And we write them
inside a code editor.

Code editor is a text editor where we


can write and execute code. One of the
most powerful and widely used code
editors is Visual Studio. Developed by
Microsoft, Visual Studio is an
integrated development environment
(IDE) that goes beyond just editing —
it provides tools for debugging,
compiling, version control, and
project management all in one place.
you can easily set it up by installing them from
the links — and if you’re unsure how to do
that, you can refer to any YouTube tutorial
that guides you step-by-step through the
installation and configuration process.

• Download visual studio:


www.code.visualstudio.com

• Download python :
www.python.org/downloads/

• For more info visit :


https://www.codedex.io/python/bonus/set
-up-your-local-environment-in-python
02.
“hello World!”
# Print
In Python, the print() function is used to tell a
computer to "talk." This is something we are going
to use a lot.
The message we want to display should be inside the
parentheses and surrounded by quotes. They can be
double quotes " or single quotes ', but the opening and
closing quote marks have to be the same.

This is an example of a print() function:

print(‘ Hello ')


In the example above, we instructed our
program to print a message. This resulting
text that is printed to the screen is referred to
as the output.

The output of this example program would


be:
Hello
Application 1:

Let’s use our editor to create a new


hello_world.py program.

On a new line, use print() to output the


message "Hello World!“ . And then run
the program

Were you able to print "Hello


World!" in the terminal?

solution:
03.
Initials
# Line by Line
Python is run one line at a time, from
top to bottom.
We can output multiple messages by
using multiple print() functions. For
example, if we want to print out two
simple greetings:
print('Morning')
print(' Evening ')
This will output:
Morning
Evening
Now let's use what we just learned to
complete a special challenge! ⋆˙⟡
Application 2:
Suppose we want the output to look
exactly like this pattern below:
1
23
456
7 8 9 10
How can you do that?
Create a pattern.py program that
prints this pattern exactly as shown.
Solution:
# Comments
• Comments are very important in programming
because they are used to document what our
code does. They are also used to disable parts of
the program.

• When the program is run, the comments are


ignored.

• In Python, we can create a comment using the #


hashtag symbol:

➢ Example:
# Printing out a message
print('Hi')

On the first line, we created a comment. As a result,


everything to the right of the hashtag # is ignored.
The program continues to the next line, and the
output is simply:
Hi
Python only ignores anything after the # on a line.
So, when a comment is placed towards the end of a
line like this:
print('Hi') # I'm a comment, too!
# Congrats!

# we're so proud of you! (╥﹏╥)


print(“Congrats! You've made it to the
end of chapter one! ”)

Here's a refresher on what we went


over:

• The print() function is used to


output messages to the terminal.
• Python code runs one line at a time,
from top to bottom.
• Comments are created using the #
hashtag symbol.
04.
Data
Types
# Variables
In programming, variables are used for
storing data values. Each variable has a
name and holds a value.

The variable name can consist of


letters, numbers, and the _ underscore.

These are all valid variable names and


values:

name = ‘Batoul Yaz'


user_id = 16180339887
xp = 60
verified = True
The = equal sign means assignment:

• We're assigning the string value ‘Batoul Yaz'


to the variable name.
• We're assigning the number value
16180339887 to the variable user_id.
• We're assigning the number value 60 to the
variable xp.
• We're assigning the truth value True to the
variable verified.

We can also change the value of a variable, or


print it out:
xp = 70
xp = 80
print(xp) # Output: 80

Here, we are assigning the number value 70 to


the variable xp. Then, we are reassigning the
number value 80 to the same variable. And
printing it out.
# Integer
An integer, or int, is a whole number. It has no
decimal point and contains the number 0,
positive and negative counting numbers. If we
were counting the number of people on the bus
or the number of jellybeans in a jar, we would
use an integer.
year = 2025
age = 32
# Float
A floating-point number, or a float, is a decimal
number. It can be used to represent fractions or
precise measurements. If you were measuring
the length and width of the couch, calculating
the test score percentage, or storing a baseball
player’s batting average, we would use a float
instead of an int
pi = 3.1415
meal_cost = 12.99
# String
A string, or str, is used for storing text.
Strings are wrapped in double quotes " " or
single quotes ' ‘.

message = "good night"


username = ‘@batoyaz’

When we did printing in the first chapter, we


printed a string data type.

# Boolean
A Boolean data type, or bool, stores a value
that can only be either true or false. In Python,
it's capitalized True or False. It's named after
the British mathematician George Boole (1815-
1864).

late_to_class = False
On_time= True
05.
Operators
# Operators
Computers are incredible at doing math
calculations. Now that we have learned about
variables, let's use them with arithmetic operators
to calculate things!

Python has the following arithmetic operators:

• + Addition
• - Subtraction
• * Multiplication
• / Division
• % Modulo (returns the remainder of a division)

score = 0 # score is 0
score = 4 + 3 # score is now 7
score = 4 - 3 # score is now 1
score = 4 * 3 # score is now 12
score = 4 / 3 # score is now 1.3333
score = 4 % 3 # score is now 1

print(score) # Output: 1
And take a look at this code that calculates a
20% tip by calculating the total and then
multiplying by a float (decimal number):

pizza = 2.99
coke = 0.99

total = pizza + coke

tip = total * 0.2

print(tip) # Output: 0.796

Another way to write this is using parentheses


to calculate the total and the tip in one line of
code:

tip = (pizza + coke) * 0.2

In Python, parentheses have the highest order


of operations.
Now that we've learned about the basics of
variables and operators, let's put them to
use!
Application 3:
Create a temperature.py program that converts a number
from Fahrenheit (°F) to Celsius (°C).

Suppose that the temp is 90 °F


Use the following formula and write it out in Python:

𝑓𝑎ℎ𝑒𝑟𝑛ℎ𝑒𝑖𝑡−32
𝑐𝑒𝑙𝑐𝑖𝑢𝑠 =
1.8

Print out the converted temperature.


Solution:
# Exponents
Python can also perform exponentiation such
as 2³ or 10².

In written math, we might see an exponent as


a superscript number (like above), but typing
superscripts isn't always easy on modern
keyboards. Since exponentiation is super
similar to multiplication, Python uses the
notation **.

So, 2 ** 3 is 2³ and 10 ** 2 is 10².

Here are more examples:

score = 2 ** 2 # score is 4
score = 2 ** 3 # score is now 8
score = 2 ** 4 # score is now 16
score = 2 ** 5 # score is now 32
print(score) # Output: 32

Let's give it a try!


Application 4:
The body mass index (BMI) was created by a
Belgian mathematician in the 1850s and it's
used by health and nutrition professionals to
estimate human body fat in certain populations.

It is computed by taking an individual's


weight (mass) in kilograms and dividing it by
the square of their height in meters.

𝑚𝑎𝑠𝑠
BMI=
ℎ𝑒𝑖𝑔ℎ𝑡 2
Create a bmi.py program that calculates your
own BMI.

Author's note: Psst. BMI is an archaic and


oversimplified way to measure personal health.
It was created by a mathematician – not a
doctor!
Solution:
06.
Inputs
# User Input
Thus far, we've only been outputting things to
the user, making our programs one-sided and
not that fun. Almost every popular website,
mobile app, or video game nowadays have both
input and output.
So how do we get input from the user?

Python uses the input() function to get user


input:

username = input('Enter your name: ')


print(username)

The output will say "Enter your name: " and


the user can type in something, hit enter, and
whatever the user typed gets stored into the
username variable.

So here, suppose the user typed in their name


and pressed enter, it will output their name.
# int()
By default, the user input is stored as a
text string, which is okay for now.

But what about when we want to get a


number from a user?

In that case, we would need to wrap an


int() around the input() to convert the
text string into a number:

age = int(input('What is your age? '))


print(age)

Now that the user types 24 and presses


enter, the age variable will be an integer
24, not a text string "24".
Application 5:
If you slept through your geometry class, a
Pythagorean theorem is the relationship
between the three sides of a right triangle. It
was named after the Greek philosopher
Pythagoras, born around 570 BC.

Pythagorean equation looks like:

2 2 2
𝑐 =𝑎 +𝑏
The a is the length of a side.
The b is the length of another side.
The c is the length of the hypotenuse.
The hypotenuse is the longest side of the right
triangle.

Create a hypotenuse.py program that asks the


user for two numbers, a and b, and then
calculates the hypotenuse c.
Solution:
Congrats!
Woohoo! You learned variables in Python!

Here's a recap of everything we learned in this


chapter:

• Data types: int, float, str, bool.


• Arithmetic operators: +, -, *, /.
• The % modulo finds the remainder.
• The ** exponentiation finds the exponent.
• The input() function is used to get user
input.
• The int() function converts a value into an
integer number.

Let's put it all together now!


Application 6:

Instructions
We just got home from a fun trip to South
America, specifically Colombia, Peru, and
Brazil. There's some leftover cash in:

• Colombian pesos
• Peruvian soles
• Brazilian reais

Create a currency.py program that asks the


user for the amount they have in pesos, soles,
and reais and calculates the total in USD.

Make sure to Google the current exchange


rates for pesos, soles, and reais!
The output should look something like this,
but with slightly different results:

What do you have left in pesos? 5600


What do you have left in soles? 105
What do you have left in reais? 280
413.0

Solution:
07.
Control
Flow
So far, every Python program we've
encountered has only had one path of
execution – they all execute one line at a time,
from top to bottom. Every time you run them,
it gives you the same result.

Sometimes, we want our program to do


different things based on different conditions.

It's like going down a highway and there's a


fork ahead with a sign that reads “city: left.
forest: right."
In the "Control Flow" chapter, we will
explore how programs "make decisions" by
evaluating different conditions, and start
introducing logic into our code!
# If Statement
An if statement is used to test a condition for
truth:

If the condition evaluates to True, code in the if


part is executed.
If the condition evaluates to False, code is
skipped.

For example, if the grade variable is greater


than 60:

if grade > 60:


print('You passed!')

The code "inside" the if statement must be


indented (preferably 2 spaces).
# Else

An else clause can be optionally added to an if


statement.

If the condition evaluates to True, code in the


if part is executed.
If the condition evaluates to False, code in the
else part is executed.

o Example:
if grade > 60:
print('You passed.')
else:
print('You failed.')

The code "inside" the else clause must also be


indented.
Application 7:
Create a grades.py program that checks
whether a grade is above or below 55.

1. Start by creating a variable called grade


and give it a value between 0-100.

2. Write a if/else statement for the following:

If grade is greater than or equal to 55, then


print "You passed."
Else, print "You failed."

3. After you run the code, change grade's


value and rerun it. Do this a few times to
make sure it's working as intended.
Solution:
# Relational Operators
A lot of the times inside conditions, we are
comparing two values. To do so, we need to
use a different type of operators called
relational operators that compares values:

• == equal to
• != not equal to
• > greater than
• < less than
• >= greater than or equal to
• <= less than or equal to
# Elif
One or more elif statements (short for "else if")
can be optionally added in between the if and
else to provide additional condition(s) to check.
Sometimes two is simply not enough.

o Example:
if grade > 90:
print('A')
elif grade > 80:
print('B')
elif grade > 70:
print('C')
elif grade > 60:
print('D')
else:
print('F')

Note: Only one of these options will execute.


Application 8:
In chemistry, pH is a scale used to
specify the acidity or basicity of a liquid.

Create a ph_levels.py program that


checks whether a pH level is basic,
acidic, or neutral.

First, create a ph variable and ask the


user for a value between 0 and 14.

Write an if, elif, else statement that:

• If ph is greater than 7, output "Basic".


• If ph is less than 7, output "Acidic".
• Else, output "Neutral".
Solution:
# Random
In Python, modules are .py files containing Python
code that can be imported inside another Python
program. The Python standard library contains
well over 200 modules that we can use.

We can use the .randint() function from a module


called random to generate a random number from a
range.

But first, let's import this module so we can use its


functions.
o Code:
import random

Next, we'll create a variable to store the randomly


generated value. Declare a variable called num, and
assign it to the function call:

num = random.randint(1, 9)

This will generate a random number between 1 and


9 (inclusive of both).
Together, the code will look like:

Try running this code!

The output should be different each time


it runs: 2, 8, 5, 9, 2, 1, 3...
Application 9:
The Magic 8 Ball is a popular office toy and
children's toy invented in the 1940s for fortune-
telling and advice seeking.
It's an oversized 8 ball with some of the following
answers:

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

Create a magic8.py program that can respond to


any Yes or No questions with a different answer
each time it executes.
The output should have the following format:
Question: [Question]
Magic 8 Ball: [Answer]
Solution:
# Logical Operators
One more thing that we should learn is logical
operators.

Logical operators, also known as Boolean operators,


combine and evaluate two conditions. They are and,
or, and not operators:

• and returns True if both conditions are True, and


returns False otherwise.
• or returns True if at least one of the conditions is
True, and False otherwise.
• not returns True if the condition is False, and
vice versa.
Here are some examples:
if hunger > 4 and anger > 1:
print('Hangry')
If the hunger variable is greater than 4 and the
anger variable is greater than 1, then the program
prints "Hangry".
if not tired:
print('Time to code!’)
If the tired variable is not True, then the program
prints "Time to code!"
So, you might be wondering: and & or are
awfully similar, how do I remember the
differences between the two? Let's break this
down in a table form:
Application 10:
Since 1927, "The Cyclone" roller coaster has delighted
visitors at Coney Island (Brooklyn, NY).
They're now installing a new entry system (the height
requirement is 137 cm and the cost is 10 credits) and
need your help writing the program for it!

Create a new file called the_cyclone.py.

➢ Ask the user what their height is and how many


credits they have, and store the values in a height
variable and a credits variable.

➢ Use a combination of relational and logical


operators to create the rules:

• If they are tall enough and have enough credits,


print "Enjoy the ride!"
• Else if they have enough credits, but they aren't tall
enough, print "You are not tall enough to ride."
• Else if they are tall enough, but they don't have
enough credits, print "You don't have enough
credits."
• Else, print a message saying they have not met
either requirement.
Solution:
# Congrats!
Here's a recap of everything we learned so
far:

• Control flow is the order in which the


program's code executes.
• if statement tests a condition for truth
and executes the code if it's True.
• elif clause can be added between if and
else.
• else executes the code if none of the above
is True.
• Relational operators are used to compare
two values: ==, !=, >, >=, <, <=.
• Logical operators are used to combine
two or more conditions: and, or, not.

Now let's put all your learnings together to


create your own quiz!
Application 11:
Write a program that helps a user find their
perfect magical pet.
The program asks two questions using input()
and int():
• Q1) Do you prefer day or night?
1.Day
2.Night
•If answer is 1 → Cat +1, Owl +1
•If answer is 2 → Toad +1, Rat +1
•Else → print "Wrong input."
• Q2) Which trait do you value most?
1.Loyalty
2.Cleverness
3.Courage
•If answer is 1 → Dog +2
•If answer is 2 → Owl +2
•If answer is 3 → Cat +2
•Else → print "Wrong input."
Finally, print out the score for each pet.
Bonus: Print out the pet with the highest score.
Solution:
Solution:
08.
Loops
# Loop
In programming, a loop is used to
repeat a block of code until a specified
condition is satisfied. It's another
incredibly powerful tool that's used a
ton!

People will often use the generic term


“iterate” when referring to loops;
iterate simply means “to repeat”.

The first kind of loop that we are


going to learn is the while loop. You
can think of the while loop like a traffic
circle.

Each lap is one iteration! A car will


iterate over and over again until it
can't do so anymore.
Application 12:
Before we dive deep into while loop, let's see a demo
using a bank's ATM.

Create an enter_pin.py program and type in the


following:

Next, press the "Run" button to see the messages


print to the terminal.

Try the following in the terminal :


• Type 1111 and then the enter key.
• Type 2023 and then the enter key.
• Type 1991 and then the enter key.
• Type 1234 and then the enter key.
Were you able to get access to the ATM?
# While Loop
Now that we got a sneak peek of a while loop, let's
see what it does!
A while loop looks very similar to an if statement.
Just like an if statement, it executes the code if the
condition is True.

However, the difference is that the while loop will


continue to execute the code inside of it, over and
over again, as long as the condition is True.

In other words, instead of executing once if a


condition is true, it executes again and again while
that condition is true.

Here, we have a while loop that asks the user to


guess a number:
guess = 0
while guess != 6:
guess = int(input('Guess the number: '))

This will run over and over again until the user
guesses the number 6.
Explanation:
The variable guess starts at 0 on the first line and
then the program enters the while loop:

1. It checks the condition: is it true that 0


doesn't equal 6? Yep. Okay, run the code
inside.
2. It checks the condition again: is it true that 5
doesn't equal 6? Yep. Okay, run the code
inside.
3. It checks the condition again: is it true that 3
doesn't equal 6? Yep. Okay, run the code
inside.
4. It checks the condition again: is it true that 6
doesn't equal 6? Nope! So it exits the while
loop and skips the code inside.
To reiterate (no pun intended), at the beginning
of each "loop", the condition is checked. The
moment the condition becomes false, the program
exits the while loop and continues on from the
line after it.
Note: If the condition is False from the get-go,
then the code block wouldn't run at all and will be
skipped.
Application 13:
Let's continue on from the code above.

Create a guess.py program and type in the following:

Run the code a few times so that you understand what


it does.

Let's make it so that it's the same guessing game, but


there is a new limit to the number of tries (it was
infinite before).

First, introduce a variable called tries at the top and


give it a value of 0.

Then, add a second condition with the tries variable to


the while loop using a relational operator.
Solution:
# range()
To loop through a set of code a specified number of
times, we can use a for loop and the range() function.

The range() function returns a sequence of numbers.


By default, the sequence starts at 0 and increments
by 1, ending at a specified number.

for i in range(6):
print(i)

For number i inside range(6), which is 0 through 5,


print number i.

This will output:

0
1
2
3
4
5

Notice how this stops at 5, and 6 is not printed. This


is because range() actually ends one before the
specified number.
Application 14:
Suppose you got detention and the teacher
wants you to write "I will not use the phone
in class" on the whiteboard 100 times.

Create a detention.py program that does this


using code.

(This is where we begin to see the true power


of computing. What takes humans hours can
take a computer microseconds. )

Solution:
# Squares
On May 6th, 1949, EDSAC, an early electronic
stored-program computer, ran its first program
at the University of Cambridge.

It calculated and printed out a list of squares:


0 0
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
On the left, you got all the single-digit numbers
from 0 to 9. On the right are their squares. For
example, in the last row, 9 × 9 = 81.

This can be done in Python using string


concatenation.
# String concatenation
for i in range(5):
print('The square of ' + str(i) + ' is ' + str(i*i))

The output would look like:

The square of 0 is 0
The square of 1 is 1
The square of 2 is 4
The square of 3 is 9
The square of 4 is 16
# String Interpolation
Let's learn a new tool that's very similar to string
concatenation, before continuing on to the instructions.

String interpolation is a process of substituting values of


variables into placeholders in a string.

For instance, if you have a template for saying hello to a


person in an email like 'Hi {name}, nice to meet you!', you
would like to replace the placeholder {name} with an
actual name. This is string interpolation.

.
The above program can be recreated
using string interpolation using the {}
sign:

for i in range(5):
print(f'The square of {i} is {i*i}')

Notice the f prefix before the quotes.


# Congrats!
You've made it to the end of this chapter!
Let's do a recap.

The while loop iterates over and over again


while the condition is true:

while coffee < 1:


print('Tired')

The for loop and the range() function to


iterate for a certain number of times:

for i in range(10):
print(i)

Now let's take your learnings to the test!


Application 15:
Fizz Buzz is a children's word game that teaches division. It's
also a classic technical interview question at countless
companies.

Though this challenge may appear simple to experienced


coders, it is designed to weed out 90% of job candidates who
cannot apply their coding knowledge to a new problem
creatively. Want to give it a try?
Create a fizz_buzz.py program that outputs numbers from 1
to 100.

Here's the catch:


• For multiples of 3, print "Fizz" instead of the number.
• For multiples of 5, print "Buzz" instead of the number.
• Here's the tricky part: For multiples of 3 and 5, print
"FizzBuzz".
The output should look like:
1
2
Fizz
4
Buzz
Fizz
7

Btw, it's totally okay if you can't get this one... it's a tough
problem!
Hint : Don’t forget to use the module %
Solution:
Checkpoint
project
Checkpoint Project
Congratulations on completing the first 8 chapters
of The Legend of Python! Now let's use the skills
you've learned (variables, control flow statements,
and loops) to build a Python project on your own.

Use the Python Visual Studio Code or your code


editor of choice for this project.

# Area Calculator

Create a calculator.py program that calculates the


area of one of the following shapes:
• Square
• Rectangle
• Triangle
• Circle

The program should present a menu for the user to


choose which shape to calculate, then ask them for
the appropriate values (side, length, width, etc.).

Then, it should calculate the area and print it out.


Here are the area equations for each shape:

Note: For pi π in the area of a circle, feel free to


either use 3.14 or import the math module to use
the math.pi variable.

The output should look something like this:


Area Calculator
1) Triangle
2) Rectangle
3) Square
4) Circle
5) Quit

Which shape: 1

Base: 5
Height: 6
The area is 15
Solution:
09.
Lists
# Lists
Welcome to the Lists chapter! Thank you for sticking
around. :)
Here, we'll learn about a neat way to store a bunch of
data values. =

Suppose we want to build a program that stores


student grades for homework and quizzes, we would
need to create a bunch of variables like so:
hw_grade1 = 98
hw_grade2 = 87
hw_grade3 = 92
hw_grade4 = 96

quiz_grade1 = 9
quiz_grade2 = 6
quiz_grade3 = 8

Creating a bunch of variables this way is tedious and


error-prone. Can you imagine what it would be like
with 100+ students?
Lists are used to store multiple items in a single
variable.
We can rewrite the above code to:
hw_grades = [98, 87, 92, 96]
quiz_grades = [9, 6, 8]
The syntax for a list looks like:
list_name = [item1, item2, item3, item4]

Lists are created using square brackets [ and ]. And


the items are separated by , commas.

# Examples
Data that could be stored in a list:

• Temperatures in the past week.


• pH level of the office plant in the past hour.
• "Now playing" in the movie theater nearby.
• temp = [86, 80, 82, 87, 79, 80, 82]
• ph = [7.2, 7.1, 7.0, 7.0, 7.2, 7.1]
• now_playing = [‘SpongeBob', ‘pooh',
‘Bluey']

More facts about lists:

• List items allow duplicate values.


• Lists can have values with different data
types.
• There's no limit to how much data a list can
hold.
Application 16:
Create a grocery.py program with a grocery list
of things that you need from the store:

• ' Eggs'
• ' Avocados'
• ' Cookies'
• ' Hot Pepper Jam'
• ' Blueberries'
• ' Broccoli'
Print out grocery to make sure you got it!
Solution:
#Index
List items are changeable, meaning we can
update individual items within a list.

But before we do that, how can we access an


individual item within a list? Well, this is where
index comes in!

An index is an item's position in a list.

Python is 0-indexed, meaning that the indices


starts at 0:

vowels = ['a', 'e', 'i', 'o', 'u']


# Index: 0 1 2 3 4

The item at index 0 is 'a'.


The item at index 1 is 'e'.
The item at index 2 is 'i'.
The item at index 3 is 'o'.
The item at index 4 is 'u’.
To output each of the items, we can use the
name[index] syntax:
print(vowels[0]) # Output: a
print(vowels[1]) # Output: e
print(vowels[2]) # Output: i
print(vowels[3]) # Output: o
print(vowels[4]) # Output: u

# Negative Index

Another thing to note about index is that it can be


positive or negative.

If the index is negative, it starts from -1 (which is


the last item of a list) and it goes backwards from
there.

vowels = ['a', 'e', 'i', 'o', 'u']


# Index: 0 1 2 3 4
# Index: -5 -4 -3 -2 -1

The item at index -5 is 'a'.


The item at index -4 is 'e'.
The item at index -3 is 'i'.
The item at index -2 is 'o'.
The item at index -1 is 'u'.
# Slicing
Is there a way to get more than just one individual
item? Yep! It's called slicing.

Slicing is where we can access certain parts of a


sequence.

Instead of accessing an item using a single index like


name[index], we can get multiple items by specifying
where to start and where to end the range like
name[start : end].

For example:
vowels = ['a', 'e', 'i', 'o', 'u']

print(vowels[0 : 3])
print(vowels[1 : 3])

# Output:
# ['a', 'e', 'i']
# ['e', 'i’]
It starts from the start index (inclusive) and ends
before the end index (non-inclusive). So, in the above
example,
print(vowels[1 : 3]) only returned items at indices 1
and 2, and didn't include index 3.
# IndexError
There is a common error in Python when
dealing with sequences called the IndexError.
This is what happens when the index is out of
the range of a list.

For example, when we try to do vowels[5],


we will get something like:

Traceback (most recent call last):


print(vowels[5])
IndexError: list index out of range

So, make sure to be careful with that!


Application 17:

Create a todo.py program that will define a


todo list that contains the following items:

• ' Get quarters.'


• ' Do laundry.'
• ' Take a walk.'
• ' Get a haircut.'
• ' Make some tea.'
• ' Complete Lists chapter.'
• ' Call mom.'
• ' Watch My Hero Academia.’

Print the first item and the second item.


What did you get?
Next, use slicing to print the third, fourth,
and fifth items.

Try printing out the item at index 9 to see


the IndexError before moving on
Solution:
# Built-in Functions

Python comes with some built-in functions, including


ones specifically for lists.

Here are some examples:

• The len() function returns the total length of a list.


• The max() function returns the maximum value in a
list.
• The min() function returns the minimum value in a
list.

Suppose we have two lists that look like:


stock1_prices = [2.52, 2.44, 2.32, 2.41, 2.51, 2.50, 2.44]
stock2_prices = [8.36, 8.31, 8.21, 8.21, 8.25, 8.11, 8.13]

print(len(stock1_prices)) # Output: 7
print(max(stock1_prices)) # Output: 2.52
print(min(stock2_prices)) # Output: 8.11

We can find a list's length, minimum, and maximum


within a split second, even if the list has 1000+ items!

To learn more, here are all the Python built-in


functions. However, not all built-in functions are
designed to work with lists!
Application 18:
Suppose the holidays are around the corner,
and the North Pole elves need your help to
have thousands of LEGO toys packed up and
ready for shipping.

Create a inventory.py program with the


following list:

lego_parts = [8980, 7323, 5343, 82700,


92232, 1203, 7319, 8903, 2328, 1279, 679,
589]

Each item in the list is the quantity of a


colored part for a LEGO toy.

Can you figure out the following information


using built-in list functions?

• Which LEGO part are the elves running


low on? Use min() to find out.
• Is there a LEGO part that the elves are
overstocking? Use max() to find out.
Solution:
# List Methods
Besides built-in functions, Python has a bunch of
built-in list methods that are very handy.

Here are some of them:

• .append() method adds an item to the end of the


list.
• .insert() method adds an item to a specific index.
• .remove() method removes an item from a list
based on the value.
• .pop() method removes the item at a particular
index.

Let's use DNA sequences as an example for this!

dna = ['AUG', 'AUC', 'UCG']


dna.append('UAA') # ['AUG', 'AUC', 'UCG',
'UAA']
dna.insert(2, 'GAU') # ['AUG', 'AUC', 'GAU',
'UCG', 'UAA']
dna.remove('AUC') # ['AUG', 'GAU', 'UCG',
'UAA']
dna.pop(0) # ['GAU', 'UCG', 'UAA']
The difference between built-in functions
and methods on a list is that methods use
the dot notation syntax on the list
variable we create. Built-in functions can
be called by themselves, but methods are
always attached to a list variable from
which they are being called.

Another notable difference is that while


not all the built-in functions are defined
to work with lists, the list methods only
work with lists.
Here are all 11 list methods to save in your
notes:
Application 19:

Let's start a book club by making a list of popular books!

Create a reading_list.py program that stores the


following items in a books list:

• 'Harry Potter'
• '1984’
• ‘The little bred man ’
• 'Byte by byte'
• 'Life in Code'
Suppose we want to add ‘Pinocchio ' to the list. Can you
use a list method to do so?

Let's say we finished reading ' The little bred man ' and
'1984'. Can you use the .remove() method to remove one
and the .pop() method to remove the other?

Print the updated list out to make sure everything's good


to go!
Solution:
Now you might be wondering, is there a way to iterate
over a list?

Yep, there are multiple ways to iterate over a list in


Python! In this exercise, we are going to show you
different ways to do so.

# for-in
The first way is using a for-in loop. Here's an example:

snowfall = [0.3, 0.0, 0.0, 1.2, 3.9, 2.2, 0.8]

for i in snowfall:
print(i)

The i is a variable which represents an item inside the


list, each time the loop iterates. This is saying for every
item in the snowfall list, print out the item. The output
will be:
0.3
0.0
0.0
1.2
3.9
2.2
0.8
# for-in with range() and len()

We can also loop through a list using the index


(position). To do so, we need the range() function and
the len() function.

As a reminder:

• range() function returns a sequence of numbers,


from 0 to a number.
• len() function returns the length of the list.

snowfall = [0.3, 0.0, 0.0, 1.2, 3.9, 2.2, 0.8]

for i in range(len(snowfall)):
print(snowfall[i])

The i here is an index. This is saying for every index


from 0 to the length of snowfall minus 1 (7 - 1 = 6),
print out the item at that index.
Application 18:

Create a mixtape.py program and think of a theme


for the songs.

Make a list called playlist and throw in some songs.

For example:

# Theme: Indie Travel Songs

playlist = [
'Porches - rangerover',
'Mount Eerie - You Swan, Go On',
'Carolyn Polachek - Look at Me Now',
'Pinegrove - Darkness',
'LVL UP - Spirit Was',
'Mitski - First Love / Late Spring'
]

Now loop over the list and print everything out!


Solution:
# Congrats!
You just added a super helpful tool to your coding
toolbox: lists!

Here's a recap of the chapter:

• Lists are used to store different items in a single


variable.
• An index is an item's position in a list. Python lists
are 0-indexed.
• Slicing can access certain parts of a list with
name[start:end].
• Python has built-in functions like len(), max(),
min().
• Lists have built-in methods like .append(), .insert(),
.remove(), .pop().
• We can iterate over a list using for-in.
Now let's pull everything together one last time and
build your bucket list!
Application 19:

A bucket list is a number of experiences or achievements


that a person hopes to have or accomplish during their
lifetime.

Create a bucket_list.py program with your own unique


bucket list.

First, create a things_to_do list, and add things you want


to do in your lifetime.

For example:
things_to_do = [
' Create the dopes learn to code platform ever.',
' Hike the Pacific Crest Trail.',
' Build an A-frame house and raise some goats.',
' Live somewhere in Asia for a year.',
' Write a book.',
' Road trip with the fam.',
' Grow old with no regrets.'
]

Now, iterate over the list and print everything out.


Solution:
10.
Functions
# Functions
As our code gets longer and longer, you might
find yourself copying and pasting a particular
code block in different parts of the program.
That's no good!

“Don't Repeat Yourself” (DRY) is a principle in


software development aimed at reducing
repetition and writing good clean code.
Functions play a big part.

A function is a reusable block of code that


performs a specific task. To execute this block
of code, you just need to write the function's
name, followed by a pair of parenthesis ( ).
Whether the task is five or twenty lines of code, you
can throw it in a function and use it later anywhere in
your program. It takes a little more effort initially but
will save you a lot of time in the long term.

Plot twist! In this course, we have been using functions


all along.

Built-in functions are 68 functions that come with the


Python interpreter available for use. Here are some that
you might recognize:

• print()
• input()
• len()
We've used them before, but didn't get into how they
work behind the scenes.

And that's okay! This is the beautiful part about built-


in functions. Like a car, you don't need to know what's
underneath the hood to operate it.

Let's look at some built-in Python functions!


# Define a Function

So how do we create a function from scratch?

User-defined functions are functions we define ourselves


to do a specific task, and it's a two-step process: define
and call.

To define a function, we need a function definition. A


function definition begins with the def keyword,
followed by the function name, a set of parentheses, and
a colon, in that order.

Here’s what a function definition looks like:

def name():
# The code inside

• The def keyword.


• The function name, followed by a pair of parentheses
().
• The colon :.
• The code inside the function is called the body of the
function. And just like if statements and while loops,
the code inside a function must be indented.

Note: The common naming convention for functions is


snake_case.
Suppose we want to create a function named
say_hello():

def say_hello():
print(‘Hello! ')
print('How are you?')

We just defined a function that prints out two


greetings!

Defining a function creates the function, and


it's the first step, but it doesn't mean that
Python will automatically run the code inside
its body. How do we convey to Python that
we want the function body executed?

We need to call the function!


# Call a Function

To call a function, we use the function name followed by


parentheses somewhere in the code:

def say_hello():
print('Howdy! ')
print('How are you?')

say_hello()

This executes the say_hello() function once!

So, the output would be:

Howdy!
How are you?

We can also call a function numerous times. For example:

def say_hello():
print('Howdy! ')
print('How are you?')

say_hello()
say_hello()
say_hello()

This executes the say_hello() function three times!


Now it’s your turn to define and call a function in a program!
Application 20:

Create a fortune_cookie.py program that gives the user


random fortunes.

Define a function named fortune(). Inside the function, print


out a random fortune from the list of options below:

• Don't pursue happiness – create it.


• All things are difficult before they are easy.
• The early bird gets the worm, but the second mouse gets
the cheese.
• Someone in your life needs a letter from you.
• Don't just think. Act!
• Your heart will skip a beat.
• The fortune you search for is in another cookie.
• Help! I'm being held prisoner in a Chinese bakery!

Make sure to use the random module's random.randint() and


an if/elif/else.

Then, call the fortune() function three times and see what
you get!

Bonus: If you're daring, rewrite the function without an


if/elif/else.
Solution:
# Parameters
So far, the functions we've created don't take in any
input(s), which means they do the same thing each time
they get called. A function can be far more useful than
that!

Sometimes, we want our functions to perform a specific


task, but the task varies depending on different input(s).
And that's where parameters come in.

Parameters are just a fancy word for input. They are


variables that a functions takes in. They go inside the
parentheses in the function definition and are used inside
the function.

For example, suppose we define and call a


happy_birthday() function like so:

def happy_birthday():
print('Happy birthday to you')
print('Happy birthday to you')
print('Happy birthday dear friend')
print('Happy birthday to you')

happy_birthday()

This prints out the same thing every time.


Let's say we want to make the song more
personalized. For example, say the person's
name instead of just “dear friend”, then we can
do this:

def happy_birthday(name):
print('Happy birthday to you')
print('Happy birthday to you')
print('Happy birthday dear ' + name )
print('Happy birthday to you')

Here, we gave the happy_birthday() function a


name parameter for the function to take in. So,
we can use the name variable within the
function body.

And later in the program, when we call the


happy_birthday() function, we can add an
argument in the call.
#Arguments
An argument is the value sent to the function when
the function is called.

happy_birthday('Lillian')

The output would be:


Happy birthday to you
Happy birthday to you
Happy birthday dear Lillian
Happy birthday to you

So, what's the difference between a parameter and an


argument? Why are there two words for what seems
like the same thing?

• The parameter is the variable listed inside the


parenthesis in the function definition (when we
define the function).
• The argument is the value sent to the function
(when we call the function).
In the example above, the variable name is the
parameter, and the value 'Lillian' is the argument.

By the way, we’ve already been using arguments all


along, when calling the print() function for instance. In
a print(‘Hi'), the ‘Hi!' is the argument.
Application 21:
In September 1999, after ten months of travel to Mars,
the Mars Climate Orbiter suddenly burned to pieces
because it had entered the atmosphere too fast.

Oh no! The NASA engineers forgot to convert imperial


data to metric data in one of the functions! This noob
mistake cost American taxpayers $125 million total.

Suppose you're a NASA intern, and your team is


calculating the distance a rocket needs to travel. The
value calculated is in kilometers, while the next step
requires miles. Your manager quickly writes this on the
board:

𝐾𝑖𝑙𝑜𝑚𝑒𝑡𝑒𝑟𝑠
𝑚𝑖𝑙𝑒𝑠 =
1.609
Create a new file called rocket.py.

Define a function named distance_to_miles() that converts


a distance from kilometers to miles. It should:
• Take in one parameter named distance (the distance in
kilometers).
• Print the distance in miles.
After, call the function and use 10000 as the argument.
Solution:
#Return value
We learned that functions can take in inputs, but did
you know that functions can also have outputs? In fact,
every Python function has an output!

The return keyword is used to terminate a function and


output a value:

def function_name():
# The code inside
return value

When we don't add it, Python will implicitly return the


default value, None, as the return value.

When we do want to be explicit:

def add(x, y):


answer = x + y
return answer

So , a return keyword is added, plus the variable we


want to output.
Now when we call the function, there will be an
output that we can play with:

total = add(4.99, 9.99) # total is 14.98

This means that we can actually print out a function


call!

print(add(3, 4)) # Same thing as print(7)


print(add(1, 5)) # Same thing as print(6)
print(add(5, 3)) # Same thing as print(8)

Here, the add() function is returning a value and that


returned value is an argument for the print() function.

The output would be:

7
6
8

Note: When a return statement is reached, Python


will stop the execution of the current function,
sending a value out to where the function was called.
# Print vs. Return

Now you might wonder, why are we returning


values instead of printing them?

Well, print() functions can be anywhere in the


program — inside or outside of a function,
whereas return is the output of a function; you
don't need to print out whatever you are
returning.

As a rule of thumb:

• Use return in a function when you want to


send value(s) from one point in the code to
another.
• Use print() in a function when you want to
display some text to the user.
Application 22:

Let's try a classic Computer Science project:


simple calculator program!

Create a calculator.py program and define these


five functions:

• add(a, b) that adds two numbers a and b.


• subtract(a, b) that subtracts two numbers a
and b
• multiply(a, b) that multiplies two numbers a
and b.
• divide(a, b) that divides two numbers a and b.
• exp(a, b) that takes a to the exponent (or
power) of b.
• Make sure to return the result in each
function definition.

Test your calculator by calling each function


once to make sure that it works!
Solution:
#Scope
Suppose we created a variable inside the body of a
function. Can we use it outside of the function? Well, let's
see.

Define a function named add() and print the variable


answer outside of it:
def add(x, y):
answer = x + y
return answer

print(answer)

When we run this code, we will get an error:


NameError: name 'answer' is not defined

This is due to something called scope.

Scope determines where in the program a variable is


visible and can be used.

Here are two types of scope:

The scope of the answer variable is only inside the add()


function. It is a local variable that belongs to the local
scope of the add() function.
Now, a variable created outside of a function is called a
global variable and belongs to the global scope, meaning
that they can be used by every function.
Let's try setting the answer variable as a global variable
(outside the function):

answer = 0

def add(x, y):


answer = x + y
return answer

add(3, 4)

print(answer)

The output won't be an error anymore!

Notice that answer is not 7. It's still 0 because if we


create a variable with the same name inside a function, it
will be a local variable and can only be used inside the
function. The global variable with the same name will
remain global and with the original value.
Application 23:
In fintech, we often perform a time series analysis on stocks.
This means that we need to analyze a stock, given its price
over a certain time.

In this exercise, we will perform a simplified version of a time


series analysis. The stock that we will be analyzing is the
$AMC stock in January 2023.

Here are the stock prices (in dollars) for each of these
weekdays:

stock_prices = [34.68, 36.09, 34.94, 33.97, 34.68, 35.82, 43.41,


44.29, 44.65, 53.56, 49.85, 48.71, 48.71, 49.94, 48.53, 47.03,
46.59, 48.62, 44.21, 47.21]

Create a stock_analysis.py program that implements three


functions:

• price_at(x) that finds the price on a given day x.


• max_price(a, b) that finds the maximum price from day a to
day b.
• min_price(a, b) that finds the minimum price from day a to
day b.
The parameters of the days will be in the range of 1 to 20
(since that is the period for the stock we are analyzing).

Make sure to call each function to test if your functions work


correctly!
Solution:
# Congrats!
Congratulations! You now know how functions work.
This is a concept that trips up a lot of people, so definitely
practice and practice.

In this chapter, we learned:

• The "Don't Repeat Yourself" methodology.


• We've been using built-in functions like print() and
input() all along.
• How to define and call a function — the two-step
process.
• Inputs with parameters and arguments.
• Outputs with the return keyword.
• Function scope vs. global scope.

Here's the function skeleton one more time, just in case


you forget!

def function_name(parameter1, parameter2):


# The code inside
return value

Now that you know how functions work, let's create one
last one!
Application 24:

When you go to a drive-thru like McDonald's, you can


order food using the item numbers. For example, a Happy
Meal might be a #3!

Create a drive_thru.py program with your favorite fast food


chain's menu.

Define a get_item() function that takes in one parameter,


the number of the item you want to order, and returns the
name of that item!

For example, if you called the function with:

Argument value 1, it could return ' Cheeseburger'.


Argument value 2, it could return ' Fries'.
Argument value 3, it could return ' Soda'.
Argument value 4, it could return ' Ice Cream'.
Argument value 5, it could return ' Cookie’.

Make sure to call this function a few times to make sure that
it works!

Lastly, let's do the following:

Create a welcome menu and put that in a welcome()


function.

Create a main program that takes in user input with input().


Solution:
11.
Classes &
Objects
# Classes
As technologists, we create programs to solve
problems that stem from everyday life. In the real
world, the objects around us are complex.

Suppose we want to build a database of students in a


school, where each student has different attributes,
like name, year, GPA, and enrollment status.

Using our previous knowledge, we could represent


each student as a list:

# Lists with student id, name, year, gpa, and enrolled


status

student_1 = [1001, 'Asiqur', 10, 3.7, True]


student_2 = [1002, 'Jerry', 9, 3.8, True]
student_3 = [1003, 'Rose', 12, 3.6, False]

However, we have no way of knowing which item


corresponds to which attribute – it will get messy
fast. For example, does student_2[1] refer to the
name, year, or GPA?

This is where classes come in!


With classes, we can create our own data types and use
them to model everyday objects with unique
characteristics and behaviors.

Classes serve as a template for the objects created using


that class. Simply put, a class is like a blueprint. It can
make a bunch of objects with identical sets of attributes,
similar to how a car manufacturer can use a model
blueprint to build hundreds of cars with different colors,
interiors, wheels, etc.

In our example, (class)


(objects).

Here's the basic syntax for creating a class in Python:

class Name:
# Attributes inside

The class keyword followed by class name creates the


class. By convention, the class name is capitalized.

For example, to make a Student class, we can write:


class Student:
name = ''
year = 0
gpa = 0.0
enrolled = False
The Student class has four attributes:

• .name of the type str (text string)


• .year of the type int (integer number)
• .gpa of the type float (decimal number)
• .enrolled of the type bool (boolean value)

With this class, we can represent each class attribute as


a variable, and we will learn how to access or change
them in later sections! For now, let's implement a class.
Application 24:

Suppose we're building a food delivery app and


want to store restaurants' info.

Create a Restaurant class in a restaurants.py


file with the following attributes:

• .name of the type str


• .category of the type str
• .rating of the type float
• .delivery of the type bool

Make these empty/default values for now.

Nothing should happen when you run the code,


because we have yet to use this class. In the
next exercise, we will start using it!
Solution:
#Objects
Now that we know how to create a class, we can use it
to create objects.

An object is an "instance" of a class. A class is simply


a template for creating objects, which are individual
copies of the class with actual values.

In the last exercise, we created a class to model


students:

class Student:
student_id = 0
name = ''
year = 0
gpa = 0.0
enrolled = False

Using the Student class, let's create an object to model


a student .
The syntax for creating an object looks like this:

Aya = Student()
Now that we have created an object of Student
and saved it to Aya, we can access and edit the
class attributes by using the dot syntax,
.attribute:

Aya.student_id = 1113
Aya.name = ‘Aya Addams’
Aya.year = 11
Aya.gpa = 4.0
Aya.enrolled = True

You can check all the attributes available on the


Aya object with the built-in vars() function, as
follows:
print(vars(Aya))

# Output: {'student_id': 1113, 'name': ‘Aya


Addams', 'year': 11, 'gpa': 4.0, 'enrolled': True}

We don't have to stop there; we can create as


many students as we want using just one
Student class.
Application 25:

In the last exercise, we created a Restaurant


class.

In a new file called bobs_burgers.py, create an


instance of the Restaurant class called
bobs_burgers with the following attributes:

• 'Bob\'s Burgers'
• 'American Diner'
• 4.7
• False

Once you do that, create two more instances


of the Restaurant class with your favorite
dinner spots nearby.

Then, use print(vars()) to output each of the


three restaurants!
Solution:
# The __init__() Method
Recall how we defined our Student class to model students:

class Student:
name = ''
year = 0
gpa = 0.0
enrolled = False

daniel = Student()

However, it feels quite clunky because we need to give each


attribute in the class a default or "dummy" value that doesn't
actually get passed on to the objects we create.

print(vars(Jack))
# Output: {}

For example, the Jack object never received values from the
Student class in the first place! We'd have to set them like so
manually:

Jack.name = ‘Jack Li’


Jack.year = 10
Jack.gpa = 4.0
Jack.enrolled = True

Assigning a value to each attribute on a separate line is tedious;


there must be an easier way! In fact, there is: we can use the
__init__() method!
Using __init__() in our class definition lets us
construct objects with unique attributes. When we
create a new Student() object, we can pass in values for
each attribute to initialize the new object, all in a single
line!

So, if we reformat our Student class with __init__():

class Student:
def __init__(self, name, year, gpa, enrolled):
self.name = name
self.year = year
self.gpa = gpa
self.enrolled = enrolled

Jack = Student(‘Jack Li', 10, 4.0, True)

• Note that __init__() also uses a separate parameter


called self. This represents the object we'll create
out of Student(). We need to include self whenever
we want to use __init__(). It's always the first
parameter.

With self, we can move each of the previous


assignments, like Jack.name = ‘Jack Li', into the
method and slightly rewrite it, like self.name = name.
Creating objects is now so much easier! If we
want to create two more objects , we just have
to write:

lynn = Student(‘Lynn McPherson', 12, 4.0,


True)
Malak = Student(‘Malak Scheible', 12, 3.4,
True)

print(vars(Lynn))
print(vars(Malak))

# Output:
# {'name': ‘Lynn McPherson', 'year': 12, 'gpa':
4.0, 'enrolled': True}
# {'name': ‘Malak Scheible', 'year': 12, 'gpa':
3.4, 'enrolled': True}

The __init__ might be more effort upfront,


but it saves us so much time if we create
hundreds or thousands of the Student objects.
Application 25:

Ever wonder how many people live in New York City?


What about London?

Create a favorite_cities.py program.

Let's make a City class that uses the __init__() method


to define the following attributes:

• name (string)
• country (string)
• population (integer rounded to the nearest
thousand people)
• landmarks (list of strings)

Next, create an object for your hometown and assign


the attributes above.

Lastly, create another object for the city that you've


always wanted to visit!
Solution:
# Instance Methods
Now that we can create classes and objects, and edit
their properties, our last step is to create functions.

Wait... functions in classes?! Isn't that super


complicated?

Actually, it's not. Functions that are defined in a class


are called methods. In fact, we have already used a
bunch of methods. For example, in exercise 19, we
looked at a few built-in list methods, such as:

.insert()
.append()
.remove()

These are built-in methods. Let's create our own


methods within a class!

Consider our Student class:


class Student:
def __init__(self, name, year, enrolled, gpa):
self.name = name
self.year = year
self.enrolled = enrolled
self.gpa = gpa
To implement a method, we need to define one inside
the class. For example, if we want to create a method
called .display_info(), we would define it like so:

class Student:
def __init__(self, name, year, enrolled, gpa):
self.name = name
self.year = year
self.enrolled = enrolled
self.gpa = gpa

def display_info(self):
print('The student ' + self.name + '\'s GPA is ' +
str(self.gpa) + '!')
But remember, like a function, defining a method
doesn't automatically run the code inside the
method's body. We still need to call the method as
follows:

Sara = Student(‘Sara', 11, False, 4.0)


Talynn = Student(‘Talynn', 11, True, 3.8)

Sara.display_info()
Talynn.display_info()

# Output:
# The student Sara's GPA is 4.0!
# The student Talynn's GPA is 3.8!
Note: Take a look at def display_info(self). Like what we
learned about with the __init__() method, the first argument
in the methods we make is always self. Every method has to
have this self argument. The object attached to the method call
is what self refers to.

In our example, we created two objects, Sara and Talynn.

When we called the Sara.display_info() method, the self


parameter refers to the Sara object.
In the case of Talynn.display_info(), self refers to the Talynn
object.
Also, you can define as many methods as you'd like!

class Student:
def __init__(self, name, year, enrolled, gpa):
self.name = name
self.year = year
self.enrolled = enrolled
self.gpa = gpa

def display_info(self):
print('The student ' + self.name + '\'s is ' + str(self.gpa) + '!')

def graduation(self):
if self.enrolled and self.gpa > 2.5 and self.year == 12:
print(self.name + ' will be able to graduate this year!)
Application 26:
It's time to open up a bank account!

Create a file called bank_accounts.py.


Let's define a BankAccount class. Then, let's use the
__init__() method to set the following attributes:

• first_name (string)
• last_name (string)
• account_id (integer)
• account_type (string)
• pin (integer)
• balance (float)
Next, let's create three methods:

• .deposit(): Add money into the account and return


the new balance.
• .withdraw(): Take money out by subtracting from
balance and returning the withdrawn amount.
• .display_balance(): Print the current value of
balance.
Lastly, initialize a new object from the BankAccount
class and use these methods to do the following:

• Deposit $96 into the account.


• Withdraw $25 from the account.
• Print the current account balance.
Solution:
# Congrats!
Nice! You've reached the end of another chapter!

Let's recap what we learned:

We learned how to:


• Create a class and initialize it with certain attributes.
• Create objects based on these classes and set values for
these attributes.
• Create classes using the special __init__() method.
• Create instance methods that will update or use these class
attributes.
Check out this Student class definition for a refresher:
class Student:
def __init__(self, name, year, enrolled, gpa):
self.name = name
self.year = year
self.enrolled = enrolled
self.gpa = gpa

def display_info(self):
print('The student ' + self.name + '\'s GPA is ' + self.gpa +
'!')

def graduation(self):
if self.enrolled and self.gpa > 2.5 and self.year == 12:
print(self.name + ' will be able to graduate this year!’)

In this final exercise, we will build a fun project using


everything we've learned about classes and objects!
Application 27:

Since 1996, the Pokémon video game franchise has


delighted players around the world with collectible
pocket monsters. A Pokédex is a device that tracks the
information for Pokémon that are seen or caught.

Create a new file called pokedex.py.

Next, let's define a Pokemon class with the following


attributes:

• entry (integer)
• name (string)
• types (list of strings)
• description (string)
• is_caught (boolean)
Note: Make sure to use the __init__() method.

Next, create an instance method called .speak() that


prints a string of the sound a Pokémon makes. A
Pokémon usually just says their name, so make the
.speak() simply print out their name .

Then, create another instance method called


.display_details() that prints the attributes of a
Pokemon object like the following:
Entry Number: 25
Name: Pikachu
Type: Electric
Description: It has small electric sacs on both
its cheeks. If threatened, it loses electric
charges from the sacs.
Pikachu has already been caught!

Lastly, create three Pokemon class objects


and use the .speak() or .display_details()
instance methods for each one.

For more information about any Pokémon


you want to add, see the Pokédex!
Solution:
12.
Modules
# Modules
Welcome to the final chapter of The Legend of
Python!

Here, we are going to take a deep dive into


something called modules.

A module is any file with a .py extension. But more


ideally, a module contains statements, functions,
and class definitions that revolve around a similar
purpose.

By default, Python comes with over 200 modules


that we can use.

Here are some examples:

• random module to generate a random number.


• math module to calculate the square root.
• datetime module to work with dates and times.
Modules are magical because they offer us tools and
method to solve a problem that we'd otherwise have
to write ourselves.

In this chapter, we will use built-in modules first


before creating our own.
# Random Choices
Let's revisit a module we've already worked with before: the
random module!

Remember when we used the .randint() method to generate a


random number in the Magic 8 Ball? Well, there are 22
methods total in the random module.

Here's another method, .choices(), in action:


import random

dice = [1, 2, 3, 4, 5, 6]

print(random.choices(dice))
• The import keyword is used to access the random module.
• The .choices() method will randomly select a single item
by default.
We can also set how many items are randomly chosen with
the k parameter:
import random

dice = [1, 2, 3, 4, 5, 6]

print(random.choices(dice, k=3))
This will return a new list of three items randomly selected
from dice. Every time you run it, the output should be
different.

Note: The k parameter only sets the length of the returned


list from .choices(). This means that a list item may be
included in the returned list more than once.
# Multiple Modules
There are two ways to import two or more modules at
the top of our program:

With multiple import statements:


import random
import math

# Rest of the code...

With one import statement and modules separated by


commas:
import random, math

# Rest of the code...

These two code blocks do the exact same thing.


Application 28:
A gambling machine was invented in Brooklyn
around 1891. Players would insert a nickel and
pull a lever. If it's a good poker hand, you win a
free beer. Soon, many bars in the city had it.
This was a precursor to the modern slot
machine.

Create a slot_machine.py program using


random.

The items are symbols of common fruits and


sevens (7️⃣). In each round, the slot machine
displays three random items. If there are three
sevens, you win!

Final Program Output

Create a symbols list and include the following


items: ' ',' ', ' ', '7️⃣'.

Next, create a results variable that uses the


.choices() method from the random module and
get three random symbols. Make sure to import
the required module at the top of the file!
Then, print each value from results, separated by | pipe
characters:

| |

Lastly, use an if/else statement:

If all of the list items in results are equal to '7️⃣', print


"Jackpot! ".
Else, print "Thanks for playing!".

Solution:
# The from Keyword

What if we wanted to import a piece of a module instead of


the whole thing? We can use the from keyword!

At the top of our file, this keyword goes before the import
keyword:

from module_name import objects

We can use the from keyword to import one or more objects


from a module, such as built-in classes, methods, or variables.

The next example uses the from keyword to import random


module's .sample() method that returns a list of values
randomly picked from another list:

from random import sample

famous_houses = [
' Stark',
' Targaryen',
' Baratheon',
' Greyjoy',
' Lannister'
]

example = sample(famous_houses, 2)

print(f'Example: {example}')
Since the .sample() method was directly
imported, we can just write sample() instead of
the usual random.sample().

By the way, more than one method, variable, or


class can be imported from a module on a single
line.

If we want to import both the .choice() and


.sample() methods:

from random import choice, sample

Note: The random.choice() method randomly


selects and returns a single element from a list.
# The as Keyword
Some module names are long, and it can be unpleasant
to write the word repeatedly. This is where aliasing can
be helpful!

We can nickname a module by using the as keyword.


This is called aliasing.

For example:
import random as rd
Here, we are renaming the random module with a
shorthand, rd.

From this point of the program, the random module


will be known as rd.

The from and as keywords can also be combined:

from random import sample as samp

example = samp(['Stark', 'Targaryen', 'Baratheon',


'Greyjoy', 'Lannister'], 2)

print('Example: ' + example[0] + ' ' + example[1])

Instead of typing sample(), we can use the alias we


assigned it to, samp().
Application 29:
Let's put our newfound knowledge of the from and
as keywords to the test by finding out the surface
areas of the planets in our solar system!

Create a new file called solar_system.py.

Next, import the following at the top of the file:

• From the math module, the pi (π) variable.


• From the random module, the .choice()
method, renamed as ch for short.
Then, copy and paste the following list:

planets = [
'Mercury',
'Venus',
'Earth',
'Mars',
'Saturn'
]

Next, use the ch() method to get a random string


from planets and assign it to a variable called
random_planet.
And use the imported pi (π) variable to
calculate the surface area of a sphere:
𝐴𝑟𝑒𝑎 = 4𝜋𝑟 2
To do this, we'll need to know the radius r for
a given random_planet (rounded to the
nearest kilometer).

Write an if/elif/else statement and assign a


value to r with the following in mind:

• If random_planet is 'Mercury', then r is


2440.
• Else, if random_planet is 'Venus', then r is
6052.
• Else, if random_planet is 'Earth', then r is
6371.
• Else, if random_planet is 'Mars', then r is
3390.
• Else, if random_planet is 'Saturn', then r is
58232.
• Else, print "Oops! An error occurred." to
the console.
Lastly, calculate the area and print the name of
the random_planet along with its area to the
console
Solution:
# Create Your Own Module
As discussed in a previous exercise, modules are
essentially .py files that contain statements and
definitions. So, all of the files that were created for the
exercises up to this point could be imported as a
module!

For example, recall the math functions defined in a


previous exercise.

If saved in a file called calculator.py, we could import it


in a new file like so:
import calculator
Suppose we have another file called main.py, the
functions from calculator.py (add(), subtract(), etc.) can
be accessed and used with dot notation like so:

import calculator
import datetime

calculator.add(3, 4) #7
calculator.subtract(3, 4) # -1
calculator.multiply(3, 4) # 12
calculator.divide(3, 4) # 0.75
calculator.exp(3, 4) # 81

Note: The two files need to be in the same folder.


# datetime Module
Wait, what was that module? No, not
calculator, the other one...

The datetime module specializes in dates and


times. Just like random, it comes with Python
by default and can simply be imported.

In addition to functions, modules may contain


class object definitions with their own defined
methods and properties.

The datetime module has a date object that


accepts the following properties:

• .year: An integer between 1 and 9999.


• .month: An integer between 1 and 12.
• .day: An integer between 1 and the number
of days in a given month.
The syntax for a date is datetime.date(year,
month, day), like so:

import datetime

release_date = datetime.date(1991, 2, 20)


print(release_date) # Output: 1991-02-20

The output shows the date object with a dash


between each part. Also, any single number
gets a leading zero 0.

The .year, .month, and .day properties can be


accessed like with any other class object:

print(f'Python was released in


{release_date.year}.')
# Output: Python was released in 1991.

Retrieving the current date is possible with


the date.today() method:

datetime.date.today()
Application 30:
Let's use the datetime and random modules to make a
birthday card to determine how far your birthday is
from today!
For this exercise, we are creating two .py files in a
separate code editor.

## bday_messages.py

Create a new file called bday_messages.py.

Import the random module.

Then, define a bday_messages list with the following


items:

'Hope you have a very Happy Birthday! ',


'It's your special day – get out there and celebrate! ',
'You were born and the world got better – everybody
wins! ',
'Have lots of fun on your special day! ',
'Another year of you going around the sun! '
Next, use the random.choice() method to get a single
item from the list.

Save this item in a random_message variable.

Let's save bday_messages.py and move to the next part.


## main.py
Create a new file called main.py.

Import both the datetime module as well as


bday_messages (the last file).
import datetime, bday_messages
Next, use the datetime module to create two date objects:

today: Today's date, using the datetime.date.today()


method.
next_birthday: The date for your next birthday, using the
year, month, and day arguments.
A really cool thing you can do with date objects is
addition and subtraction!
time_difference = date1 - date2

Use date subtraction to calculate how many days away


today is from next_birthday. Then, assign the result to a
new variable called days_away.

Then, create a control flow statement:

If today is equal to next_birthday, print the


random_message variable (imported from
bday_messages).
Else, print 'My next birthday is {days_away} days away!'.
The output should look something like this:

My next birthday is 42 days away!


## bday_messages.py

## main.py
# Python Packages
Packages are the folders that contain the modules.

So far, we have been working with singular modules (i.e.,


bday_messages.py). However, a collection of related modules
with a similar purpose is a package.

This is where things get crazy. There are 400,000+ Python


packages in the world (and that's only counting those on PyPI,
the official Python Package Index). You could even build and
register your own module on PyPI for others to use!

Python can tell a regular folder from a package if it has an


__init__.py file, in addition to other .py files.

Note: Some large and specialized packages are called


"libraries".

Here are some examples of packages and libraries in Python:

• NumPy, Pandas, SciPy for data analysis.


• Matplotlib, Seaborn, Plotly for data visualization.
• Scikit-learn, TensorFlow for machine learning.
• Beautiful Soup for web scraping.
• Pygame for mini-games.
• NLTK, OpenAI for chatbots.
• OS, Requests for automation.
These packages make Python one of the most versatile
languages in existence; you can use it to make all sorts of
applications!
# Installing with pip3
While this isn't the only package installer, pip is a popular one!

Note: Installing modules, packages, and libraries is currently


not possible with our online editor on the right. To follow
along, an external editor like VS Code or a command
prompt/terminal will be needed.

Installing packages with pip can be done in the terminal. For


example, to download a popular data plotting library called
Matplotlib:

pip3 install matplotlib

If this command doesn't work or you get a "not found" error,


try running pip install matplotlib.

Note: pip3 is typically used when working with Python 3. It's


an updated version of the old pip, which was mainly for
Python 2 (retired in 2020).

The package can then be imported in a Python file, like so:

import matplotlib

And then to access the various modules, functions, and other


tools, we use . dot notation. For example, we can now use
Matplotlib's pyplot module:

import matplotlib.pyplot
Application 29:

It's time to try out a Python package!

First, make sure pip is installed by running pip3


in a terminal. If not, follow the steps to do so
here.

Next, install a package called wikipedia.

pip3 install wikipedia

Next, create a new file called wiki.py.

Then, use the wikipedia package's documentation


to search for a phrase of your choice.

A few examples could be:

• "Philosophy of life"
• "Python (programming language)"
• "Galaxy"
Try running this program in the terminal with:

python3 wiki.py
Solution:
# Congrats!
Wow. You've reached the end of the last
chapter in The Legend of Python!

In this chapter, we learned about:

• Linking modules with the import keyword.


• Some built-in modules from the Python
standard library.
• Importing specific tools from modules with
the from and as keywords.
• Packages and installing them with pip.
These last few chapters have really tested
your Python programming abilities. You made
it through them all and you should be super
proud of yourself!
The end is just the beginning!
This is where things get exciting, now
that you have all the foundational
building blocks. The world of
programming just opened up in front
of you officially.
We look forward to seeing what you
build. Go forth and make us proud!
ヾ(╥﹏╥)○
P.S. Are you ready to take on the
final project?
Final
Project
# Introduction
One popular game is where we guess an
unknown word or phrase one letter at a
time. If the player(s) can guess the word
within a certain number of attempts, they
will win. Alternatively, when they run out
of attempts, they will lose. This game is
usually played on paper, but what if we
could make it using Python?

Word Guesser Final Output


In this project tutorial, we'll be using:

• The random module


• A code editor (VS Code,)If needed, you
can follow the steps in this project
tutorial to set up VS Code with Python.
1# Create the Word Bank

First, we'll need to create a word bank of all the possible


words to be guessed, and randomly select one to be the
correct answer. This way, the game has an element of
mystery and surprise!

We can do this by installing the random module:

import random

Next, we will make a list that has all the possible words
that can be the answer. This tutorial will only use five
words, but you can add as many as you want!

word_bank = [‘python', ‘JavaScript’, ‘Coding',


‘Programing', ‘Github']
Now, we will randomly choose one of these words to
be the correct answer.

word = random.choice(word_bank)

The random.choice() method is used to randomly


select a word from the word_bank list and to assign it
to the word variable. All possible options have an
equal probability of being chosen.
# Finishing the Setup
We don't want to reveal the letters of the word we're
trying to guess initially, so we need a list of
underscores as "placeholders" to represent letters
that haven't been guessed yet. The number of
placeholders should directly correspond with the
number of letters the word has. (i.e., the word “apple”
is five letters, so there should be five underscores as
placeholders)

guessedWord = ['_'] * len(word)

In Python, you can multiply a list by an integer and


the list will repeat that amount of times. The ['_']
creates a list with a single underscore element, while
the len(word) function returns the length (or number
of characters) in the word string.

We'll finish setting by determining how many


attempts the player has at guessing the word. We
will be using 10 for this tutorial, but you can make it
any number you want.

attempts = 10

Go ahead and save the file and let's move on to the


game loop!
## Game Loop
We need to create a while loop so the player can
continuously guess until they run out of attempts or
guess the word correctly.

while attempts > 0:

Each time the loop runs, we will display the current state
of the word being guessed.
while attempts > 0:
print('\nCurrent word: ' + ' '.join(guessedWord))

The statement is printed on a new line via \n, and joins


the strings in guessedWord together with spaces. For
example, if the state of guessedWord is ['a', '_', 'p', '_',
'e'], the result would be the string "a _ p _ e", making the
program look smoother and less clunky.

Since the guessing is based on user input, we need to


prompt the user to guess a letter and store it in a
variable.

guess = input('Guess a letter: ').lower()

We then need to determine whether or not the guessed


letter is in the correct word. If it is, we loop through
each letter of the word to find which position the letter is
in and replace the placeholder with the guessed letter.
if guess in word:
for i in range(len(word)):
if word[i] == guess:
guessedWord[i] = guess
print('Great guess!')

The for loop goes over each index of the word, to


check every letter. If the letter at position i
matches the player’s guess, it updates the
position in the guessedWord list. We'll print out
some positive feedback to let the user know that
they guessed correctly.

Furthermore, we need to write some code that


handles situations where the user guesses
incorrectly. If the player's guess is not in the
word, the number of attempts decreases by one.
Since attempts is an integer, we must also
convert it to a string to let the player know how
many attempts they have left.

else:
attempts -= 1
print('Wrong guess! Attempts left: ' +
str(attempts))
We're almost done! We'll know if the player
has won the game when they guess all the
letters in the word. If there are no more
underscores as placeholders in the
guessedWord variable, there are no more
blanks left. When the player wins, we will
break the while loop and end the game.

if '_' not in guessedWord:


print('\nCongratulations!! You guessed
the word: ' + word)
break

Finally, we need a condition that results in a


loss for the player when they run out of
attempts and reveal the correct word. This
means that this line of code needs to be written
outside of the while() loop.

if attempts == 0 and '_' in guessedWord::


print('\nYou\'ve run out of attempts! The
word was: ' + word)

Note: We don't need to break the while loop


because the condition was while attempts > 0.
Solution:
# Conclusion
Congratulations! You have completed the
project!

In this tutorial, you used the following to


build a word-guessing game:

• The random module


• List and string operations
• Input/output handling
• Control flow statements
• Now, you can enjoy this game you built
yourself, or with friends!
Visual
Studio tips
YOU DID IT. From your
first "Hello, World!" to
importing modules, you’ve
officially completed the
course. You’ve coded,
debugged, and probably
yelled at the screen once or
twice. Go celebrate – you
earned this .
Dear Programmer,
I want to thank you from the bottom of my heart
for reading this book and for trusting me to be part
of your Python journey . Writing it has been
a special experience for me, but knowing that
someone like you is learning and growing with it
makes it all truly worthwhile.

I hope the chapters helped you build confidence and


curiosity in coding. Remember, every programmer
starts small, and each step you take brings you closer
to creating amazing things .

This is only the first book of our journey together.


The second part of this book is on the way, where
we’ll dive into higher-level concepts and take your
skills even further. I can’t wait to share it with you.
Thank you again for your support, your time, and
your trust . Until then—keep practicing, stay
curious, and never stop learning .
With gratitude,
Batoul Yaz
The End

You might also like