Download as pdf or txt
Download as pdf or txt
You are on page 1of 203

Programming for Kids:

Python Edition
Made by the Bay Coding Club

Written and Edited by

Nathan Gorski
Yixing Xu
Acknowledgements
We would foremost like to thank Ruby Sun for founding Bay
Coding Club, and commissioning this book. Without her, this
book would certainly not exist. We would also like to thank Jing
Li, and the rest of the Bay Coding Club team for their help and
support.

We would like to thank the contributors to openclipart.org and


fontlibrary.org whose free contributions were the backbone of
the aesthetic of this book.

We would like to thank Nicholas Valente for his opinions on


various aesthetics of this book, such as the fonts. He also
pointed out that the text alignment should be justified, rather
than left, only a few days before publication. That was clutch.

We would like to acknowledge Christopher O’Driscoll, Nate


Stover, and Caleb Feltis, who contributed nothing.

Finally, we are compelled to add that the front cover was


designed by Freepik. The back cover was made by Yixing.
Contents
Introduction 6

Project Based Learning 8

Chapter 0: Setting Up Python: 9

Chapter 1: Basics 18
The print command 18
Data & Variables 20
Comments 28
Exercises 29

Chapter 2: Outputs 32
String Concatenation 32
Typecasting 33
F-strings 38
Exercises 40

Chapter 3: Inputs and If-Statements 44


Inputs 44
If-Statements 47
Exercises 56
Chapter 4: Complex If-Statements 62
Else and Elif 62
Custom Conditions 70
Bool Variables 72
Exercises 78

Chapter 5: Lists and the Random Module 83


Creating Lists 83
List Indexing 84
List Functions 86
Random Module 88
Exercises 91

Chapter 6: While Loops and For Loops 95


While Loops 95
The len Function 99
For Loops 101
Using a for loop with range 105
Exercises 109

Chapter 7: Tuples and Dictionaries 113


Tuples 113
Dictionaries 116
Exercises 121
Chapter 8: Functions 124
Simple functions 124
Parameters 128
Return Value 133
Exercises 140

Chapter 9: Turtle 145


Exercises 156

Project Ideas 160

Answers to Multiple Choice Exercises 169


Solutions to Starred Programming Exercises 170
Solutions to projects 179

Glossary of Python Commands 192


Glossary of Vocabulary 194

Index 199
Introduction
Welcome to Python! You’ve probably heard a lot about
computer programming, and all the crazy powerful things that
it is capable of - self driving cars, neural networks, triple A
video games, the list goes on! With all these topics in mind,
programming probably seems like quite a crazy task. Although
computers can do an extremely large number of different
things, most tasks that people do with computers are much
more similar to each other than you might think.

At their heart, all major programming tasks are basically the


same thing - telling your computer what to do using very
precise, very simple step-by-step instructions. But eventually,
a lot of simple actions can all combine to do an incredibly
complex task.

Think of assembling a Lego set. If I showed you a picture of


something that you can make out of Lego pieces, and just told
you to perfectly recreate it, you might have a hard time figuring
it out. But if I gave you instructions for how to build it one brick
at a time, the task suddenly becomes pretty easy.
Programming is sort of like this. You tell your computer how to
do a very complex task, one simple step at a time. And
eventually, all those little steps can combine to make
something incredible.
In general, a Python program is just a list of actions. Every
action is not very complicated - most of them you can type with
less than 30 letters, and you can type many with less than 10.
When you run the program, your computer reads the list of
actions, from top to bottom, and does the small tasks in order.

In this book, you will learn the basic actions that are common
to almost every type of program out there. You might be
surprised to learn that once you finish up this book, you will
know about 80% or more of the actions that you need to learn
in order to make many very complex programs. Most of the
challenge of programming doesn’t come from learning the
small actions. Instead, it can be tricky to see how the tiny
actions fit together and accomplish a big task. But you will
learn this with time.

Everybody has to start somewhere. The authors of this book


definitely did. As did all of the programmers who work at huge
famous companies and do incredible things. We personally
wish you the best of luck in starting!
Project Based Learning
The authors of this book strongly believe that the best way
to learn computer science is to get your hands dirty and learn
by doing. As mentioned in the introduction, this book teaches
a set of tools that you can use to create larger programs. Much
of the challenge of programming is knowing how to use those
tools to make a larger program. We can teach you how to do
that in this book, to some extent. But a large part of learning
how to make complex programs comes from experimenting,
and seeing for yourself how everything relates to each other.

In order to help you with this, some exercises were


included at the end of every chapter. Some ideas for larger
projects are also included at the end of the book. In order to
properly understand the material, it is highly recommended
that you try the exercises and projects, or come up with your
own projects.

In order to help you with the exercises, we have included


solutions for all of the multiple choice questions in the back of
the book. All of the coding problems that have a star (*) next
to the number have a solution in the back. Finally, we have
included sample solutions for all of the projects!
Chapter 0
Setting Up Python

You’re probably very eager to start programming, but before


you do, we have some preparations to do! Unless you already
installed Python on your computer, you probably don’t have
any way of writing and running Python code. If you did install
Python on your computer, and you feel comfortable with how
to run Python scripts, feel free to skip to section one.
Otherwise, you should keep reading!

Online Options
You have a couple of choices for how you want to write and run
Python code. First, there are a few websites that allow you to
write and run your code, all in your browser, without having to
install anything. This has the advantage of requiring very little
setup. However, it makes it harder to make complicated
programs. This won’t be an issue as long as you are studying
from this book. But it could be a problem in the future. Another
disadvantage of an online editor is that it requires an internet
connection.

To be honest, an online option is probably the easiest option for


getting started quickly with Python. If you are running a
Chromebook, or using a tablet, this is definitely your best
choice, as the instructions provided in this book for an offline
Chapter 0: Setting Up Python
setup will not work. If you are on Windows, or macOS, an online
choice is still easy, but using an offline setup is not a bad choice.

Around the time that this


book was written (Feb
2021), two fantastic free
online options are
trinket.io and repl.it. This
book does not include any
further tutorials for how
to use either of these
options. But if you choose to use one, it should be easy enough
to pick up. If you opt for an online editor, you can skip to chapter
1 after you get it set up.

Offline Installation
If you opt to not use an online code editor, you will need to
install Python on your computer. The following instructions
will guide you through the process. These instructions are
current as of February 2021.

First, open your web browser and navigate to python.org.


There should be a tab at the top of the webpage labeled
“downloads.”
Getting Started

If you click on the downloads tab, the web page should


automatically detect what operating system you are using
(Windows, macOS, etc…) and recommend a downloader for
you. For instance, it will say “Download the latest version for
Windows” or “Download the latest version for macOS”.

Right below, there should be a yellow box saying “Download


Python 3.9.1”. The number may be a little different, because a
new version of Python may have been released since the
publication of this book. Click on that yellow box, and an
installer should download to your computer.

Once you download the installer program, run it, and follow the
instructions. It should be easy enough to use. After this, you
have Python installed on your computer!
Chapter 0: Setting Up Python
Setting Up Idle (Offline Only)
Now you’re ready to code, right?
Not so fast. What you just
installed to your computer is a
program which reads Python
code files that you create.
However, you still need a way to
write Python files, and you need
to know how to give them to the
program that you just installed.

For various reasons, writing code on a word processor, like


Microsoft Word, will not work. If you want, you can write code
on Windows using Notepad, or on macOS, using TextEdit.
Although if you do this, running the code is somewhat
annoying. Not to mention that Notepad and TextEdit are pretty
bland!

The recommended way of writing and running code on your


computer is via an Integrated Development Environment or
IDE. An IDE is a program that allows you to write and run your
code all in one program. There are many good IDEs which run
Python. Pyzo, Spyder, Eric, PyDev, and Visual Studio are some
examples, and there are many more. This book will guide you
through how to set up Idle, another such IDE. We chose Idle
because it is pretty good, and very easy to set up. But if you
want to use a different one, there are online resources to help
you with all of the other choices. At a beginner level, it does not
Getting Started
make a huge difference which IDE you use, so don’t put in too
much effort researching all the different IDEs.

Now let’s get started with Idle. One huge advantage to Idle is
that, if you installed Python, it should already be installed on
your computer!

To open Idle on Windows, open up the start menu and type Idle.
It should recommend a program called Idle, whose icon
features the Python logo. Double click on that icon. Doing so
should open up a program called Idle ( continue to next page )

To open Idle on macOS, open up a new terminal, type idle, and


press enter. It should open up a program called Idle ( continue
to next page )
Chapter 0: Setting Up Python
If you properly opened Idle, you should see a window like this:

We will now create a new code file. At the top of the window,
click file > new file. This should open up a new window, which
should look like a blank white square. This is where you will be
writing your Python code for your new code file.
Getting Started
In order to save this new file, at the top of the window, go to file
> save as. Navigate to a desired location on your computer, and
save the file. You can name it whatever you want, but do not
name it python, random, or turtle (I know the latter two sound
a little strange. It will make more sense later).

Great! You have just created a Python file. We want to test


running the file. In your new blank window, type in
print(“hello”). You need to copy it perfectly, character for
character. Then, click file > save.
Chapter 0: Setting Up Python
Then, at the top of the window, click on run > Python module.
If you do, the first window that opened up should have
changed, so that it now has the word “hello.” This means it
worked! Congrats, you now have gotten Idle working.

In general, in order to edit and run Python code, you write


whatever code you want in your editor, save the file
somewhere, and then run it by clicking run > Python module.
Getting Started
It is recommended that you do not create a new Python file
every time you want to code something new. Instead, it is
better that you open up an old file, erase your old code, and
write some new code in there. What you do is completely up to
you, of course. But if you make a new file every time that you
want to do something new, you will have a lot of old Python
files taking up space!

Anyhow, it seems like you are now ready to begin coding! It’s
time to move on to the next section!
Chapter 1
Basics

The print Command

The first simple action that we will learn is the print command.
The print command will print out a word that you tell it to print
out. The easiest way to describe how to use it is to show you.
Type the following code into your editor and run it.

print(“hello world”)

Congratulations! You have just written and run your first


program! You should notice that all the program did was show
the words “hello world”.

If you got an error or you don’t see “hello world”, here are a few
things that may have gone wrong. First, check how you typed
print. Coding is case-sensitive, so something like the
following would give you an error:

Print(“hello world”)
The Print Command
Another error you may have made is forgetting the double
quotation marks like so:

print(hello world)

One frustration that many


people run in to with
programming is that you
have to type in the code
perfectly, or else it won’t
work. Computers are
extremely precise. This is
part of what is good about
them, but it also makes
programming tough for beginners.

What the print command does is that you can type any words
between the “quotation marks” of this command, and when
you run the program, it will print it out and display it on the
console.

print(“Really, that’s all you need to do?”)

Yes, it is. There are a few ways that this can run into trouble, like
if you try to put a third quotation mark inside of the other two.
But as a rule of thumb, anything on your keyboard other than
another quotation mark can go between the quotes. There is
Chapter 1: Basics
also more that you can do with the print command. But for
now, we will start here.

Multiple Print Commands


Remember that a Python program is a list of instructions. So
far, the program that you wrote is just a list of one instruction.
But we can add more instructions to the list. If we do, then all of
those instructions will run if we run the program. For instance,
we could use three print statements, like:

print(“This is a haiku”)
print(“But you would not have noticed”)
print(“If I did not say”)

And it will print out each statement on a new line. Try writing a
three line poem, and print out each line by putting each print
statement on a new line. You’re now ready to move on to learn
some new commands.

Data and Variables

In order to do more powerful things with programs, we will


need to keep track of data. There is lots of information to keep
track of in a program. For instance, in a video game, you might
need to keep track of the player’s position, what level you are
on, your score, and many other things.
Data and Variables
To keep track of information in a computer program, we must
put that information in the memory of the computer. To
remember where we put the information, we need to give a
name to the place where we put the information. Otherwise, it
would be really hard to keep track of where we put things!

A variable is a place in your computer’s memory that has a


name. You may know this word variable from algebra. If it
helps, you can also think about a variable like you learned it in
math.

Making Variables
To make a variable in Python, we use the following format:

var_name = value

The above code claims a new location in memory, and names it


var_name. If you want to give that location in memory a
different name, replace var_name with the name that you
want to give to a place in memory. Replace value with what
information you want to put in that part of memory.

Some examples might include:

height = 5
weight = 500000
age = 22
Chapter 1: Basics
The first example, height = 5, gives the name height to an
area of your computer’s memory. Then, it stores the number 5
in that part of memory. The other examples work in a similar
way.

Try writing a few examples in a Python script and running it. For
now, only put numbers in variables. If everything runs
correctly, it will look exactly like nothing has happened.

Using Variables
In order to use the variable that we just made, you need to do
something with the information that you put into that
variable. One way that you can do this is by printing it out. Try
running the following code:

height = 5
print(height)

It should print out the number 5. Notice that we did not put any
“quotation marks” around the word height. This is to tell
Python that we do not want to print out the word “height”, but
instead print out whatever we are storing in the variable
height.

Variable Names
The name of a variable can be any word made out of numbers,
letters, and __underscores__. The only rule is that it cannot
start with a number. And no spaces are allowed.
Data and Variables

Here are some examples of valid variables names:

number
number2
___
__I_AM_COOL__
XEliteXBallerX2

Here are some examples of things that are not valid variable
names:

#relatable
your mom
000000000000hi

Assignment and Values


In general, whatever information is stored inside of a variable
is called the value of that variable. From here on out, we will call
the information inside of a variable the value of that variable.
Giving a value to a variable is often called assigning a value. For
example, the line height = 5 assigns the value 5 to the
variable height. You might see us use these words later.

If you want to change or update the value of a variable, all you


have to do is repeat the command again.
Chapter 1: Basics

Look at this code:

height = 5
print(height)
height = 10
print(height)

The previous code would first


print out 5, and then print out
10. Why do you think this is?
Think about how a computer runs code. Your computer reads
code from the top down in your program. So when this code
runs, first, it sets the value of height to 5. Then it prints out the
value of height, which is 5, because only the first two lines of
the program have run at this point. Then, the third line runs,
and the value of height gets set to 10. Finally, the fourth line
runs, and prints out the value of height, which is now equal to
10.

Numbers
There are different types of things that we can store inside of a
variable. The main two things we can store are numbers and
words. You can store a number into a variable by just typing
that number after the equals sign, like in the examples above.
Python will also accept decimal numbers, like 1.5. Whole
numbers, like 2, 44, and 99, are called ints, and the decimal
numbers, like 3.14, and 2.5, are called floats. The reason why
Data and Variables
whole numbers and decimal numbers have different names is
because your computer keeps track of them in different ways.

Strings
In order to store words in a variable, you need to put “quotation
marks” around the word. When we surround anything with
“quotation marks”, we call it a string. You can put any
character on your keyboard between the quotation marks to
make a valid string, including spaces. The only exception is that
you cannot put a third quotation mark between the other two.
Here are some examples of strings.

“blue or brown”
“:)”
“hunter2”
“!@#$%^&*()”

Storing a string in a variable is very similar to storing a number


in a variable, it could look like:

favorite_color = “blue or brown”


smiley = “:)”
password = “hunter2”
keyboard_symbols = “!@#$%^&*()”
Chapter 1: Basics
The reason why we use quotation marks for strings is so that we
can tell the difference between strings and variable names.
Otherwise, in a situation like this:

height = 60
dimension = “height”

We would have kind of a mess on our hands. If you do not put


quotation marks around a word, and it is the name of the
variable, the program will use the value of that variable when it
runs. This is not just true in print statements; it works all over
the program. For example, check out this code:

height = 50
dimension = height
print(dimension)

This code would print out 50. But notice that you are not
“storing the variable in another variable.” You are only storing
the current value of that variable in another variable. So if you
run this code:

height = 50
dimension = height
height = 100
print(dimension)

It would print out 50. On the second line, we essentially told the
computer to assign the value of height to the dimension. The
Data and Variables
value of height was 50 when it happened. So after the line
dimension = height, the value 50 was stored in memory in
two different locations: in height, and also in dimension.
When the value of height was changed to 100, the number 50
was still stored in the variable dimension, so the line
print(dimension) printed out 50.

