Programming For Kids - Python Edition, 2021
Programming For Kids - Python Edition, 2021
Python Edition
Made by the Bay Coding Club
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.
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
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.
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.
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.
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.
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.
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 )
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).
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 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”)
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)
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.
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.
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.
Making Variables
To make a variable in Python, we use the following format:
var_name = value
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
number
number2
___
__I_AM_COOL__
XEliteXBallerX2
Here are some examples of things that are not valid variable
names:
#relatable
your mom
000000000000hi
height = 5
print(height)
height = 10
print(height)
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”
“!@#$%^&*()”
height = 60
dimension = “height”
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
Comments
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 previous code will simply print out “hello world”. The #
sign, and the code after it, will not cause any errors or any other
behavior.
Anyway, that’s basically all that we’ve got for the first chapter.
Good luck with programming!
Exercises:
a. say(“Hello World”)
b. print(Hello World)
c. say(Hello World)
d. print(“Hello World”)
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”
a. My_variable
b. XxX_my_variable_XxX
c. ____________my_variable____________
d. 8o8___my_variable___8o8
5) If we run the code
animal = “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)
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
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”.
When this code is run, it will print “I like being called Tater Tot.”
Typecasting
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
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”.
int(non-int)
height = 50
growth_rate = 10
years = 10
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)
F-Strings
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:
Exercises
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
a = “Molly”
b = 999
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
a. str(14)
b. int(2.0)
c. bool(“True”)
d. str(“False”)
print(a + b)
a. a = “a”, b = “b”
b. a = True, b = 4
c. a = 2, b = 3.0
d. a = 2, b = 3
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:
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:
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
new_variable = input(“Question?”)
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:
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:
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
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.
If thing1 == thing2:
Do something
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!”
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:
if name == “Karen”:
print(“I”)
print(“feel”)
print(“sorry”)
print(“for”)
print(“you”)
if name == “Sanhita”:
print(“Your name is Sanhita”)
Here are some ways that the previous code might run:
So as you can see, you can also put code after an if-statement
that will always run.
Exercises
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
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
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)
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.
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
Hint: Store the response in a string, and change the value of the
string in the if-statement.
Chapter 4
Complex If-Statements
If we run it again
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:
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.
But if the user types in neither Peppa, nor Pig, then nothing will
print out after. The code will look like this:
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:
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”)
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
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)
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.
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:
height = 30
age = 80
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
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:
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
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”)
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?
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:
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.
Creating Lists
The way that you make a list in Python and store in in a variable
is like this:
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
We call the things inside of the list the elements of the list.
List Indexing
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])
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)
[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:
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)
my_list = [1,2,3]
my_list.insert(1.5, 1)
print(my_list)
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
import random
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.
For instance, the following code will print out a random name:
Exercises
print(random.randint(1,20))
import random
a = random.randint(2,4)
if a == 1:
print(“A”)
elif a == 2:
print(“B”)
elif a == 3:
print(“C”)
a. A
b. B
c. C
d. No output
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]
While Loops
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:
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
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.
index = 0
while index < len(list_of_names):
print( list_of_names[index] )
index = index + 1
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 z in names:
print(z)
numbers = [1,2,3,4,5,6,7]
sum = 0
for i in numbers:
sum = sum + i
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)
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:
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.
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 i in range(len(lst))
a = [55,22,35,21,53]
for i in a:
print(i)
a = [55,22,35,21,53]
for i in range(len(a)):
print(a[i])
a = [43,23,65,34,33]
sum = 0
for i in a:
sum = sum + i
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:
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.
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.
Exercises
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!”)
for i in range(100):
print(“bruh”)
a = -5
while a < 5:
print(“yep”)
a = a + 1
a = 0
while a != 11:
print(a)
a = a + 2
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:
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.
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]
You can also access specific positions in a tuple, and it will also
act the same as a list.
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:
You have now learned basically everything that you will ever
need to know about tuples. The next topic is not as simple.
Dictionaries
my_dictionary = {}
my_dictionary[nickname] = data
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.
Me
45
Not me
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.
Exercises
a = (1,5,7,2,3,9)
a. a[4] = ‘four’
b. a[“four”] = 4
c. a.append( { “four” : 4 } )
d. we can’t do it without making a new dictionary.
b = (6,5,4,3,2,1)
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.
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.
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!
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.”)
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.”)
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
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.
def name_of_functions(parameter):
Commands
Commands
Commands
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:
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:
print_name(“Spiderman”)
print_name(“Carmen Sandiego”)
print_name(“Doctor Pepper”)
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:
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”)
name_color(“brown, “Steve”)
name_color(name=”Steve”,color=”brown”)
name_color(color=”brown”, name=”Steve”)
name_color(“Steve”, “brown”)
Return Value
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.
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:
first_num = 4
second_num = do_math(first_num)
print(second_num)
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
def thingy2(a, b, c)
one = a + b
two = c – b
three = 2
print(one + two + three)
thingy2(3,2,1)
def do_math(a,b):
return 2*a*a + 3*b
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)
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
> 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:
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
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
turtle.fd(100)
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)
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)
turtle.color(“name-of-color”)
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
a. turtle.left(30)
b. turtle.turn(30)
c. turtle.turn(30, “left”)
d. turtle.degrees(30)
a. turtle.position(5)
b. turtle.forward(-5)
c. turtle.backward(-5)
d. turtle.distance(5)
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”)
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)
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.
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:
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:
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.
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:
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
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
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.
173
Appendix
Chapter 5
Problem 7
my_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
181
Appendix
Random Mini-Story Generator
import random
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]
183
Appendix
Hangman
import random
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: ")
if not any_underscores:
game_running = False
185
Appendix
Fun With Factoring
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
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
if (action == "add"):
what = input("Add what?\n")
lst.append(what)
else:
print("I did not understand that.")
Solutions to Projects
Password Generator
import random
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 = ["!","@","#","$","%","^","&","*"]
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])
password = ""
while len(characters_list) > 0:
password += characters_list[random_index]
characters_list.pop(random_index)
print(password)
Solutions to Projects
Turtle Controller
import turtle
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.
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.
193
Glossary of Vocabulary
assignment Used to store a value inside a
operator (=) variable.
195
Appendix
197
Appendix
string concatenation Merging two strings together,
one after the other.
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.
The fonts Liera Sans and Anonymous Pro are both licensed
under the SIL OFL.
203