Bools
There is another less common data type called a bool. A bool is
a type of data which is either True or False. Here are some
examples of variables whose value is a bool:

has_a_dog = True
has_a_goat = False
older_than_10 = True

We don’t have much use for


bools now. But they will be very
important later! Now that we
have covered enough of the
basics of variables, you’re
probably wondering why we
even need to use variables
when we can print out the
values by themselves.
Chapter 1: Basics

Comments

As an ending note for the first chapter, we will introduce


something that you can type into your code that doesn’t do
anything. A comment is a line in your code that does not affect
how your program works at all.

Making Comments
The way that you make a comment is by writing a # sign
somewhere in your code. Afterwards, Python will ignore
whatever you write after the # sign. Here is an example:

# The following code will print out “hello world”


print(“hello world”)

The previous code will simply print out “hello world”. The #
sign, and the code after it, will not cause any errors or any other
behavior.

Uses for Comments


But just because comments don’t do anything doesn’t mean
that they aren’t useful. When your code gets really
complicated, it is actually very easy to forget what parts of the
code do. Comments can be helpful for labeling what different
parts of your program do. Another use for comments.
Exercises
Another use for comments is if you have some code that you
don’t want to run, but you also don’t want to delete, for
whatever reason. By adding a # sign in front of every line of
code that you don’t want to run, you can effectively “turn it
off”. Putting a comment in front of a line of code to stop it from
running is called commenting out code.

Anyway, that’s basically all that we’ve got for the first chapter.
Good luck with programming!

Exercises:

1) Which line of code will write “Hello World” to the console:

a. say(“Hello World”)
b. print(Hello World)
c. say(Hello World)
d. print(“Hello World”)

2) Circle all of the strings in the options below

a. True
b. 5
c. 6.7
d. “False”
e. Bay Coding Club
f. 99
Chapter 1: Basics
3) Which of the following makes a variable called cows which
stores the number 7 as an int?

a. cows = 7
b. cows = “7”
c. int cows = 7
d. variable cows = “7”

4) Which of the following would not be a valid variable name?

a. My_variable
b. XxX_my_variable_XxX
c. ____________my_variable____________
d. 8o8___my_variable___8o8
5) If we run the code

animal = “cows”

Which of the following will print out the word “cows”?

a. print(animal)
b. print(“animal”)
c. print(cows)
d. #print(“cows”)
Exercises
*6) What will be the output of the following code:
number = 22
color = “brown”
number = 33
color = “purple”
print(color)
color = “green”
print(color)
print(number)

7) What is wrong with the following code?


my_name = “Ariana”
my_color = “purple”
print(“Hello, my name is”)
print(my_name)
print(“And my favorite color is)
print(my_color)

*8) Write a program that has variables which store three


different favorites of yours (favorite food, favorite color etc…)
and print them out.

9) Write a program that changes the value of a variable three


times. Print out the value after each time you change the value.

10) Write a program that tells a short story, but use variables
for some of the information in the story. The style should look
similar to problem 5 (except your code should work!
Chapter 2
Outputs

String Concatenation

One useful application of variables is string concatenation, also


called string addition. String concatenation allows us to
combine multiple strings, including if a string is stored in a
variable. We use “+” for string concatenation, like so:

nickname = “Tater Tot”


print(“I like being called ” + nickname)

When we run this, it will print “I like being called Tater Tot”
(without the quotation marks). This is because, in the print
statement, we are telling the computer to print the string “I
like being called ” followed by the value stored in our nickname
variable. When the computer runs this code, the computer
finds the value of the nickname variable, which is “Tater Tot”,
and just tacks “Tater Tot” right onto the end of our previous
string, to get “I like being called Tater Tot”.

Concatenating Three or More Strings


We have just one problem. While the code will run just fine, we
need to add a period at the end of a statement, or else it is
grammatically incorrect. Can we add another string containing
Typecasting
just a period? Yes! Actually, we can use string concatenation
and add as many strings and variables together as we want. So
if we want to add a period to the end of our print statement, it
would look like this:

nickname = “Tater Tot”


print(“I like being called ” + nickname +
“.”)

When this code is run, it will print “I like being called Tater Tot.”

Typecasting

Now let’s experiment some more with string concatenation.


We’ll throw the height variable back into the mix and print a
statement using string concatenation, like so:

nickname = “Tater Tot”


height = 50
print(“I like being called ” + nickname + “,
because I am ” + height + “cm tall.”)

Note that the final two lines of this code are supposed to be on
one line. The page is not wide enough to fit what we want!
Whenever code is not indented, it means that it is supposed to
go with the previous line.
Chapter 2: Outputs

That print statement was really annoying to type in! And


worse yet, when we try to run it, there is an error that pops up
that reads:

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

This error is being identified as a


TypeError, which is
essentially an error that occurs
when Python expects it will run
into one type of data (int, string
etc…) and then finds something
else. The reason why we are
getting this error is because
when you use a + for string
concatenation, Python expects another string after the + sign.
But the value of height is an int, not a string. This is not what
Python expects.

Converting to a String
Remember that ints are whole numbers and strings are
anything surrounded by double quotation marks. In order to be
able to run the print statement, we will have to make the
value of height into a string. We can do this through
typecasting. Typecasting is when we convert the type of one
piece of data into a different type. To do this, we can use:

str(non-string)
Typecasting
Using this code does all of the heavy lifting of converting for
you. For example, 17 is an int. But if you type str(17), the
program will treat this exactly the same as it would treat a
string of the number 17. So, as far as Python is concerned,
str(17) is the exact same as “17”. This works with other types
of data, too. So str(3.14) is the same as “3.14” and
str(True) is the same as “True”.

And actually, if the value of a variable is an int, then putting


that variable between the parentheses of str() will be the
same as a string version of that value. So if we have a variable
called a, whose value is 16, then str(a) will be treated the
same as the string “16”. When you do this, it does not actually
affect whatever is stored in that variable in the long term.
Using str(a) is kind of like telling Python: “Just this once, act
like a is a string”.

Converting to Other Data Types


On a related note, you can use a very similar command to use a
string as an int.

int(non-int)

Is used to convert non-int values into ints. Inside the


parentheses, you can only put a float, or a string whose
characters are only digits (i.e. “17”). So, as far as Python is
concerned, typing int(“17”) is the same as typing 17.
You can do something similar for the float and bool data types.
Chapter 2: Outputs
Using Typecasting With Concatenation
Anyway, now that we know how to convert non-strings into
strings, we can debug our code and fix our print statement so
that it can actually run. We will typecast the height variable
into a string. If we do so, it will look like this:

nickname = “Tater Tot”


height = 50
print(“I like being called ” + nickname + “,
because I am ” + str(height) + “ cm tall.”)

This effectively prints out “I like being called Tater Tot,


because I am 50cm tall.”

Something you may be


wondering is why we
would even want to use
ints if they cannot be
printed out when
concatenated with other
strings and variables. The
reason why is because we
can use mathematical
operations with ints and
floats in Python.
Typecasting
Here is an example:

nickname = “Tater Tot”

height = 50
growth_rate = 10
years = 10

final_height = height + growth_rate * years

print(“I like being called ” + nickname +


“, because I am ” + str(height) + “cm tall.”)

print(“But don’t worry! My doctor says I am


growing at a rate of 10cm per year.”)

print(“That means I will be ” +


str(final_height) + “cm tall in 10 years!”)

This will print out :

I like being called Tater Tot, because I am 50cm tall.


But don’t worry! My doctor says I am growing at a rate of
10cm per year
That means I will be 150 cm tall in 10 years!

As you can see, we use + for addition and * for multiplication.


Other mathematical operations we can use are – for
Chapter 2: Outputs
subtraction and / for division. This is actually incredibly
important for programming large programs!

Permanent Typecasting
As you have noticed, typecasting will not change the type of the
value of a variable long term. But what if you actually did want
to change the type of the value of a variable forever? Actually,
you can do this with typecasting as well. The following code
example demonstrates this:

age = “24”
age = int(age)

The second line of the previous code will permanently change


the value of age to be an int. The term int(a) is the int version
of whatever was stored in age. The line age = int(age)
assigns to age the int version of whatever it used to store. This
turns the value of age into an int. Pretty nifty!

F-Strings

Now, it may seem a bit tedious to have to keep adding variables


and strings together, typecasting, and closing the double
quotation marks. This is why we have another basic method for
combining strings and variables: f-strings!
F-Strings
An f-string is formatted with “f” added in front of the string.
You have to add “f” in front of your string to indicate that it is
an f-string. The great things about f-strings are that they are
very flexible in terms of typecasting. f-strings are typically
more efficient to use than string concatenation. Because f-
strings are so flexible, you might think that the f stands for
“flexible”. Actually, the f stands for “formatted”. This is a
reference to some older programming languages.

Using F-Strings
The idea behind f-strings is that you don’t need to put + signs
around things that you want to put into the string, and use str()
whenever that thing is not also a string. Instead, you just write
the thing that you want to put in the string inside of {curly
brackets} and call it a day. It is easiest to just see an example.
Check out how we can rewrite the previous code, but with f-
strings:

nickname = “Tater Tot”


height = 50
print(f“I like being called {nickname},
because I am {height} cm tall.”)

print(f“But don’t worry! My doctor says I am


growing at a rate of 10cm per year.”)

print(f“That means I will be {height + 10*10}


cm tall in 10 years!”
Chapter 2: Outputs
That’s way easier! In fact,
it’s so much easier that
you are probably
wondering why we did
not just start with f-
strings. Just like lots of
things in code, there are
times when it is better to
do it the old-fashioned
way. Plus, we secretly got
to tell you about how
variables are different
types, how to convert types, and how to do math. But for the
sort of thing that we are doing here in chapter 2, f strings are
definitely easier.

Exercises

1) Which of the following will print out the number 13

a. print(int(“thirteen”))
b. print(3+2*4+1)
c. print(4*4-(2+1))
d. print(“1” + int(3))
Exercises
2) Say we run this code:

a = “John Doe”
b = 7

Which code would print out:

John Doe has 7 cows

a. str(a) + “ has ” + b + “ cows”


b. str(a) + “has” + str(b) + “cows”
c. a +“has” + str(b) + “cows”
d. a + “ has “ + b ” + “cows”
e. a + “ has ” + str(b) + “ cows”

3) Say we run this code:

a = “Molly”
b = 999

Which code would print out:

Farmer Molly has 999 cows

a) print(“Farmer ” + a + “ has ” + b + “
cows”)
b) print(f”Farmer {a} has {b} cows”)
c) print(f“Farmer {a} + has + {b} cows”)
d) print(“Farmer {a} has {b} cows”)
Chapter 2: Outputs

4) Which of the following statements does not change the type


of any data?

a. str(14)
b. int(2.0)
c. bool(“True”)
d. str(“False”)

5) Which of the following values of a and b will cause the


following code to give an error?

print(a + b)

a. a = “a”, b = “b”
b. a = True, b = 4
c. a = 2, b = 3.0
d. a = 2, b = 3

6) Write a program that makes a variable called pets, which


stores how many pets you have. Then use concatenation to
print it out in the following format:

I have 99 pets
Exercises
7*) Write a program that makes variables called town, state,
and country, that store the name of your town, state/province,
and country. Then use concatenation to print them out in one
line. The output should look like this:

Chicago, Illinois, United States

Another output could look like this:

Charlottetown, Prince Edward Island, Canada

8*) Make a variable for how many years old you are. Then, write
a program that prints out how many seconds old you are. Treat
one year as 365 days, one day as 24 hours, etc.

9) Find the line in the following code that does not work, and
correct it:

name = “John Doe”


age = 45
color = “Brown”
print(“Hello, my name is ” + name + “ I am ”
+ age + “, and I like the color ” + color)

10) Write a program that prints out your name, age, and
favorite color, like in problem 9 (except your code should
work). However, use f-strings, and do not use +
Chapter 3
Inputs and If Statements

Inputs

Part of what makes computer programs interesting is that they


are interactive. Currently, we can write programs that print out
words. But if you want to read words, you can more easily write
them down on a piece of paper.

There is an easy way to ask questions to whomever is running


the program. In order to do this, you use the input function.
The basic way that we use it is like this:

new_variable = input(“Question?”)

Basically, when you run this, it will print out “Question?” - or


whatever else you type between the quotation marks. Then, it
will give you a chance to type in an answer. After you type it in,
press enter when you are done. After that, Python will figure
out what you typed in, and then store it in the variable
new_variable (or whatever you called it).

Just like anything else, it is easiest to learn if you see some


examples, and experiment with it yourself.
Inputs
One way of using the input command could look like this:

name = input(“What is your name?”)


print(f“Hi, {name}!”)

When showing how the code runs, output from the program
will be in black, and input typed in by the user will be in green.
The code just above this paragraph might run like:

What is your name?William the conqueror


Hi, William the conqueror!

To be clear, the green


text William the
conqueror is an example
of something that could
possibly be typed in by
the person running the
code. The user could type
in anything else, and it
would work just as well
(try it yourself!).

New Lines
One annoying thing about this code is that you type your
response on the same line as the question. In order to get
around this, you can add \n to the end of your question. In
general, if you put \n inside of a string, it will break it up into
Chapter 3: Inputs and If-Statements
two different lines. It isn’t just for using input, and you can use
it for print also. Notice that you want to add \n. You do not
want to type /n. Here is an example:

print(“This will print on\ntwo different


lines”)

Will print out:

This will print on


two different lines

Anyway, if you want input to let you type your answer on a new
line, put \n on the end. We can rewrite our previous example as

name = input(“What is your name?\n”)


print(f”Hi, {name}!”)

Now it will work like this:

What is your name?


Naruto
Hi, Naruto!

The input Statement Gives You a String


It is important to note that the data you get from an input
statement is always a string. So you may not get the results you
want if you try doing math with inputs.
If-Statements
For example, the following code:

num1 = input(“Type a number\n”)


num2 = input(“Type another number\n”)
sum = num1 + num2
print(sum)

Will work like this:

Type a number
2
Type another number
4
24

The reason that this will be the output is that num1 will store
the string “2”, and num2 will store the string “4”. So the line
sum = num1 + num2 will assign sum the values of num1 and
num2 concatenated with each other, which is the string “24”.
You can get around this issue by typecasting, and turn each
variable into an int.

If-Statements

So now you can ask for inputs, but you still don’t really know
how to do anything with them. So far, even with inputs, our
code does almost exactly the same thing every time we run it.
What we can do with inputs might work for making something
Chapter 3: Inputs and If-Statements
like a MadLib. But in general, it does not give you much power.
In order to make the program do different things depending on
what you typed in, you need to use if-statements.

An if-statement is a way of testing whether or not two things


are equal to each other. The way of using one is like this:

If thing1 == thing2:
Do something

In order to use an if-statement, you replace thing1 and


thing2 with two different things that you want to check if they
are equal. Those two things could be variables, or data. If one of
those things is a variable, it will check if the value of that
variable is equal to the other
thing. Also, you must
replace Do something with
some extra code that will run
if the two things are equal. It
is difficult to explain this
without any examples. Here
is one way of using an if-
statement:

name = “Naruto”
if name == “Naruto”:
print(“You must like ramen!”)
If-Statements
In the if statement, we wrote name == “Naruto”. If the value
of name ends up being equal to “Naruto”, then the code under
the if-statement will run. Since the value of name is indeed
equal to “Naruto”, it will print “You must like ramen!”

Assignment Operator vs Comparison Operator


You might be wondering why we are using the == instead of the
= sign. This is because the = sign has another use already. Do
you remember where you’ve used it before? That’s right. We
used the = sign to assign values to variables. Because of this, it
is called the assignment operator. That is why we can’t use it to
test whether two things are equal to each other. Instead, we
have to use ==, which we call a comparison operator. We call it
a comparison operator because we use it to check if the values
are equal. It might sound silly that we have to do this, but in
some cases you might want to use both = and == in the same
line, in which case it would get kind of confusing if it was just a
= for both. We will explore this more in the next section.

Also, the part of the if-statement which uses the == sign is


called the condition of the if-statement.

Using If-Statements With Input


Now let’s get back to our previous example. In that code, we
made a new variable, and then immediately used it in an if-
statement. There is not much reason to do that when writing a
program. So, a more real-life application is using an if-
statement with an input command. When we do this, you can
Chapter 3: Inputs and If-Statements
create a program that simulates having a conversation with
you. For instance:

name = input(“What is your name?\n”)


print(f”Hi, {name}!”)
if (name == “Naruto”):
print(“You must like ramen!”)

This will print “You must like ramen!” but only if the user types
in “Naruto” for the input. What happens when the user inputs
anything other than “Naruto”? Well, let’s try it out. When you
try it out, you’ll find that it prints:

What is your name?


Sakura
Hi, Sakura!

Thus, when you type


anything other than Naruto,
the program won’t do the
other print statement!
If-Statements
Code Inside of an If-Statement
Also, you can have as much code as you want to run inside an if
statement, as long as you make sure to indent all of it. So the
following code:

name = input(“What is your name?\n”)


print(f”Hi, {name}!”)
If name == “Peppa Pig”:
print(“Get”)
print(“off”)
print(“my”)
print(“lawn”)
print(“you”)
pring(“pig!”)

Will run like this:

What is your name?


Peppa Pig
Hi, Peppa Pig!
Get
off
my
lawn
you
pig!
Chapter 3: Inputs and If-Statements
But if you type in a different name, it will run like this:

What is your name?


Steve
Hi, Steve

It is really important that all of your indented code is indented


exactly the same, or else your code won’t work. A common
mistake that beginners make is that one line of the indented
code is little to the left or to the right, and it causes the entire
program to crash! So this code, for example, will not work

if name == “Karen”:
print(“I”)
print(“feel”)
print(“sorry”)
print(“for”)
print(“you”)

In order to fix it, you would need


all of the prints to perfectly line
up! But as long as you’re careful,
you can put basically any code
that you can imagine inside of an
if statement.
If-Statements

If-Statements Inside of Other If-Statements


You can even put other if statements inside. If you do, you
would need to double indent the code under the second if
statement. Here is an example:

name1 = input(“What is your first name?”)


name2 = input(“What is your last name?”)
print(f”Hi, {name1}!”)
if name1 == “Pig”:
print(“You are a pig.”)
if name2 == “Peppa”:
print(“You are Peppa Pig!”)

The output of the previous code will be different depending on


what you type in:

What is your first name?


Nathan
What is your last name?
Gorski
Hi, Nathan

What is your first name?


Wilbur
What is your last name?
Pig
Hi, Wilbur
Chapter 3: Inputs and If-Statements
You are a pig.

What is your first name?


Peppa
What is your last name?
Pig
Hi, Peppa
You are a pig.
You are Peppa Pig!

In the first case, name1 is equal to “Nathan”, so the condition in


the first if statement is not true. Therefore, the program will
not continue after the first if statement.

Inthe second case,


name2 is equal to “Pig”,
so the code under the
first if statement ends
up running. The code
under the first if
statement includes
another if statement,
where the condition is
name1 == “Peppa”.
This is not true, in the second case, so the code under the
second if statement does not run.
If-Statements
In the third case, we again have name1 being equal to “Peppa”,
so the first if statement ends up being true. But also, name2 is
equal to “Pig”, so the code under the second if statement also
runs.

So now you know how to put if statements inside of other if


statements!

Code After an If-Statement


As one final note before we end the section, you can put code
that will run after an if statement simply by not indenting the
code afterwards. The following code:

name = input(“What is your name?”)

print(“Always prints before the if!”)

if name == “Sanhita”:
print(“Your name is Sanhita”)

print(“Always prints after the if!”)

Here are some ways that the previous code might run:

What is your name?


Arjun
Always prints before the if!
Always prints after the if
Chapter 3: Inputs and If-Statements
What is your name
Sanhita
Always prints before the if!
Your name is Sanhita!
Always prints after the if!

So as you can see, you can also put code after an if-statement
that will always run.

This is all of the basics of if-statements that you need to know.


You can do surprisingly a lot with just this knowledge alone. In
the next section, however, we will be working on many
different variations of if-statements!

Exercises

1) Which of the following is the correct use of the input


statement:

a. name = input(What is your name?)


b. name = input(“What is your name?”)
c. input(name)
d. “What is your ” + input(“name”)
e. What is your + input(name)
Exercises
2) What will be the output of the following code:
name = “Jerry”
if name == “Jennifer”:
print(“Your name is not Jessica”)
if name == “Jessica”:
print(“Your name is not Jerry”)
if name == “Jerry”:
print(“Your name is not Jennifer”)

a) No output
b) All three print statements will print
c) Your name is not Jessica
d) Your name is not Jerry
e) Your name is not Jennifer

3) Which print statements will run in the following code?

first_name = “Jesse”
last_name = “Smith”
if first_name == “Jesse”:
print(“Hi, Jesse!”) (i)
if last_name == “James”:
print(“It’s Jesse James!”) (ii)

a) Just (i)
b) Just (ii)
c) Both (i) and (ii)
d) Neither (i) nor (ii)
Chapter 3: Inputs and If-Statements

4) Which print statements will run in the following code?

name = “Jason”
if name == “Natsuki”:
print(“Hi, Natsuki!”) (i)
print(“I’m so happy to see you!”) (ii)

a. Just (i)
b. Just (ii)
c. Both (i) and (ii)
d. Neither (i) nor (ii)

5) Which print statements will run in the following code?

name = “Maria”
if name == “Eugene”:
print(“What’s up, Eugene!”) (i)
print(“I’m so glad to see you!”) (ii)

a. Just (i)
b. Just (ii)
c. Both (i) and (ii)
d. Neither (i) nor (ii)
Exercises
6) Write a program that asks you to type in your name, and then
gives a personal message to you, depending on what name you
type in. Your program should support at least 4 names.

7) Make a program that asks you to type in your name. If they


type in a certain name, have them ask another question, and
respond depending on how they answer. The program might
look like:

What is your name?


Gary
Hi, Gary!

What is your name?


Louisa
Hi, Louisa!
What is your favorite food?
spaghetti
I like spaghetti as well!

Hint: put an input inside of an if statement.


Chapter 3: Inputs and If-Statements
8*) Write a program that asks for a color. Then, it prints out a
fruit that is that color. For example, running the program might
look like:

Please say a color


blue
blueberries

make the program check at least four colors.

9) Write a program that asks for a color and a fruit, and then
says whether or not the fruit is that color. For example, running
the program would look like:

What is a color?
Green
What is a fruit?
Apple
Apples are green

What is a color?
Brown
What is a fruit?
Blueberries
Blueberries are not brown

Make the program take at least 2 fruits and at least 2 colors.


Exercises
10*) Write a program that asks you to guess a number, and it
tells you if you got it right or wrong. It could look like this:

What is the number?


5
WRONG!

What is the number?


8
Correct!

Hint: Store the response in a string, and change the value of the
string in the if-statement.
Chapter 4
Complex If-Statements

Else and Elif


Else -Statements
In the previous section, we learned how to do a lot of stuff with
if statements. And what you learned will get you very far. But
there are other add-ons which make if statements more
powerful.

One add-on to an if-statement is an else-statement. In order


to explain this, we will first refer back to the previous example.
Here is one of our old code examples for if-statements which
makes a conversation:

name = input(“What is your name?\n”)


print(f”Hi, {name}!”)
if (name == “Naruto”):
print(“You must like ramen!”)

Well, it doesn’t seem fair that only Naruto gets a friendly


comment like “You must like ramen” and no one else does. We
should be able to give a different fun comment to different
people, depending on what they type in. But it would be
difficult to make an if statement for every possibility out there.
There are so many names!
Else and Elif
Fortunately, we have else-statements. Else-statements are
formatted very similar to if statements, except that we don’t
compare anything. An else-statement goes after an if
statement, and it runs whenever the condition in the if
statement is false. Here is some sample code which uses an else
statement:

name = input(“What is your name?\n”)


print(f”Hi, {name}!”)
if (name == “Naruto”):
print(“You must like ramen!”)
else:
print(“Very nice to meet you! :)”)

Now when we run it:

What is your name?


Sakura
Hi, Sakura!
Very nice to meet you! :)

If we run it again

What is your name?


Naruto
Hi, Naruto
You must like ramen!
Chapter 4: Complex If-Statements
So if the condition in the if statement is true, the code
underneath the if statement will run. Otherwise, the code
under the else statement will run.

Nested Else-Statements
Just like an if statement, you can put whatever you want in an
else-statement, including other if statements and else
statements. You just need to make sure that all of the
indentations work out correctly. Here is an example:

guess = input(“Guess a number from 1-10”)


if guess == “4”:
print(“Correct!”)
else:
guess2 = input(“Nope! Try again!”)
if guess2 == “4”:
print(“You got it! Nice!”)
else:
print(“Sorry, wrong again!”)

This code essentially gives you two guesses to correctly guess


the number 4. Here is one way that the code could run:

Guess a number from 1-10


5
Nope! Try again!
4
You got it! Nice!
Else and Elif
In this case, the first guess is equal to 5, so the code in the first
if statement does not end up running. Thus, the code in the
following else statement will run. That else statement contains
an entire other input-if-else combination, which runs how we
would expect it to.

You might find it strange that the code checks if the input is
equal to the string “4” rather than the number 4. It’s because
input always gives you a string, even if you type a number.

Elif-Statements
In case you are not happy with the options given by if
statements and else statements, there is actually another type
of thing which lets us check even more options. That other
thing is elif statements. The term elif is short for else if.
Basically, you can put elif after an if statement. It acts sort of
like a “back-up” if statement. An Elif-Statement comes with a
condition, and code goes under it, just like an if-statement. If
the condition of the if-statement ends up being false, then the
code will check the condition of the elif statement, and if that
condition is True, the code under the elif-statement will run.
Here is an example.

name = input(“What is your name?”)


if name == “Gub Gub”:
print(“You have a weird name.”)
elif name == “Pig”:
print(“You are a pig.”)
Chapter 4: Complex If-Statements

Here is one way the previous code could run:

What is your name?


Gub Gub
You have a weird name.

Here is another way it could run:

What is your name?


Pig
You are a pig.

But if the user types in neither Peppa, nor Pig, then nothing will
print out after. The code will look like this:

What is your name?


Nathan

Here is the reason for this.


First, if the user types in Gub
Gub, the condition of the
first if statement will end up
being true, so it will print
out “You have a weird
name”. Then, because the
first if statement was true,
the program does not check the elif statement.
Else and Elif
If the user types in “Pig”, then the condition of the first if
statement ends up being false, so the program checks the elif
statement. The condition of the elif statement ends up being
true, so the program prints out “You are a pig”.

If the user types in something that is neither Gub Gub nor Pig,
then the condition of the first if statement ends up being false.
Then, the program checks the elif statement. The condition of
the elif statement also ends up being false, so nothing gets
printed out.

Multiple Elif-Statements
You can actually put as many elif statements as you want, one
after another. Each elif statement will only be checked if the
previous elif-statement gets checked and its condition is false.
And also, you can actually put an else statement after a bunch
of elif statements. The else statement will end up triggering if
the if statement ends up being false, and also all of the elif
statements are false.

We’ll show an example of this on the next page. It’s pretty long,
so we had to put it on the next page so that it didn’t get split up.
Chapter 4: Complex If-Statements
Here is an example that uses multiple elif statements:

name = input(“What is your name?”)

if name == “Jerry”:
print(“I remember you!”)
elif name == “Rachel”:
print(“You were that girl I liked!”)
elif name == “Eli”:
print(“Your name looks like elif”)
elif name == “Wendy”:
print(“You should open a restaurant”)
else:
print(“I don’t have any fun comments to
make about your name”)

Here are two ways that the code could run:

What is your name


Eli
Your name kind of looks like elif

What is your name?


Jason
I don’t have any fun comments to make about your name
Else and Elif
In the first example, if
you type in Eli, it sets the
value of the variable
name to Eli. When the
first if statement gets
checked, its condition is
name == Jerry. Since
the value of name is Eli,
this condition is false.
Because of this, the first
elif statement is then
checked. The first elif
statement has the
condition
name == Rachel. This is again false, so the second elif
statement is checked. The condition of the second elif
statement is name == Eli. In this case, the condition is True,
so the print statement under the second elif statement will
run and print out “Your name looks kind of like elif”. Then,
because the condition of the second elif-statement ended up
begin correct, the elif statement after it will not be checked,
and the code under the else-statement will not run.

In the second example, the string “Jason” gets passed in for the
value of name. The condition of the if-statement is not true, in
this case. The code will then go down each of the elif-
statements, one by one, and all of their conditions will end up
Chapter 4: Complex If-Statements
being false. Finally, the else-statement is reached, and since
none of the conditions of the if-statement or any of the elif-
statements were true, the code under the else-statement will
run.

Custom Conditions

We learned that the condition of an if-statement is the part


with the ==. Actually, using an == is just one of many different
types of conditions that you can use! Rather than explaining
them all, we thought that it would be easier to put them all into
a table. The table is on the next page!
Custom Conditions
Custom Conditions Table

Name Sign Example


Equals == if name == “Naruto”:

Checks if the variable name stores the


value “Naruto”
Not equal != if name != “Sakura”:

Checks if the variable name does not


store the value “Sakura”
Greater than > if power_level > 9000:
(numbers
only) Checks if the value of power_level is
greater than 9000
Less than < if weight < 333:
(numbers
only) Checks if the value of weight is less
than 333
Greater than >= if floor >= 13:
or equal to
(numbers Checks if the value of floor is greater
only) than or equal to 13

Less than or <= if gallons <= 2:


equal to
(numbers Checks if the value of gallons is less
only) than or equal to 2
Chapter 4: Complex If-Statements

Bool Variables
Comparing Things
Now it’s time to get a little more technical. It turns out that
everything in the previous table is actually an operator, sort of
like the math operators +, -, * and /. I know that it may sound
strange, but they are. The + operation takes two numbers and
turns them into a third number (by adding them together).
Actually, the == sign takes two different things and turns them
into a bool, which is equal to True if those two things are equal,
and False if those two things are not equal. It is similar for all of
the other symbols. Seriously, try it for yourself. The following
code:

a = (5 == 5)
b = (3 > 4)
c = (3 >= 3)
d = (4 != 4)
print(a)
print(b)
print(c)
print(d)

Will print out:

True
False
True
False
Bool Variables
In the previous code,
the first line contains
(5 == 5). The (==)
symbol checks if the
two things next to it
are equal. The two
things next to it are
both the number 5, so
the entire thing
simplifies down to
True. Similarly, the
second line contains
(3 > 4). The ( >) symbol checks if the thing to the left is greater
than the thing to the right. The thing to the left of it is 3, and
the thing to the right is 4. Since 3 is not greater than 4, the
whole thing turns into False.

Bools and If-Statements


And actually, it turns out that if-statements rely completely on
bools for everything that they do. Whenever you write the word
if, the thing after it should have type bool. If that bool is equal
to True, the code of the if statement will run. If that bool is
equal to False, the code of the if statement will not run.

As far as Python is concerned, writing (thing1==thing2) is a


bool, because the == sign turns compares thing1 and thing2,
and turns it into a bool. That is why we can write if-statements
Chapter 4: Complex If-Statements
like if thing1 == thing2. You can also put a variable which
stores a bool after an if-statement. Try this:

if True:
print(“This will always run”)
a = True
if a:
print(“This will always run”)
b = (3 == 3)
if b:
print(“This will always run”)

The previous code will print out “This will always run” three
times. This is because, in each case, the thing after the if-
statement was a bool!

Bool Operations
It turns out that there are three more math operations that we
can use with bools. You may have heard of them if you have any
knowledge of logic gates. They also come up in Minecraft
redstone. Those three operations are and, or, and not.

The operations and and or are kind of like the + operation. The
+ operation takes in two numbers and turns them into another
number. The and and or operations take in two bools, and
turns them into a third bool. The output of and will be True if
both of the inputs are True. The output of or will be True if at
least one of the inputs is True.
Bool Variables
This table shows the possible values of the and, and or

and or
True and True = True True or True = True
True and False = False True or False = True
False and True = False False or True = True
Fales and False = False False or False = False

The operation not only takes in one input, kind of like square
root. Not should be followed by a bool, and flips the value of
that bool. So, the expression not True is equal to False. The
expression not False is equal to True. So to recap, here are
the values of not:

not True = False


not False = True

Bool Operations and If-Statements


So why are we learning about and, or, and not? Well, actually,
because if-statements rely on bools as their inputs, we can use
these operations to make much more complicated if-
statements! We will see an example on the next page!
Chapter 4: Complex If-Statements
Here is an example:

height = 30
age = 80

if (age >= 70) and (height >= 30):


print(“You are old and tall!”)

Here, the bool (age >= 70) is True if the value of the variable
age is greater than or equal to 70. The bool (height >= 30) is
True if the value of the variable height is greater than 30. The
bool (age >= 70) and (height >= 30) will be True if both
(age >= 70) is True, and also (height >= 30) is True. Here is
a more complicated example:

age = 16
took_class = True

if (age >= 16 and took_class) or (age >= 18):


print(“You can get your drivers’ license!”)

In the previous if-statement, remember that age >= 16 is a


bool, which is True if the value of age is greater than or equal to
16. The variable took_class stores a bool. So (age >= 16 and
took_class) will be True if both (age >= 16) is True and
took_class is True. The expression (age >= 18) is True if the
Bool Variables
value of age is greater than
or equal to 18. And the or
operation makes the whole
line True if either (age >=
16 and took_class) is
True, or if (age >= 18) is
True. Therefore, this code
will print out ”You can get
your drivers’ license!” if
either age is greater than or
equal to 16 and took_class
is True, or if age is greater
than or equal to 18.

So now, you really know just about all there is to know about if-
statements, and you know some stuff about bools as well! It’s
important to practice this stuff, since conditional statements
are the backbone of programming.
Chapter 4: Complex If-Statements
Exercises:

1) If we run this code:

answer = input(“What is your answer”)

if answer == “a”:
print(“Apple”)
if answer == “b”:
print(“Banana”)
if answer == “c”:
print(“Pear”)
else:
print(“Lime”)

When we run the program, what answer would not make the
program say Lime?
1. “a”
2. “b”
3. “c”
4. “d”
Exercises
2) If we run this code:

a = 12

Which of the following code will print out the word “correct”

a.
if a = 12:
print(“correct”)

b.
if a == 11:
print(“incorrect”)
else:
print(“correct”)

c.
if a === 13:
print(“incorrect”)
else:
print(“correct”)

d.
if a == 12
print(“correct”)

e.
if a = 11:
print(“incorrect”)
else:
print(“correct”)
Chapter 4: Complex If-Statements

3) Say we have the following program

if a == 4:
if b == 3:
print(“apple”)
elif b == 1:
print(“banana”)
elif a == 2:
if b == 3:
print(“watermelon”)
elif b == 1:
print(“cantaloupe”)

What values do we need for a and b in order to print out


watermelon?
a. a=2 b=1
b. a=2 b=3
c. a=4 b=1
d. a=4, b=3

4) What will be the output of the following code?


a = True and (False or (False or True) )
b = ( not (False and True) ) and True
print( str(a) + “, “ + str(b) )

a. True, True
b. True, False
c. False, True
d. False, False
Exercises

5) Which input option will make the following code not print
out anything?

age = input(“How old are you?”)


if int(age) > 0 and int(age) < 15:
print(“you are pretty young”)
elif int(age) < 60:
print(“you are neither old nor young”)
else:
print(“you are really old!”)

a. -4
b. 10
c. 70
d. All inputs will cause the code to print something.

6) Make a program that asks questions about the user, and see
if they are similar to you. For example, running this program
might look like:

What is your favorite TV show?


Peppa Pig
That is not my favorite TV show.

What is your favorite color?


Green
That is my favorite color!
Chapter 4: Complex If-Statements

7*) Come up with requirements to join a club. Then, use inputs


and an if statement to see if the user is able to join your club.
The if statement should use boolean expressions like and, or,
and not. The club should have at least three requirements.

8) Make a program where the user types in a number, and the


program outputs if that number is small, medium, or large. We
say that a number is small if it is less than 20, and large if it is
larger than 80.

9*) Make a program where the user has to guess a number. The
program should say if you guessed it. If you did not guess the
number, the program should say if your guess was too small, or
too large.

10) Make a program where the user has to guess three


numbers. If they guess all of them correct, say so. Otherwise,
say which numbers they guessed wrong.
Chapter 5
Lists and the Random Module

Creating Lists

So far, we have learned about several data types: ints, strings,


floats, and bools. However, there are actually a few other types
of data that you can store in variables. One additional type of
data is a list. A list is more or less what it sounds like: a list of
things.

The way that you make a list in Python and store in in a variable
is like this:

name = [value1, value2, ... ,final_value]

Where name is the name that you want to give to a new variable
and each value1, value2, ... final_value are replaced
with whatever you want to put in the list. We put the ... in the
example to mean that you can make the lists as long as you
want. You could make lists with any number of things in it, as
long as there is enough memory on your computer to store it!
There could also be one thing, or even zero things if you want.
A list with zero things in it would just be [ ]
Chapter 5: Lists and Random Module
Storing Data in Lists
You can store any data type that we have learned about in a list.
You can store ints, strings, floats, bools, and even other lists!
Also, the type of thing in the list does not need to match. For
example, you list does not need to be only ints, only strings, etc.
As a real example, here is how you could make a list that stores
various information, and stores that list in a new variable

my_list = [45, “hi”, True, 33, 3.14]

We call the things inside of the list the elements of the list.

List Indexing

If you want to find out what is at a certain position in the list,


you type the name of the list followed by [square brackets] with
the number of the spot you want. For instance, if you had a
variable called my_list which stores a list, you would type
my_list[1] to get the element at the 1 position in the list. One
thing that may be confusing to you is that the front of the list is
not the 1 position, but actually the 0 position. The position
number of an element in a list is called the index of that
element.
List Indexing
Here is an example of using the indexes of elements of a list.

my_list = [1,2,3,4,5,6,7,8,9,10]
print(my_list[0])
print(my_list[1])
print(my_list[2])
print(my_list[3])

The previous code will print

1
2
3
4

Modifying Lists
Anyhow, you can also use the [brackets with a number inside]
format to change the values of the stuff inside of lists. In
general, think of each slot in the list as its own variable, which
is not related to the other ones. Consider this code.

my_list = [1,2,3]
my_list[1] = 4
print(my_list)

This code will print out

[1, 4, 3]
Chapter 5: Lists and Random Module
Accessing List Elements
This doesn’t just work for changing the values inside of a list.
You can use the [brackets with a number inside] format any
time you want to use something stored in a list. You could use
this for printing, math, string concatenation, or whatever else
you could think of. Here are some examples:

my_list = [3, “blue”]


print(my_list[0] + 5)
print(“My favorite color is ” + my_list[1])

This code will print out:

8
My favorite color is blue

List functions
Append
We learned how to create a list and how to use and replace
values in a list, but we can also add new values. The command
we use is listname.append(newValue). Here is an example:

my_list = [1,2,3]
my_list.append(4)
print(my_list)

The previous code will print out [1, 2, 3, 4].


List Functions
Insert
Using append will always add
the new value to the end of the
list. However, you may want to
choose where the new value will
be in the list. In other words, you
may want to insert a new
element into a list somewhere
not at the end. In this case, you
can use the command
listname.insert(newValue, index). If you do this, the
value newValue will be inserted into the list so that its position
number is index. Whatever value used to be at position index
gets pushed backwards, along with everything after it.
Inserting the values will let you insert them at whichever index
you want. Check out this example:

my_list = [1,2,3]
my_list.insert(1.5, 1)
print(my_list)

This will print out [1, 1.5, 2, 3].

As you can see, inserting is not the same as replacing. When you
insert a new value at an index, it will simply shift the values at
or to the right of the index to the right.
Chapter 5: Lists and Random Module
Pop
In order to remove things from a list, you can type
listname.pop(index). This will remove whatever is in the
list that has index as its position number. It will then adjust the
list so that it does not have a hole in it where we just removed
an element.

my_list = [1,2,3]
my_list.pop(1)
print(my_list)

When this is run, it will show [1, 3], because we removed the
element at index 1.

Random Module

We will now take a bit of a detour, and discuss the random


module, and modules in general. Sometimes, when you’re
coding something in Python, the things you can do with the
base code just don’t cut it, and you really need extra features to
make whatever you want to do. That’s where a module comes
in to play! A module is basically just somebody else’s code that
they let you use. Some modules were made by the people who
make Python. Some are made by companies and professional
programmers. You can also make your own modules. It is a very
handy system overall.
Random Module
Some modules get installed on your computer automatically
when you install Python. The module that we are going to use
in this section is one of those. So, you do not need to download
anything.

The random module allows us to use commands that create


random numbers for us. This is way harder to code than maybe
you would think, so we can be thankful that somebody else
wrote the code for us!

Whenever we use a module, the first thing that we need to do is


tell Python that we plan on using some code outside of what we
have written down in our file. The way of doing that is to write
import and then the name of the module that we will be using.
In this case, we are using the module called random. Thus, at
the top of your code, you should write

import random

Now you can make variables equal to random values! If you


want to give a variable a random int value between two
numbers a and b (including, possibly, a or b), you assign it the
value random.randint(a,b). The following are some
examples of this:

coin_toss = random.randint(1,2)
dice_roll_value = random.randint(1,6)
number_of_candies = random.randint(4,7)
Chapter 5: Lists and Random Module
You can also pick decimal values
between two values by using
random.uniform(a,b) instead.
But we will probably not use this
much.

Random with Lists


One immediate way of using
random.randint is for picking
random things from a list! If we
have a list that stores things, like
strings, we can pick one at random
by randomly picking a location in the list. This allows us to get
random words, instead of just numbers.

For instance, the following code will print out a random name:

list_of_names = [ “Diego”, “Victoria”,


“Pablo”, “Maria”, “Guillermo”, “Catarina” ]
random_index = random.randint(0,5)
print(list_of_names[random_index])

Notice that the maximum value for random_index that we


allowed was 5. We chose this because that is the index of the
last thing in the list. If the first entry of the list is in the 0
position, and there are 6 things in the list, then the last thing in
the list is in the 5 position. So, if we pick a number that
represents a position in the list, it should be some number
Exercises
between 0 and 5. Be careful when using this method to not
allow the position number to get too high.

The random module is not as useful as other things when it


comes to writing real code, unfortunately. But it does come up
in video game programming. And actually, it is just good for
writing practice problems, and understanding code in general.
Lists, on the other hand, are more important than probably you
would imagine. Next, we will take a look at another topic that
pairs with lists that is more universal.

Exercises

1) If we run the code:

print(random.randint(1,20))

which of the following is not a possible output?


a. 5
b. 18
c. 0
d. 6
e. 12
Chapter 5: Lists and Random Module
2) If we have the following code:

import random
a = random.randint(2,4)
if a == 1:
print(“A”)
elif a == 2:
print(“B”)
elif a == 3:
print(“C”)

Which of the following is not a possible output for the


program?

a. A
b. B
c. C
d. No output

3) If we run the code:


a = [10, 3, 2, 1, 4, 8]
print( a[3] )
What would we expect the output to be?
a. 3
b. 2
c. 1
d. a[3]
e. [10, 3, 2, 1, 4, 8, 3]
Exercises
4) If we run the code:
a = [5,4,3,2,1]
What code will change the 2 to a 6?
a. a[2] = 6
b. a[3] = 6
c. a[4] = 6
d. a[6] = 2
e. a[6] = 3
f. a[6] = 4

5) If we run the following code, what will the output be?

lst = [4,2,3,7,9,1]
lst.insert(80,2)
print(lst)

a. [4,80,3,7,9,1]
b. [4,2,80,7,9,1]
c. [4,80,2,3,7,9,1]
d. [4,2,80,3,7,9,1]

6) Create a list variable that stores your three favorite foods.


Then, use print statements, and the list indexes, to print out
each food in the list.
Chapter 5: Lists and Random Module
7*) Create a variable which stores a list with nothing in it. Then,
use list functions to add the numbers from 1-10 to this list. (Do
not just make a new list with the numbes from 1-10). Then, use
list functions to remove all of the even numbers from the list.
(Do not just make a new list of all of the odd numbers!)

8) Make a list of five words. Then, make a program that asks


you to input a word, and it searches the list and finds and prints
out the position of the word in the list. If you word you input is
not in the list, have the program print out a message saying
that it is not in the list. You should be able to change your list
without changing any of your other code, and the program will
still work.

9) Write a program that prints out a random fruit from a


choice of at least five fruits

10*) Write a program that generates a list containing five


random numbers.
Chapter 6
While Loops and For Loops

While Loops

One extremely important thing to do in programming is to


repeat something over and over again. One obvious way to do
this is to copy and paste your code a bunch of times. But this will
make the code really messy. Also, the number of times that you
want to repeat it might be different each time you run the
program, which would make this even worse.

To see what we’re talking about, try the following exercise:


Make a program that asks you to input a number, and then
prints out the word “hello” that many times. For instance, the
output could look like this

What number do you want?


5
hello
hello
hello
hello
hello
Chapter 6: While Loops and For Loops
You might not be able to think of a way to do this. You could
maybe sort of get something working with if statements. But
in order to make this work, you would have to write one if
statement for every single number! That would take up more
space than your computer even has on it, just for this silly
program that doesn’t do anything. However, there is actually a
really easy way to do this using while loops!

Defining While Loops


A while loop is kind of like an if-statement, except that it will
repeat what is inside until the condition is not true. The way
that we use a while loop is like this:

while (condition):
do something

Except that, the code do something will run over and over
again, as long as the (condition) is equal to True. Once the
(condition) is equal to False, (do something) will stop .

It may seem like using a while loop will always cause the code
inside to run forever. In a lot of cases, it does! For example, this
code will have a while loop which runs forever:

a = 2
b = 2
while a == b:
print(“saw, dude”)
While Loops
The code will print out
the words “saw, dude”
over and over again,
forever and ever. The
key to making it not run
forever is to make it so
that the condition of the
loop becomes False
somewhere in the loop.
One easy example
would look like this:

a = 2
b = 2
while a == b:
print(“saw, dude”)
a = 0

This will only print out “saw, dude” one time. Of course, that is
no more useful than just using an if-statement! The key to
making it useful is fudging with the variables so that the
condition becomes false after however many times you want
the loop to run.
Chapter 6: While Loops and For Loops
Making While Loops Useful
To show an example for how this is actually useful, the code
below implements the program that asks you for a number,
and prints out “hello” that many times. Check it out:

in_number = input(“Please type a number”)


in_number = int(in_number)
loop_count = 0
while loop_count < in_number:
print(“hello”)
loop_count = loop_run_count + 1

When this program runs, the first thing it does is asks you to
type in a number. Using input will return this answer as a
string. To get around this, the line in_number =
int(in_number) tells the program to treat in_number like an
int, instead of a string. Then we make a variable called
loop_count, which will keep track of how many times the loop
has run. Notice that each time we run the loop, the variable
loop_count increases by 1. The condition of the loop is
loop_count < in_number. Since loop_count starts at zero
and increases by 1 every time that the loop runs, the loop will
stop running after the loop runs the number of times that you
typed in!
Len Function

The Len Function

One other use of while loops is to run through the values of a


list. The following code will print out all of the values in a list
that we have made:

list_of_names = [ “Yiorgos”, “Vasiliki”,


“Athanasios”, “Konstandina”, “Panagiotis”,
“Molly” ]

index = 0
while index <= 5:
print( list_of_names[index] )
index = index + 1

You can see that we used index <= 5 as the condition for the
while loop, because 5 is the largest index of an element in the
list. The index of the last element of our list is 5, so we cannot
let index be larger than 5 when we run print(
list_of_names[index] ) or else there will be an error.

Sometimes, you might not want to count by hand how many


things there are in a list. Actually, if you have a variable called
name whose value is a list, then using len(name) will be equal
to how many things there are in that list. So, for example, if c =
[4,5,6], then len(c) is equal to 3.
Chapter 6: While Loops and For Loops
This can make our lives much easier when we deal with loops.
We can incorporate it into the previous code as follows:

list_of_names = [ “Yiorgos”, “Vasiliki”,


“Athanasios”, “Konstandina”, “Panagiotis”,
“Molly” ]

index = 0
while index < len(list_of_names):
print( list_of_names[index] )
index = index + 1

Notice that the <= in the


while loop was changed to a <
sign! There is a good reason
for this. In our previous code,
we wanted index to be less
than or equal to 5. But the
length of list_of_names is
actually six! The reason for
this is because the index of
the front of the list is zero. So the way the math works out, the
index of the final element of any list is one less than the number
of things in that list. Using the condition index <
len(list_of_names) will work. Another choice would be
making the condition index <= len(list_of_names) - 1.
For Loops
Using len to count how many elements are in a list makes our
life much easier. It means that we don’t need to manually count
how many elements are in the list. Counting manually can be
pretty tricky if the length of the list gets really large. It would be
especially bad if we started using append and pop to change
the length of the list, because the length of the list would
change mid-program. So all things considered, it’s best to stick
to using len.

For Loops

While using len to cycle through a list makes our lives easier,
another possibly better way to cycle through a list is by using a
for loop. For loops are great for iterating through a list. A for
loop is formatted like this:

for (variable) in (list):


code you want inside the for loop

Components of a For Loop


For loops are usually pretty tricky for students to understand,
so let’s try to break this down. A for loop has three parts to it:
the loop-variable, the list, and the code inside of the loop. The
loop-variable and the code inside of the loop are created when
you make the for loop. The list, however, can exist before you
make the for loop. In the example above, the loop variale is
(variable) and the list is (list). In order to help you
Chapter 6: While Loops and For Loops
visualize this, we will look at some for loops and identify the
different parts. Consider the following example:

names = [“Juan”, “Juanita”, “Marcos”,


“Margarita”]

for z in names:
print(z)

In this example, the loop-variable is z, which is a new variable


which we create when making the loop. The list of the loop is
names. And the code inside the loop is print(a). Here is
another example:

numbers = [1,2,3,4,5,6,7]
sum = 0
for i in numbers:
sum = sum + i

In this example, the loop-variable is i, the list is numbers, and


the code inside the loop is sum = sum + i.
For Loops

How the Components Work Together


These three parts all work together when a for loop runs. When
the for loop runs, the number of times that the code inside the
loop will run will be equal to how many elements there are in
the list. So if the list for a for loop has 5 elements in it, the code
inside the for loop will run 5 times. Using this reasoning, the
loop in the names example above will run four times. The
numbers example above will run seven times.

Now here is the tricky part: each time a for loop runs, the loop-
variable will have a different value. The first time that the loop
runs, the loop variable will be equal to the element in the zero
position of the list. The second time, the loop-variable will be
equal to the element in the one position of the list. Each time
the loop runs, the loop-variable will be equal to the next thing
in the list, until, eventually, the loop-variable has taken on
every value in the list. Then, the loop finishes.
Chapter 6: While Loops and For Loops
Here is an example. Consider the following for loop:

lst = [1,2,3]
for i in lst:
print(i)

In this for loop, the loop


variable is i, the list is lst,
and the code inside the loop is
print(i). Because lst has
three things in it, the loop will
run three times. The first
time the code inside the loop
runs, the loop-variable, i,
will be equal to 1. So the code
will print out the value of i,
which is 1. The second time
the loop runs, the loop-variable, i, will be equal to 2. So the
loop will print out the value of i, which is 2. Finally, the loop-
variable, i, will be equal to 3, and the loop will print out 3.
Putting this together, our code will print out:

1
2
3
Using a For Loop with Range
Now that we know how a for loop is formatted, we can use the
for loop on a previous example to show how easy it is to print
out a list. Remember when we used a while loop to print out a
list of names? Here is the same example, but with a for loop:

list_of_names = [ “Yiorgos”, “Vasiliki”,


“Athanasios”, “Konstandina”, “Molly” ]

for name in list_of_names:


print(name)

This is much shorter and required fewer lines of code than the
while loop. The for loop was built to iterate over sequences like
lists, which is why it simplifies the process immensely.

Using a For Loop with Range

If you want to make a for loop, where the list is the list of
numbers between 0 and some other number, Python has a very
easy way to do this! If you write range(n), where n is a
number, Python will treat this the same as the list
[0,1,2,...,n-1]. For example, if you write range(5),
Python will treat it the same as the list [0,1,2,3,4]. If you
write range(3), then Python will treat it the same as the list
[0,1,2]. And the following code:

for i in range(10):
print(i)
Chapter 6: While Loops and For Loops

Would print out all of the numbers between 0 and 9. This can
actually be very handy with lists as well.

For Loops Using Range and Len


Actually, say we have some list called lst. If you start out a for
loop using the code:

for i in range(len(lst))

Then the loop-variable i will start out at 0, and end at


len(lst)-1. But this means that the variable i will scroll
through all of the positions of every item in the list lst. We
know that the index of the item at the front of lst is 0. And the
index of the item at the end of the list is len(lst)-1.
Seriously! If the value of lst is [55,23,20,4,19], then
len(lst) is equal to 5, and the position number of the last
thing in the list is 4, which is len(lst)-1.

So in this case, rather than the loop-variable being equal to


each thing in the list, it is equal to each position of each thing in
the list. This actually gives us another way of going through
every item in a list. Remember, if i is the position of something
in a list, then lst[i] is the item at that position! It might be
easier to show some ways of writing our for loops using this
new method.
Using a For Loop with Range
This code:

a = [55,22,35,21,53]
for i in a:
print(i)

Could be rewritten as:

a = [55,22,35,21,53]
for i in range(len(a)):
print(a[i])

The following code:

a = [43,23,65,34,33]
sum = 0
for i in a:
sum = sum + i

Could be rewritten as:

a = [43,23,65,34,33]
sum = 0
for i in range(len(a)):
sum = sum + a[i]
Chapter 6: While Loops and For Loops
Why Use a For Loop With Range?
It may seem kind of random why we would want to come up
with this other way of writing what is basically the same for
loop. But actually, it is in some ways more powerful than the
previous way. For instance, if we had a list of numbers, and
wanted to increase every number in the list by 1, we could do
this using our new for loop method as follows:

numbers = [5,27,0,-2,5,8,13, 49, 52, 166]

for i in range(len(numbers)):
numbers[i] = numbers[i] + 1

But if you want to do the same task using the old for loop
method, it wouldn’t work.

numbers = [5,27,0,-2,5,8,13, 49, 52, 166]


for n in numbers:
n = n+1
How do we put this back into the list?
??????????????

The way that a for loop works is that if you change the loop
variable, you do not change the original list at all. Using for n
in list_of_numbers gives you every element in the list, but
it does not tell you where you got them from. So once you
Exercises
change one, you do not know how to put it back in the original
list.

As a rule of thumb, if you want to change a list using a for loop,


it is important to use range!

Anyway, this basically finishes up our talk about loops. These


can be a bit tricky, but they are extra important! So make sure
to practice up!

Exercises

1) If we have the following while loop:

while a > 5:

Which of the following values for a will cause the loop to stop
(choose all correct answers)
a. a = 3
b. a = 4
c. a = 5
d. a = 6
e. a = 7
f. a = 8
Chapter 6: While Loops and For Loops
2) If we have the following code:

a = -2
while a < 5:
print(“oi!”)

How many times will the word oi! be printed out


a. 0
b. 5
c. 7
d. The program will not stop

3) If we have the following code:

for i in range(100):
print(“bruh”)

How many times will the word bruh print out


a. 0
b. 99
c. 100
d. The program will not stop
Exercises
4) If we have the following code:

a = -5
while a < 5:
print(“yep”)
a = a + 1

how many times will yep be printed out?


a. 0
b. 9
c. 10
d. The program will not stop

5) If we have the following code:

a = 0
while a != 11:
print(a)
a = a + 2

How many numbers will end up being printed out?

a. 0
b. 5
c. 10
d. The program will not stop.
Chapter 6: While Loops and For Loops
6) Write a while loop to print out all of the numbers between
one and one thousand.

7*) Write a while loop to print out all of the numbers between
one and one hundred, except for the number 25. Only use one
while loop in your answer.

8) Write a program that asks you the same question over and
over again, even if you answer it. It could look like this:

Hi, how are you?


good
Hi, how are you?
I’m still good
Hi, how are you?
Please stop asking me this
Hi, how are you?
...

It is not enough to just print the question over and over again.
The program must also allow you to type an answer each time
it asks the question. Your code should have 5 lines or less.

9) Repeat problems six and seven, but with a for loop

10*) Use a for loop to convert a list of ints to a list of strings. For
example, If before the loop runs, your list were [1,2,3].
Afterwards, it would be [“1”,“2”,“3”]. If, before the loop
runs, your list were [44,32,89,21], afterwards, your list
would be [“44”,”32”,“89”,“21”].
Chapter 7
Tuples and Dictionaries

Tuples

In this section, we are going to learn about two new data types.
They are both similar to the list, in that they are made up of
other types of data.

The first data type that we will learn is less complicated, and
less important. It is called the tuple. A tuple is essentially the
same thing as a list, except that once you make it, you can’t
change it at all. This may sound kind of silly, but sometimes it
is better. Basically, if Python knows that something will never
change, it doesn’t have to use as much memory, so the program
will run faster. This does not generally matter at this point in
our programming ability, but when making some really
complex programs, it can really add up. The way of making a
tuple is the same as making a list, but you use (parentheses).
Instead of [square brackets]

The following code creates a tuple, as well as a list:

names_tuple = (“Obi”, “Adeola”, “Ekon”, “Alika”)


names_list = [“Obi”, “Adeola”, “Ekon”, “Alika”]
Chapter 7: Tuples and Dictionaries
The first line of the code on the previous page creates a tuple,
and the second creates a list. If we were to print out the
variables created in the previous code, it would look like this:

(“Obi”, “Adeola”, “Ekon”, “Alika”)


[“Obi”, “Adeola”, “Ekon”, “Alika”]

You can also access specific positions in a tuple, and it will also
act the same as a list.

mt_rushmore = (“Washington”, “Jefferson”,


“Roosevelt”, “Lincoln”)
print(mt_rushmore[0])
print(mt_rushmore[1])

Will print out

Washington
Jefferson

You can even use tuples in a for loop, instead of a list! The main
way that a tuple will be different, is if you try to change one of
the values, it will blow up on you. Check out this code:

mt_rushmore = (“Washington”, “Jefferson”,


“Roosevelt”, “Lincoln”)
names_tuple[2] = “Kennedy”
Tuples
The previous code will not work! Once you make a tuple, it is
going to stay that way forever. You can’t change it!

Although here is something that you should not get confused


about: what you cannot do is change just one part of a tuple. But
you can change the value of a variable to be a new tuple
whenever you want.

For example, this code will actually work

names_tuple = (“Obi”, “Adeola”, “Ekon”, “Alika”)


names_tuple = (“Guillermo”, “Maria”, “Pablito”,
“Juanita”)

This is because whenever you use (parentheses) it is making a


brand new tuple and is not modifying the old one. So in this
Chapter 7: Tuples and Dictionaries
case, the tuple (“Guillermo”, “Maria”, “Pablito”,
“Juanita”) was made, the old tuple (“Obi”, “Adeola”,
“Ekon”, “Alika”) was thrown away, and we stored the tuple
of our favorite Spanish names in the variable names_tuple.

You have now learned basically everything that you will ever
need to know about tuples. The next topic is not as simple.

Dictionaries

Next up is… dictionaries! A dictionary is a bit abstract. You can


think of it as a collection of nicknames for different values. So,
you can give nicknames to different values to remember later.
The “nicknames” in this case are other values that you could
store in a variable, like numbers, words, or even tuples.

The easiest way to make a dictionary is to make an empty


dictionary, and put things into it later. A dictionary basically
stores nicknames for things, and an empty dictionary is a
dictionary with no nicknames in it. You can make one like this:

my_dictionary = {}

Keep in mind that my_dictionary is just a regular variable,


which is a location in memory. So, doing this basically tells
Python that you want to use some part of memory as a
dictionary, which currently is empty. To that end, you could
Dictionaries
name this variable whatever you want, it does not need to be
called my_dictionary. After you do this, you can give a new
nickname to a piece of data like this:

my_dictionary[nickname] = data

Again, the nickname can be a number, a string, a tuple, or any


other type of data. For example, it could look like this:

my_dictionary[“Tater Tot”] = “Me”


my_dictionary[5] = “Five”
my_dictionary[ “One two three” ] = (1,2,3)

Once you make a dictionary, and start to fill it up with


nicknames, you can actually print it out. When you do, you will
see all of the pairs of nicknames and data which you have
entered into it. If we print out the dictionary from the previous
example, it will print out

{'Tater Tot': 'Me', 5: 'Five', 'One, two, three': (1, 2, 3)}

Actually, if you want to make a new dictionary, and you know


what nickname you want to go with what data, you can actually
make a new variable using this format! The following code does
just this:

dict = {“Tater Tot”: “Me”, “number”: 45}


Chapter 7: Tuples and Dictionaries
Here, the nickname “Tater Tot”
would go with the data “Me”, and the
nickname “Favorite_number” goes
with the data 45.

Before we go any further, we should


note that “nicknames” is not an
official word for how to use a
dictionary - we are just using it to
make it easier to understand. What we
call a “nickname” is actually called a
key. And the thing that we give a nickname to is actually called
a value. Technically speaking, a dictionary is a set of pairs of
one key and one value. So, in the case of the dictionary that we
just made, the key “Tater Tot” is paired up with the value
‘Me’. And the key “number” is paired up with the value 45.

Now if you have a key, you can get a value that goes with it in a
similar fashion to how you do lists. Put the name of the variable
that stores the dictionary, followed by [square brackets],
and put the key inside of the square brackets. Look at the
following code. Assume dict is the same as before.

print( dict[“Tater Tot”] )


print( dict [“number”] )
Dictionaries
The code on the previous
page would print out.

Me
45

And we can change the


value that goes with a key
in a way similar to lists.
This code:

my_dictionary[“Tater Tot”] = “Me”


my_dictionary[“Tater Tot”] = “Not me”
print( my_dictionary[‘Tater Tot’] )

Will print out

Not me

Dictionaries actually have many uses in more advanced topics.


They are not something with tons of obvious uses right away,
but in situations when you use them, they can be extremely
useful. One possible use is encrypting messages and sending
secret codes. For example, say we want to write words in a
secret code where we replace every letter with its number in the
alphabet. So A gets replaced by 1, B gets replaced by 2, C gets
replaced by 3, and so forth.
Chapter 7: Tuples and Dictionaries
In order to convert words into this secret code, we could use a
dictionary, such as in the following case:

secret_message = [“H”, “E”, “L”, “L”, “O”]

alphabet_dictionary = {“A”: 0, “B”: 1, “C”:


2, “D”: 3, “E”: 4, “F”: 5, “G”: 6, “H”: 7,
“I”: 8, “J”: 9, “K”: 10, “L”: 11, “M”: 12,
“N”: 13, “O”: 14, “P”: 15, “Q”: 16, “R”: 17,
“S”: 18, “T”: 19, “U”: 20, “V”: 21, “W”: 22,
“X”: 23, “Y”: 24, “Z”: 25}

for i in range(len(secret_message)):
# The code below should be on one line!
secret_message[i] =
alphabet_dictionary[secret_message[i]]

This looks fairly complex, but the basic idea behind the code is
that, in the for loop, the number i will scroll through the
values 0 through 4. We will explain the case where i = 0. The
other cases are similar. When i = 0, the value of
secret_message[i] is “H”. Therefore,
alphabet_dictionary[secret_message[i]] is the same
as alphabet_dictionary[“H”]. We can see that the key “H”
in alphabet_dictionary has the value 7. Thus, this will swap
out the value of secret_message[0] to 7.

In the end, the array secret_message will have the value


[7, 4, 11, 11, 14]
Exercises
Dictionaries are pretty cool, and here and there, they can be
really convenient!

Exercises

1) Which of the following is an example of a tuple:


a. {'k1': 'v1', 'k2': 'v2'}
b. (1,2,3)
c. [1,2,3]

2) Which of the following is an example of a dictionary


a. {'k1': 'v1', 'k2': 'v2'}
b. (1,2,3)
c. [1,2,3]

3) Say we have the following code:

a = (1,5,7,2,3,9)

Which code will print out the number 7?


a. print(a[7])
b. print(a[2])
c. print(a[3])
d. print(a[4])
Chapter 7: Tuples and Dictionaries
4) If we have the following code:

a = {“three”: 3, “two”: 2, “one”: 1}

where the numbers spelled out with letters (“one”, “two”,


“three”) are the keys, and the digits (1,2,3) are values. How
would we add the key “four” with value 4 to a:

a. a[4] = ‘four’
b. a[“four”] = 4
c. a.append( { “four” : 4 } )
d. we can’t do it without making a new dictionary.

5) If we have the following code:

b = (6,5,4,3,2,1)

Which of the following would change the 5 in b to a 9?

a. b[1] = 9
b. b[2] = 9
c. b[5] = 9
d. We can’t do it without making a new tuple

6*) Write a poem with at least three lines, and store all of the
lines in a tuple. Then, using a while loop, print out each line on
a new line. Your code can only feature the print statement once.

7) Write a program that makes a dictionary where the keys are


different foods, and the values are what you think of them. So
a key could be “Pizza” and a value could be “I like pizza.”
Exercises

8) Using your code from problem 7, make the program ask you
for a food, and use the dictionary to say what you think of that
food. The output could look like this:

What is a food?
Pizza
I like pizza

What is a food?
Squash
I mean squash is okay I guess

After you set up the dictionary you can only use four lines of
code.

9* ) Write a program where the user types in a string. Then, use


a dictionary to figure out how many times each letter appears.
The keys should be letters, and the values should be how many
times it appears. Print the dictionary at the end of the program.

Hint: If my_str is a string, then list(my_str) will be equal to


a list, where each letter of my_str is a different entry in the list.

10 ) Write a program where you type in a message, and then


the message gets encoded, such that each letter is replaced by
another specific letter. For example, every A gets replaced by
E, every C gets replaced by F, etc.
Chapter 8
Functions

Simple Functions

There is only one more major section in this book! I’m getting
sentimental already! But this chapter is going to be a good one.
We are studying functions, which is one of the most important
things in programming!

Basically, think of a function as like an abbreviation for a larger


chunk of code. To give an example of when we would want to
use a function, say you wanted to run this code at different
points in your program:

print(“Pardon the interruption,”)


print(“I just really felt like”)
print(“printing this out.”)

That is, you wanted to run these lines of code more then once.
But maybe you want to scatter it all over your program, so it
does not make sense to use a while loop. One way of doing it is
to copy and paste the code many times. But that would be really
annoying to do. A better possibility is to use a function.
Simple Functions
A function allows us to give a nickname to a set of commands.
Then, rather than typing in all of those commands, we can just
type in the name of the function, and it will run all of those
commands for us. Another way of thinking about this is that a
function is like writing a mini program inside of our larger
program. Then, you can run the mini program whenever you
want within the larger program. If you’re familiar with Scratch,
writing a function is similar to making a custom block.

Making a Function
The way that we make a function is like this:

def name_of_function():
List of commands
Commands
Commands

Just like if-statements, for loops, and while loops, our function
uses indents. You can put as many commands as you want
inside of a function, as long as you keep indenting them. You
can also put things like if statements, for loops, and while loops
inside of a function as well, but you will need to double indent
them (or indent them even more, depending on how many you
have inside each other!).
Chapter 8: Functions
If we wrote the series of print statements from before as a
function, it could look like this

def print_message():
print(“Pardon the interruption,”)
print(“I just really felt like”)
print(“printing this out.”)

The name of a function follows all of the same rules as variables


- it can be letters, numbers, or _underscores_, and it cannot
start with a number. The word def at the start of the function
is short for define. When you make a new function, it is called
defining the function. And because programmers like giving
things multiple names, another word for a function is a
method.

Calling a Function
Now as you already know, if you write a program, you need to
run it or else it won’t do anything. Functions are no different.
Writing a function won’t do anything unless, somewhere in the
program, we decide to run the function. If we make a function,
then you can run it at any time by writing the name of the
function followed by (), which is an (open parenthesis followed
by a close parenthesis). Running a function is sometimes called
calling the function. To call the function that we just wrote, we
would type:

print_message()
Simple Functions
Putting this all together, if we ran the following code

def print_message():
print(“Pardon the interruption,”)
print(“I just really felt like”)
print(“printing this out.”)

print(“First time printing the message”)


print_message()
print(“Second time printing the message:”)
print_message()
print(“Third time printing the message:”)
print_message()

It would print out:

First time:
Pardon the interruption,
I just really felt like
printing this out
Second time
Pardon the interruption,
I just really felt like
printing this out
Third time:
Pardon the interruption,
I just really felt like
printing this out
Chapter 8: Functions

Parameters

Now sometimes, we want to write functions which are almost


exactly the same each time that we run them, but maybe are
slightly different. For example, maybe we want to run some
code that printed out this:

Hello, my name is Spiderman


Hello, my name is Carmen Sandiego
Hello, my name is Doctor Pepper

These three lines of code are almost exactly the same, but they
are a little bit different. It seems like we could maybe write
some code to take advantage of how these three lines of code
are similar. It would be nice if we could write a function and run
it three times, once for each line, and tell the function how we
wanted each line to be different. The way that we do that is with
parameters.

A parameter is basically a piece of extra information that you


give to a function to tell it exactly how it should run. In the
previous example, the three lines of code print out “Hello, my
name is”, but the lines all end with a different name. Therefore,
if we wanted to write a function to print out each of the above
lines, each time we run the function we would need to tell it
what name to print out.
Parameters
Adding Parameters
In order to add a parameter to a function, you must choose a
name for your parameter, and type it between the parentheses
of the line where you write def. Here is an example:

def name_of_functions(parameter):
Commands
Commands
Commands

In this case, we named our parameter parameter, but you can


name it whatever you want. The names of parameters follow
the same rules as variable names.

Using Parameters
Actually, when writing the function, think of a parameter as a
variable, except that it will have some value that is different
every time you run the function. For example, our previous
lines of code could be simplified by the function:

def print_name( name ):


print(“Hello, my name is ” + name)

this case, the first time we run the function, we would want
name to be equal to “spiderman”, the second time, we would
want name to be “Carmen Sandiego”, and the third time, we
would want name to be “Doctor Pepper”.
Chapter 8: Functions
The way that you run a function that uses a parameter is by
putting what value you want the parameter to have between
the (parentheses) when you call the function. If we ran this:

def print_name( name ):


print(“Hello, my name is ” + name)

print_name(“Spiderman”)
print_name(“Carmen Sandiego”)
print_name(“Doctor Pepper”)

Then it would print out

Hello, my name is Spiderman


Hello, my name is Carmen Sandiego
Hello, my name is Doctor Pepper

So to review why this works,


when you run
print_name(“Spiderman”),
it takes the value “Spiderman”
and assigns it to the parameter
name. Then, the code
print(“Hello, my name
is” + name) will run, where
name is treated like a variable,
and has the value “Spiderman”.
So the code will print out
Parameters
“Hello, my name is Spiderman”.
print_name(“Carmen Sandiego”) and
print_name(“Doctor Pepper”) will work in a similar way.

Multiple Parameters
You can also write functions with multiple parameters if you
want. Functions can have as many parameters as you want, but
they need to have different names, and they need to be
separated by commas. We could write a two-parameter
version of our previous function like this:

def name_color(name, color):


print(“Hello, my name is ” + name + “ and
my favorite color is ” + color)

When you run a function with multiple parameters, you put the
values that you want for each of them between the
parentheses, and you need to separate them by commas. So to
run the previous function, if you ran the code:

name_color(“Steve”, “brown”)

It would take the value “Steve” and assign it to name. It would


also take the value “brown” and assign it to color. Then, it
would print out

Hello, my name is Steve and my favorite color is brown


Chapter 8: Functions
Notice that the values are given to parameters in order. So the
first value, “Steve”, was assigned to the first parameter, which
was name. Then, the second value, “brown”, was assigned to
the second parameter, which is color. If we reversed the order
that passed in the values, Python would not magically figure
out what happened. Running the code:

name_color(“brown, “Steve”)

Would print out

Hello, my name is brown and my favorite color is Steve

There is another way of passing in parameters that does not


require you to remember the order. You can type the name=
Return Value
before each value to specify which value you want to go with
which parameter, where name is replaced with the name of a
parameter. When you do it that way, the order that you type in
the parameters does not matter. Here are two examples of this:

name_color(name=”Steve”,color=”brown”)

name_color(color=”brown”, name=”Steve”)

Both of the following examples will do the same thing as this


code:

name_color(“Steve”, “brown”)

Return Value

Now we talked before about how if you use parameters like a


variable, they go away when the function is done. Actually, if
you make any variables at all inside of a function, they go away
when the function is done. If you don’t believe it, then try
running the following code

def my_function():
a = 6
my_function()
print(a)
Chapter 8: Functions
This will cause Python to crash! When the code tries to run
print(a), it will say that the variable a is not defined. This is
because any variables that you make inside of functions cannot
be used outside of the function.

This could actually be kind of a problem if your functions solves


any complicated math problems where you want to store the
answer in a variable so that you can use it later. For instance, say
you want to make a function that adds five to a parameter, and
you also want to store the result in a variable for later. You could
try a function like this:

def add_five( number ):


number = number + 5

But remember that the parameter “number” is forgotten after


the function ends, so this won’t really keep track of anything.
You might want to make a new variable, like this:

def add_five( number ):


final_num = number + 5
Return Value

but as we just learned, this


won’t work either, because
the variable that you made
will also be forgotten. So it
seems like we are really in a
pickle here. But fear not,
for there is one last cool
feature of functions that is
built to specifically solve
this problem: the return
statement.

The return statement of a


function allows us to use
one value from the
function after the function
has finished. The way that we specify which value we want to
keep is by writing it down somewhere in the function after the
word return.

Using a Return Statement


To add a return statement to the add_five example, it would
look something like this

def add_five( number ):


return number + 5
Chapter 8: Functions
Basically, what this function does is allows us to remember the
value of number + 5 and use it later.

In order to use return values,


when you call the function, you
must write variable = right
before you call the function,
where variable is the name
of some (possibly new)
variable. Doing this will cause
whatever you put after
return in the function to be
stored in the variable. For our
previous example, it would look like this:

second_num = add_five( 3 )
print( second_num )

The way that this will work is that add_five will run, with 3 as
its parameter. So when add_five runs, the parameter number
will be equal to 3. It will then run the line return number+5.
Clearly, number+5 has the value 8. So the value 8 is returned,
and it is stored in the variable second_num. Then,
print(second_num) will cause the program to print out 8.
Return Value
Another Example
This is often confusing to understand for students, so here is
another example to help you out:

def do_math( number ):


number = number * 2
number = number + 5
return number

first_num = 4
second_num = do_math(first_num)
print(second_num)

Notice that first_num has a value of 4. It gets passed in as the


parameter for do_math, so the parameter number will be equal
to 4 when the function begins. The first line of do_math will
multiply the value of number by 2, so that number is equal to 8.
The second line then adds 5 to number so that number is equal
to 13. Then the line return number will return whatever value
is stored in number, which in this case is 13. So the variable
second_num takes on the value of 13. Finally, the value of
second_num gets printed out, so the program will print 13.

Return ends the function


There are a few final things you should know about return.
First, after Python executes a return statement, it will
immediately exit out of the function, and any code after it will
not run.
Chapter 8: Functions
Here is an example:

def print_things():
print(“This will run”)
return 5
print(“This will not run”)

var = print_things()

The previous code will output “This will run”, but it will not
output “This will not run”. This is because when the function is
run, once it hits the return statement, the function will stop
running, and will not get to the line print(“This will not
run”).

Thus, you should only put the return at the end of the
function, or somewhere where you know that you don’t need
the function to keep running afterwards.

Conditional returns
If you make a return depend on an if-statement, you can and
should put a return in multiple locations to make sure that
something always gets returned when you run a function.
Otherwise, you could run into strange issues.
Return Value
One example of such issues is here:

def func(b):
if a == 2:
return 5

number = func(3)
print(number)

The above code will print out None, which is Python’s way of
saying “nothing”. When we ran func(3), the parameter b
takes on a value of 3, which means that the return statement
will never be reached. Since nothing is returned, the variable
number gets assigned the value None. While this will
technically work, it is a bad habit to have functions that will
sometimes return something, and sometimes return None. In
order to work around this, make sure to use else statements,
or other ways to ensure that you always return something. Here
is a way of fixing the previous code:

def func(a):
if a == 2:
return 5
else:
return 1

In this example, no matter the value the parameter a, the


function will always return something. And that’s basically it
for functions. Nice work!
Chapter 8: Functions
Exercises:

1) If we run the following code:

def thingy(a, b, c):


print(a + b – c)
thingy(1,5,2)

What will the output be?


a. a + b – c
b. 4
c. 8
d. -2

2) If we run the following code:

def thingy2(a, b, c)
one = a + b
two = c – b
three = 2
print(one + two + three)
thingy2(3,2,1)

What will the output be?


a. 3
b. 4
c. 5
d. 6
Exercises
3) Given the following code:

def do_math(a,b):
return 2*a*a + 3*b

Which option would print out 17?

a. do_math(1,5)
b. do_math(3,2)
c. z = do_math(2,3)
print(z)
d. y = do_math(5,1)
print(y)

4) If we run the following code, which print statements will


run?
def my_function(a,b):
if a == 4:
print(“saw dude”) (i)
return 9
if b == 12:
print(“hello”) (ii)
return 10
my_function(4,12)

a. Just (i)
b. Just (ii)
c. Both (i) and (ii)
d. Neither (i) nor (ii)
Chapter 8: Functions
5) If we run the following code, which print statements will
run?

def my_function2(x,y):
for i in range(x):
if y == 2:
print(“hi”) (i)
else:
return 6
print(“okay, bye now”) (ii)

a. Just (i)
b. Just (ii)
c. Both (i) and (ii)
d. Neither (i) nor (ii)
e. Impossible to tell

6) Write a function called add that takes in two numbers as


parameters and returns their sum.

7) Write a function called describe which takes, as parameters,


your name, age, and favorite color, and then it uses all of those
in a sentence. The output could look like this:

> describe( “Eileen”, 9, brown )


Hello, my name is Eileen, I am 9 years old, and my favorite color
is brown
Exercises

8*) Write a function called print_to, where it takes a parameter


that is a number, and it prints out all of the numbers between
one and that number. For instance, it could look like this:

> print_to(3)
1
2
3

> print_to(100)
1
2
3
4

99
100
Chapter 8: Functions
9*) Write a function called tuple_add where the inputs are
two tuples of numbers, and returns a new tuple where each
entry is the sum of the numbers from that entry from the other
tuples. For instance, it could look like this:

> tuple_add( (1,1), (2,3) )


(3,4)

> tuple_add( (0,1), (5,4) )


(5,5)

> tuple_add( (-1,-1), (4,4) )


(3,3)

10) Write a function called fruit_color, where the input is a fruit


and a color, and it tells you if the fruit is that color. For instance,
the output could look like this:

> fruit_color( “apple”, “red”)


Apples are red

> fruit_color(“blueberries”, “green”)


Blueberries are not green
Chapter 9
Turtle

To finish off our basic introduction to Python, we will explore a


more creative and graphical part of Python -- Turtle!

Now the name may sound strange, but turtle is just the name
of a black triangle we will see in the center of the screen which
moves around and draws lines and shapes. We will write code to
open up a new window with a Turtle in it, and then use this
Turtle to draw whatever we want.

Getting Started
In order to use Turtle, we must import its module. We touched
on importing modules before with random. Remember that?
That’s exactly what we’ll do here, like so:

import turtle

It’s that easy, and now you have a VIP access pass to all of the
functions in the turtle library. Now we are going to want to set
up the screen for Turtle. The following code should open up a
new turtle window.

import turtle
turtle.done()
Chapter 9: Turtle

Because the done() function is from the turtle library, in order


to get it to work, we need to put the word turtle in front of it,
so that Python knows to take the done() method from the
turtle library. This is similar to how you need to type
random.randint, when using the randint function from the
random module.

Now when we run it we will see that a window/screen pops up


that has a black triangle in the center of it. It should look about
like this:
Drawing With Turtle

Great, so now we have successfully launched our screen and


created our turtle! That black triangle in the center of the
screen is our “turtle.” I know that it may not look like a turtle,
but that’s what we have. Part of why it doesn’t look like a real
turtle is because, in practice, our turtle acts more like a pen.
When we move the pen around, it will draw lines coming out of
it. The arrow shape is helpful for knowing exactly where lines
will be drawn. It would be much more difficult if it looked like
an actual turtle!

Moving Forwards and Backwards


To move the pen forward, we will use turtle.forward(x),
where x is how far we want the turtle to move. Let’s go ahead
and try it. Add this line of code between import turtle, and
turtle.done()

turtle.forward(100)

Go ahead and run it, and we’ll see that the turtle moves 100
units in the direction it is pointing! In general, when you give
the turtle instructions on what to do, you need to do it after
import turtle, as that is the line which allows us to use turtle
functions. You also need to put them before turtle.done(),
which is how you tell the program that you are all done.
Chapter 9: Turtle

Since forward is a long word, you can also use turtle.fd(x)


and it will do the same thing. If we try it, we’ll see that it works
the exact same way:

turtle.fd(100)

When we run it, it works the exact same way as


turtle.forward(100)

To move it backward or in the opposite direction of the way the


turtle is facing, we will use turtle.backward(x), where x is
Drawing With Turtle
the number of “steps” or units we want the turtle to move
backward.

turtle.fd(100)
turtle.backward(100)

If we run it, we will see that the turtle will move forward 100
paces and then 100 back to its original position. Notice that the
turtle does not face the opposite direction when it is moving
backwards. It essentially just “backpedals” while pointing in
the same direction.
Chapter 9: Turtle
Of course, there is a shorter version of turtle.backward()
and it is turtle.bk(). We can go ahead and try it:

turtle.fd(100)
turtle.bk(100)

And we see that it works exactly the same.

Turning
Now that we have down forward and backward, you are
probably wondering how we can move left and right. Can you
guess the name of the functions? That’s right! It’s just
turtle.left(x) and turtle.right(x).

The way the left and right functions work, however, are less
intuitive, because the turtle doesn’t actually move left or right.
Instead, it turns left or right. The command turtle.left(x)
will turn the turtle left in x degrees. turtle.right(x) will
turn the turtle right in x degrees. Turning left means we are
turning counter-clockwise and turning right means we are
turning clockwise.

Let’s go ahead and try it out. We will have the turtle turn left and
move 100 paces like so:

turtle.left(90)
turtle.fd(100)
Drawing With Turtle

And there you have it! You can now move the turtle around and
draw all sorts of lines and shapes! There are a few cool things
that you can do. For one thing, if you want to move the turtle
without drawing a line after it, you can type in

turtle.penup()

And it will stop drawing when you move it. If you want to start
drawing again afterwards, you have to write

turtle.pendown()
Chapter 9: Turtle
And it will start drawing again. An example of this is the
following code:

turtle.fd(50)
turtle.penup()
turtle.fd(50)
turtle.pendown()
turtle.fd(50)

Which will show up like this:


Drawing With Turtle
You can also switch the color of the drawing of turtle, by using
the code

turtle.color(“name-of-color”)

Where you replace name-of-color with the name of the color


that you want. So for instance,

turtle.color(“red”)

You can type most colors you can think of. Just don’t get too
ridiculous with the name. Like it probably won’t be able to
recognize colors like mauve and vermillion. Think red, yellow,
green etc…

Finally, you can actually draw filled-in shapes using turtle. But
it’s a little tricky to do so. The first thing that you need to do is
type turtle.begin_fill() to say that you want to start
making a filled in shape. Then, you want to make the turtle
travel in some sort of loop, so that it finishes where it started.
Finally, type turtle.end_fill() in order to make it fill in the
drawing that you just made.
Chapter 9: Turtle
This code would make a filled in triangle:

turtle.color(“red”)
turtle.begin_fill()
turtle.fd(50)
turtle.left(120)
turtle.fd(50)
turtle.left(120)
turtle.fd(50)
turtle.end_fill()
turtle.color(“black”)
Drawing With Turtle
Pretty cool, huh! In case you are curious, we changed the color
of the turtle at the end so that it does not blend in with the
triangle. If that weren’t there, then the two would be the exact
same color (try it yourself!).

Now you have all of these turtle commands to play around with.
Turtle can be really fun to just mess around with, and a great
way to learn it is just to try things. One trick to get you started
is that turtle can make some really cool stuff with for loops. For
instance, try out this code:

for i in range(40):
turtle.fd(150)
turtle.left(171)
Chapter 9: Turtle
Exercises

1) Which of the following turns the turtle to the left by 30


degrees?

a. turtle.left(30)
b. turtle.turn(30)
c. turtle.turn(30, “left”)
d. turtle.degrees(30)

2) Which of the following moves the turtle forward by 5?

a. turtle.position(5)
b. turtle.forward(-5)
c. turtle.backward(-5)
d. turtle.distance(5)

3) Which of the following will cause the turtle to stop drawing,


but not stop the whole program?

a. turtle.stop()
b. turtle.end_fill()
c. turtle.penup()
d. turtle.end_draw()
Exercises
4) Which of the following will cause the turtle to change color
to red?

a. turtle.change_red()
b. turtle.red()
c. turtle.change_color(“red’)
d. turtle.color(“red”)

5) Which of the following will cause the turtle to draw a


triangle?

a. for i in range(3):
turtle.fd(10)
turtle.left(60)

b. for i in range(3)
turtle.fd(10)
turtle.left(120)

c. for i in range(3):
turtle.fd(10)
turtle.turn(60)

d. for i in range(6):
turtle.fd(10)
turtle.turn(120)

6*) Use the turtle to draw a square.


Chapter 9: Turtle
7) Use the turtle to write your name. You may need to make the
window larger. You can do this by adding the following code at
the beginning of your program, just under import turtle

setup( width = 500, height = 500, startx =


None, starty = None)

It should all be on one line. You can replace the numbers after
width and height to get a larger window. Do not make them too
large (several thousand ) or else you could run in to issues with
the window not fitting on your screen.

8) Use turtle to draw a house. Make different shapes and fill


them in different colors. Your house should have a roof, a door,
and at least one window.

9*) Write a program that makes a regular shape (triangle,


square, pentagon, hexagon, octagon, …) with a random
number of sides, and every side is a random color. The number
of sides should be some number between 3 and 12. You can do
more sides if you are feeling adventurous, but your shape will
start looking like a circle!

Hint: For a regular shape with n sides, all of the angles will have
a measure of (n – 2) * 180 / n. Bit if you try turning the turtle by
that many degrees, it won’t work. It’s not because the formula
is wrong! Think about how the turtle turns!

10) Write a function called star which takes in one input that is
an odd number. When you call the function, it draws a star with
that many points. For example:
Exercises

>star(5) >star(7)

>star(9)

Once you write it, test it out for different odd numbers. What
happens when you try calling star with an even number?

Hint: For a star with n points, the angle inside the star is 180/n.
You will need to know this for your answer. But if you try using
right(180/n) or left(180/n), you will run in to the same problem
as problem 9. It’s not because the formula is wrong!
Project Ideas
In the experience of the authors, one of the best way of
practicing how to code is to try to code a large project. Any
project will do; if there is some program that you think you can
make that sounds fun, go for it! But sometimes, coming up
with ideas for text-based projects can be tricky, so we have
included some ideas for projects below:

Fill-In-The-Blanks Story Generator


Create a program that will ask the user for different types of
words, using input statements. These words will then be used
to fill in the blanks of a story. Here is a simple example of how
your program might look:

Please say a job:


Firefighter
Please say a name:
Fasika
There once was a firefighter named Fasika.

But your program should be much more complicated than


this!
Project Ideas
Text-Based Adventure Game
Create a program that will allow the user to choose their own
paths in your story and reach an unpredictable outcome. For
example, ask them questions to progress the story like “Do
you like cats?” or “Where would you like to live?” and give
them options to choose from. Then, create a story based on
those options. If they like cats, respond with “One day, you
meet a cat with beautiful luscious orange fur in an abandoned
box along the street” and then continue asking questions to
build the story based on their responses!

Here is one example for how it could look.

You are walking on a forest trail, and you come across a split in
the path. Do you go left or right?
right
Eventually, you find a cave. Do you keep going down the trail,
or go inside the cave?
keep going

Appendix
Random Mini-Story Generator
Create a program that randomly generates a phrase or
sentence and creates a story from multiple when’s, who’s,
how’s, and what’s, etc. Figure out how to create a small story
using different structures (adjectives and verbs, beginning
and end, who’s and what’s, etc.). For example:

Once upon a time, a villager happened upon a tiger with silky


black locks and white stripes in a magnificent, crystal cave.

When, who, what, where.

Hangman
Create a program that randomly generates a word for the user
to guess. Allow the user to guess a letter from the word and
then let them know if their letter is incorrect or correct. If their
letter is incorrect, then keep track of the incorrectly guessed
letters and then print it out for the user. If their letter is
correct, print out the correctly guessed letters in the correct
order in the word.

Hint: You can typecast a string into a list using


list(strng_name). If you do this, each letter of the word will
be its own element in the list.

If you want an extra challenge, have it give you a limited


number of guesses!
Here is an example of how it could look when you run it:
Project Ideas

My word is: [‘_’, ‘_’, ‘_’]


Guess a letter in my word: d

You guessed correctly!


All letters guessed: [d]

My word is: [‘d’, ‘_’, ‘_’]


Guess a letter in my word: b

You guessed incorrectly!


All letters guessed: [‘b’]

My word is: [‘d’, ‘_’, ‘_’]


Guess a letter in my word: g

You guessed correctly!


All letters guessed: [‘b’]

My word is: [‘d’, ‘_’, ‘g’]


Guess a letter in my word: O

You guessed correctly!


All letters guessed: [‘b’, ‘i’]

Congratulations! My word was dog!


Appendix
Fun With Factoring:

We say that a number x is a factor of a number y if you can


divide y by x. For example, 2 is a factor of 10, because you can
divide 10 by 2. 3 is not a factor of 10, because you cannot divide
10 by 3.

We say that a number x is a prime number if it has two factors,


which are 1 and x.For example, the number 5 is prime,
because its only factors are 1 and 5. Notice that the number 1 is
not prime, because it only has 1 factor, which is 1.

Make a program where a user types in a number, and then it


prints out a list of all of the factors of that number. The
program should also have an option to print out all of the
factors of that number which are prime, or just all of the
factors.

To do this, you can use the modulo operator in Python,


denoted %. If a and b are two variables, then a%b == 0 if b is a
factor of a. And a%b != 0 if b is not a factor of a. For example,
12 % 3 == 0, because 3 is a factor of 12. But 12 % 5 != 0,
because 5 is not a factor of 12.

On the next page, we show some examples of how this could


look.

Here are some examples of how this could run:


Project Ideas

What is your number?


10
Prime factors, or all factors?
Prime
[2,5]

What is your number


12
Prime factors, or all factors?
All
[1,2,3,4,6,12]
Appendix
Shopping List Manager

Make a program for updating a shopping list. Your program


should have a loop which asks you for different commands for
managing your list. It should have options to add, remove, and
view the list, at the very least. Here is an example of how it
might look:

What would you like to do?


Add
Add what?
Eggs
What would you like to do?
Add
Add what?
Bread

What would you like to do?


View
Here is your list:
Bread
Eggs
Project Ideas
Password Generator
Write a program to generate a random possible password for
you. It should start by asking:

How many uppercase letters you need


How many lowercase letters you need
How many digits you need
How many special characters you need

Then, using this information, it should output a random valid


password using these numbers. Because the password is
random, the output should not always be the same, even if
you enter the same numbers at the beginning!

Here is an example of how it could run:

How many uppercase letters?


4
How many lowercase letters?
2
How many digits?
4
How many special characters?
3

N@32aE4!#ZA9f
Appendix
Turtle Controller

Write a turtle controller program which asks you for inputs, and
allows you to draw picture by typing in inputs. It should support
at least 5 commands. The output could look like this:

What would you like to do?


Forward

What would you like to do?


Right

What would you like to do?


Forward
Multiple Choice Answers
Chapter 1 Chapter 2 Chapter 3

1) d 1) c 1) b
2) d only 2) e 2) e
3) a 3) b 3) a
4) d 4) d 4) b
5) a 5) b 5) d

Chapter 4 Chapter 5 Chapter 6

1) c 1) c 1) a, b, and c
2) b 2) a 2) d
3) b 3) c 3) c
4) a 4) b 4) c
5) d 5) d 5) d

Chapter 7 Chapter 8 Chapter 9

1) b 1) b 1) a
2) a 2) d 2) c
3) b 3) c 3) c
4) b 4) a 4) d
5) d 5) d 6) b
Answers to Starred Exercises
Chapter 1

Problem 6:
The code will print out:
purple
green
33

Problem 8:
favorite_food = "wings"
favorite_color = "green"
favorite_number = 176
print(favorite_food)
print(favorite_color)
print(favorite_number)

Chapter 2

Problem 7
city = "Wheaton"
state = "Illinois"
country = "United States"
print(city + ", " + state + ", " + country)
Solutions to Starred Exercises
Problem 8
years = 22
days = years * 365
hours = days * 24
minutes = hours * 60
seconds = minutes * 60
print(seconds)

Chapter 3

Problem 8
color = input("Please say a color\n")
if color == "red":
print("apple")
if color == "blue":
print("blueberries")
if color == "green":
print("watermelon")
if color == "yellow":
print("lemon")

Problem 10
# Why does this code us strings again?
hidden_number = "3"
number = input("Please guess a number 1-10\n")
response = "WRONG!"
if number == hidden_number:
response = "Correct!"
print(response)

171
Appendix
Chapter 4

Problem 7
# The requriements to join the club are: You
# must not live in Idaho and you must be under
# 13 years old. Or, if you do not meet the
# requirements, you should know somebody in the
# club.

state = input("What state do you live in?\n")


age = input("How old are you?\n")
age = int(age)
person = input("Do you know a member?\n")

state_bool = (state == "Idaho")


age_bool = (age < 13)
person_bool = (person == "yes")

if (not state_bool and age_bool) or


person_bool:
print("You can join! Congrats!")
else:
print("You cannot join, sorry!")
Solutions to Starred Exercises
Problem 9
hidden_number = 8
guess = input("Please guess a number 1-10\n")
guess = int(guess)
if guess > hidden_number:
print("Too high!")
elif guess == hidden_number:
print("Nice! You got it!")
else:
print("Too low!")

(more on next page)

173
Appendix
Chapter 5

Problem 7
my_lst = []

# Adding the numbers 1-10 to the list


my_lst.append(1)
my_lst.append(2)
my_lst.append(3)
my_lst.append(4)
my_lst.append(5)
my_lst.append(6)
my_lst.append(7)
my_lst.append(8)
my_lst.append(9)
my_lst.append(10)
print(my_lst)

# Removing the even numbers from the list.


# If we didn't do it in reverse order, it would
# be more complicated!
my_lst.pop(9)
my_lst.pop(7)
my_lst.pop(5)
my_lst.pop(3)
my_lst.pop(1)
print(my_lst)
Solutions to Starred Exercises
Problem 10
import random
low = 1
high = 10
rand_lst = []
rand_lst.append(random.randint(low, high))
rand_lst.append(random.randint(low, high))
rand_lst.append(random.randint(low, high))
rand_lst.append(random.randint(low, high))
rand_lst.append(random.randint(low, high))
print(rand_lst)

Chapter 6

Problem 7
counter = 1
while counter <= 100:
if counter != 25:
print(counter)
counter = counter + 1

Problem 10
my_list = [1,2,3,4,5]
print(my_list)
for i in range(len(my_list)):
my_list[i] = str(my_list[i])
print(my_list)

175
Appendix
Chapter 7

Problem 6
tup = ("I want", "this to fit", "on one line")
for line in tup:
print(line)

Problem 9
word = input("Please type in a word")
dict = {}
# First, set up the dictionary so that
# it knows which letters it will keep track of
word_list = list(word)
for letter in word_list:
dict[letter] = 0
# Now, count how many times each letter appears
for letter in word_list:
dict[letter] = dict[letter] + 1
print(dict)

Chapter 8

Problem 8
def print_to(num):
i = 1
while i <= num:
print(i)
i = i + 1
Solutions to Starred Exercises
Problem 9
def tuple_add( first_tup, second_tup ):
first_entry = first_tup[0] + second_tup[0]
second_entry = first_tup[1] + second_tup[1]
new_tup = (first_entry, second_entry)
return new_tup

Chapter 9

Problem 6
import turtle
turtle.fd(100)
turtle.left(90)
turtle.fd(100)
turtle.left(90)
turtle.fd(100)
turtle.left(90)
turtle.fd(100)
turtle.done()

177
Appendix
Problem 9
import turtle
import random

colors = ["red","blue","yellow","green"]
sides = random.randint(3,12)

for i in range(sides):
c = colors[random.randint(0,3)]
turtle.color(c)
turtle.fd(40)
turtle.left(180 - (sides-2)*180 / sides)

turtle.done()
Solutions to Projects
Fill-In-The-Blanks Story Generator

adj1 = input("Type an adjective: ")


obj1 = input("Type a cool object (plural): ")
verb1 = input("Type a verb: ")
adj2 = input("Type an adjective: ")
adj3 = input("Type an adjective: ")

# Note: These print statements take up multiple


# lines in the book, because the page isn’t
# wide enough. They should be on one line each
# in your code!

print(f"Once upon a time, there was a {adj1}


palace that was surrounded by many {obj1}. ")

print(f"As you make your way around them, your


clothes get caught on the {obj1}, and you
decided to {verb1} it. ")

print(f"When you get to the door of the palace,


you realize it is {adj2}. It is all very
{adj3}!")
Appendix
Text-Based Adventure Game

see_scorpion = "You see a scorpion that is of


an extremely venomous species. Do you (a) pet
it or (b)slowly back away from it? "

dead_scorpion = "The scorpion is actually dead,


so you don't get to pet it, but you decide you
can at least roast it and eat it or keep it to
use as a weapon."

scorpion_choice = "Do you (a) eat it or (b)


keep it in your pocket to use as a weapon
later? "

eat_scorpion = "You end up eating it and it is


delicious. You then go walking around and find
a group of people who are very nice to you. You
all live happily ever after together. Good
game."

keep_scorpion = “After keeping the scorpion in


your bag, it ends up waking up. It was asleep
the whole time! You become very startled and
end up bumping into a cactus. It hurts a lot
and you are in pain. Game over."

back_away = "You slowly back away from the


scorpion but you weren't looking where you were
going and end up bumping into a cactus. It
hurts a lot and you are in pain. Game over."
Solutions to Projects
print("You suddenly spawn in the desert.")
b = input(see_scorpion)
if (b == "a"):
print(dead_scorpion)
c = input(scorpion_choice)
if (c == "a"):
print(eat_scorpion)
else:
print(keep_scorpion)
else:
print(back_away)

181
Appendix
Random Mini-Story Generator

import random

# These lists should all be on one line, but


# the page is not wide enough to fit them!

whens = ["Once upon a time", "One day",


"Suddenly"]

whos = ["a villager", "a tiger with silky black


locks and white stripes", "a puppy", "a
prince", "a princess", "an astronaut"]

whats = ["happened upon", "jumped around with",


"played with", "waved at", "laughed with"]

wheres = ["in a magnificent, crystal cave", "in


a massive, mysterious aircraft", "on a warm,
sandy beach"]

# Here is where we pick the parts of the story.


when_number = random.randint(0,len(whens)-1)
when = whens[when_number]

who1_number = random.randint(0,len(whos)-1)
who1 = whos[who1_number]

who2_number = random.randint(0,len(whos)-1)
who2 = whos[who2_number]
Solutions to Projects
what_number = random.randint(0,len(whats)-1)
what = whats[what_number]

where_number = random.randint(0,len(wheres)-1)
where = wheres[where_number]

print(f"{when}, {who1} {what} {who2} {where}!")


#assembling our story!

183
Appendix
Hangman

import random

# You could make this list longer!


words = ["christmas", "holidays", "minecraft"]
word_index = random.randint(0,len(words)-1)
word = words[word_index]
word_list = list(word)

game_running = True
blanks_list = []
guesses = []
for letter in word_list:
blanks_list.append("_")

while game_running:
print("My word is " + str(blanks_list))
guess = input("Guess a letter: ")

# Fill in blanks with the guessed letter


Num_replaced = 0
for i in range(len(word_list)):
if word_list[i] == guess:
blanks_list[i] = guess
num_replaced = num_replaced + 1
Solutions to Projects
# We are still inside the while loop!

# If no letters were replaced, then the


# guess must be wrong
if num_replaced == 0:
print("Incorrect guess!")
else:
print("correct guess!")

# Check if there are any underscores left.


# If there are none, then the game is over.
any_underscores = False
for letter in blanks_list:
if letter == "_":
any_underscores = True

if not any_underscores:
game_running = False

# The code below is not inside the while loop!


print("")
print("My word was " + word)
print("You win!")

185
Appendix
Fun With Factoring

def factor(number): #returns list of factors


# empty list to store the factors
lst = []
#find all the factors of the number
for x in range(1, number + 1):
if (number % x == 0):
lst.append(x)
return lst

def prime(number):
# returns True if the number is prime,
# returns False is the number is not prime
if number == 1:
return False
if number == 2:
return True
for i in range(2, number):
if (number % i == 0):
return False
return True

num = input("What is your number? ")


num = int(num)

# This should be on one line:


factorType = input("Do you want all factors or
prime factors? (Type 'prime' for prime and
'all' for all) ")
factors = factor(num)
Solutions to Projects

if (factorType == "prime"):
primes = []
for factor in factors:
if (prime(factor)):
primes.append(factor)
print(f"Prime factors: {primes}")
else:
print(f"Factors: {factors}")

187
Appendix
Shopping List Manager

lst = [] #empty shopping list


running = True
while running:
print("What would you like to do?")
action = input("add, remove, or view\n")

if (action == "add"):
what = input("Add what?\n")
lst.append(what)

elif (action == "remove"):


what = input("remove what?\n")
removed = False
index = 0
while index < len(lst) and not removed:
if lst[index] == what:
lst.pop(index)
removed = True
index = index + 1
if not removed:
print("I couldn't find " + what)

elif (action == "view"):


print(lst)

else:
print("I did not understand that.")
Solutions to Projects
Password Generator

import random

# These lists should be on one line


# each, but the page isn’t wide enough
# to print them that way.

alphabet = "abcdefghijklmnopqrstuvwxyz"
lowers = ["a", "b", "c", "d", "e", "f", "g",
"h", "i", "j", "k", "l", "m", "n", "o", "p",
"q", "r", "s", "t", "u", "v", "w", "x", "y",
"z"]
uppers = ["A", "B", "C", "D", "E", "F", "G",
"H", "I", "J", "K", "L", "M", "N", "O", "P",
"Q", "R", "S", "T", "U", "V", "W", "X", "Y",
"Z"]
digits = ["0", "1", "2", "3", "4", "5", "6",
"7", "8", "9"]
symbol = ["!","@","#","$","%","^","&","*"]

# Get numbers from the user


lower_num = input("how many lowercase?\n")
lower_num = int(lower_num)
upper_num = input("how many uppercase?\n")
upper_num = int(upper_num)
digit_num = input("how many digits?\n")
digit_num = int(digit_num)
special_num = input("how many specials?\n")
special_num = int(special_num)
character_list = []
189
Appendix
# First, put all needed characters in a list
for i in range(lower_num):
random_index = random.randint(0,25)
character_list.append(lowers[random_index])

for i in range(lower_num):
random_index = random.randint(0,25)
character_list.append(uppers[random_index])

for i in range(digit_num):
random_index = random.randint(0,9)
character_list.append(digits[random_index])

for i in range(special_num):
random_index = random.randint(0,7)
character_list.append(symbol[random_index])

# Take out all of the characters in the list,


# and add them to the password randomly

password = ""
while len(characters_list) > 0:

# This should be on one line:


random_index =
random.randint(0,len(character_list)-1)

password += characters_list[random_index]
characters_list.pop(random_index)

print(password)
Solutions to Projects
Turtle Controller

import turtle

print(“Welcome to turtle! The commands are:”)


print(“'f' for forward, 'b' for backward”)
print(“'r' to turn right, 'l' to turn left”)
print(“'color' to change the color\n”)

while True:
action = input(“Please enter a command\n”)
if (action == “f”):
turtle.fd(100)
elif (action == “b”):
turtle.bk(100)
elif (action == “r”):
turtle.right(90)
elif (action == “l”):
turtle.left(90)
elif (action == “color”):
color = input("What color?\n")
turtle.color(color)
print(“Done.”)
else:
print(“Unknown command: ” + action)

191
Appendix

Glossary of Commands
#comment Does not do anything. Used for
organization and commenting
out code.

def function(parameters) Defines a new function

float(non-float) Turns a non-float object into a


float.

for i in sequence: goes through each item in a


sequence. See for loops for more
information.

if(boolean): Executes the code below or in it


when the boolean is true.

import module_name Tells Python that we want to use


amodule

input(string) Takes the user’s input and


returns a string.

int(non-int) Turns a non-int object into an int


len(obj) Returns the length of a string,
list, or tuple.

list.append(new_element)
Adds the new element to the end
of a list.

list.insert(new_element, index)
Inserts the new element at the
indicated index.

list.pop(index) Removes the element at the


indicated index.

print(string) Prints the string to the console.

str(non-string) Turns a non-string object into a


string.

while(boolean): Repeats code while the boolean is


True

193
Glossary of Vocabulary
assignment Used to store a value inside a
operator (=) variable.

bool A type of data which is either True


or False.

comment A line of code which does not do


anything. Used for organizing
your code, and commenting out
code.

commenting out Making a command into a


comment so that it won’t run.

comparison Used to check if values are equal.


operator (==)

condition The part of the if-statement


which uses the == sign and is
evaluated as True or False.

dictionary A collection of nicknames for


different values, otherwise
known as key-value pairs.
Glossary of Vocabulary
elements The things inside of the list they
are contained in.

elif statement Operates like an if statement but


only executes when the condition
of the if-statement ends up being
False.

else statement Goes after if or elif statement(s)


and runs when the conditions in
the if and elif statement(s) are
False.

float A type of data which represents


decimal numbers.

f-string A string formatted with “f” added


in front of the string and are very
flexible when it comes to types.

function An abbreviation for a larger chunk


of code. Sometimes called a
method.

Integrated Development A program which allows you to


Environment (IDE) write, read, and run your code, all
in one place.

195
Appendix

if statements Tests whether or not a bool


expression is true. Often used to
test if two things are equal.

Index The position number of


something inside of a list or tuple.

int A type of data which represents a


whole number. Short for integer.

key-value pairs Nicknames that have values


associated to each one.

list A type of data structure that can


store multiple values.

loops Used to repeat chunks of code.


There are two types, for loops,
and while loops.

method An abbreviation for a larger chunk


of code. Sometimes called a
function.
Glossary of Vocabulary
module Pre-written code that you can
access from your program.

operator Used for turning information into


other information. For example,
the + sign turns two numbers into
another number.

output The result of operations or


modifications done to the input.

parameter A piece of extra information that


you give to a function to tell it
exactly how it should run.

random The module that allows you to do


operations that have to do with
random.

return statement Allows us to use one value from


inside a function after the
function has finished.

string A primitive datatype for anything


surrounded by “double quotes”.

197
Appendix
string concatenation Merging two strings together,
one after the other.

tuples Essentially the same thing as a


list, except that they cannot be
changed.

turtle A graphical module in Python.

typecasting When we convert the type of one


piece of data into a different type

TypeError An error that is raised when an


operation is attempted to be done
on a datatype that it should not be
done on.

Value The information stored inside of a


variable.

Variable A name for a location in your


computer’s memory.
Index
Addition def, 125
Of ints, 37 Dictionary, 116
Of strings, 32 Accessing, 118
Append, 86 Empty, 116
Arithmetic, 37 Key / value pairs, 118
Assignment operator, 49 Modifying, 119
Assignment, 23 Division, 38

Bool, 27 Element, 84
Operations, 74 Accessing, 86
With if-statement, 73 Modifying, 85
Typecasting to, 35 Of a list, 84
Of a tuple, 114
Calling a function, 126 Elif-statement, 65
Comment, 28 multiple, 67
Commenting out, 29 Else-statement, 62
Comparison operator, 49 Nested 64
Variations, 71
Condition, 49 F-string, 39
Of while loop, 96 Float, 24
Table of symbols, 71 Typecasting to, 35
Of If Statement, 49 For loop, 101
With range, 105, 108
components, 101, 103
Appendix
Function, 124 Installing Python, 9
Calling, 126 Int, 24
Defining, 125 Operations, 37
Parameters, 128 Typecasting to, 35
Multiple, 131 Integrated Development
Using, 129 Environment, 12
Return, 135
Using, 135 Key, 118
Using, see Calling
len, 99
Hello World, 18 List, 83
IDE, 12 Element of, 84
IDE, online, 7 Finding Elements, 86
Idle, 12 Creating, 83
If statement, 47 Functions, 86
Code after, 55 append, 86
Code inside, 51 insert, 87
Condition of, 49, 71 pop, 88
Nested, 53 Indexing, 84
With bool, 73 len, 99
With else, 63 Modifying, 85
with equality, 48 With for loop, 103
With inputs, 50 With random, 90
import, 89 With While Loop, 99
Index, 84
input, 44 Loop
gives a string, 46 While, 96
insert, 87 For, 101
Index
Pop, 88
Math Print, 18
For ints, 37
For bools, 74 Random, 89
Method, see Function randint, 89
Minus, 37 uniform, 90
Module, 88 With lists, 90
Import, 89 return, 135
Random, 89 Using, 136
Turtle, 145
Multiplication, 37 String, 25
Concatenation, 32
New line, 45 F-strings, 39
Typecasting to, 35
Online editor, 9 Vs. variable name, 26
Operator, 72 Subtraction, 37
Arithmetic, 37
Assignment, 49 Tuple, 113
Bools, 74 With for loops, 114
Comparison, 49, 71 Turtle, 145
Parameter, 128 Backward, 148
Multiple 131 Colors, 153
Using, 129 Fill, 153
Forward, 147
Plus Penup/pendown, 151
For numbers, 37 Turning, 150
For strings, 32 With for loops, 155

201
Appendix
TypeError, 34
Typecasting, 34
Permanent, 38
W. concatenation, 36

Value,
Of a variable, 23
Of a dictionary, 118
Variable, 20
Assigning, 23
Changing value of, 24
Making, 21
Names, 22
Vs. strings, 26
Printing, 22

While Loop, 96
Condition of, 96
With lists, 99
Using len, 100
Index
Except for the proper names, the text in this book is a
copyright © 2021 of Bay Coding Club. All rights reserved.

"Python" and the Python logos are trademarks or registered


trademarks of the Python Software Foundation, used by the
authors with permission from the Foundation.

The fonts Liera Sans and Anonymous Pro are both licensed
under the SIL OFL.

With two exceptions, the illustrations in this text were made


using clipart from openclipart.org, and the original images are
licensed under Creative Commons Zero (CC0). The exceptions
are the for loop diagram on page 103, which is an original, and
the portrait of John F Kennedy on page 115, which is in the
public domain, and was accessed via the Library of Congress.

The front cover was made by Freepik.

203

You might also like