Creative Coding in Python 30 Programming
Creative Coding in Python 30 Programming
Creative Coding in Python 30 Programming
I N G I N
CO D
PY T H O N
C R E A T I V E
I N G I N
O D
C
Y T
P 30+H O N
PROGRAMMING
PROJECTS IN ART,
GAMES, AND
MORE
SHEENA VAIDYANATHAN
© 2019 Quarto Publishing Group USA Inc.
Text and Projects © 2019 Return Metrics Inc.
Series concept, illustrations, and design/presentation © 2019 Quarto Publishing Group USA Inc.
All rights reserved. No part of this book may be reproduced in any form without written permission of the
copyright owners. All images in this book have been reproduced with the knowledge and prior consent of the
artists concerned, and no responsibility is accepted by producer, publisher, or printer for any infringement of
copyright or otherwise, arising from the contents of this publication. Every effort has been made to ensure
that credits accurately comply with information supplied. We apologize for any inaccuracies that may have
occurred and will resolve inaccurate or missing information in a subsequent reprinting of the book.
Quarry Books titles are also available at discount for retail, wholesale, promotional, and bulk purchase. For
details, contact the Special Sales Manager by email at [email protected] or by mail at The Quarto
Group, Attn: Special Sales Manager, 100 Cummings Center, Suite 265-D, Beverly, MA 01915, USA.
10 9 8 7 6 5 4 3 2 1
ISBN: 978-1-63159-581-3
eISBN: 978-1-63159-582-0
Printed in China
To my father,
who inspired me and made me
believe I could always do more
than I thought was possible.
CONTENTS
8
8
8
9
10
11
INTRODUCTION
What Is Coding?
Why Learn to Code?
Why Python?
Installing Python
The First Line of Code
Python Functions
CREATE YOUR
OWN CHATBOTS
16
19
20
1 2
Big Ideas
Storing Data with Variables
Getting Data from the User
Outputting Data on a Screen
CREATE YOUR OWN
ART MASTERPIECES
Big Ideas
38 Turtle Graphics
40 Loops
44 Storing Data in Lists
22 Adding Comments to Your Code
11 Computers Are Picky: Project
23 Doing Math on the Computer
Understanding Errors 46 Creating Geometric Art
12 Problem Solving: Project
Next Steps
Planning Your Code by 26 Creating Your Own Chatbot
50 Experiment and Extend
Writing Algorithms
Next Steps
12 Pseudocode
32 Experiment and Extend
12 Flowcharts
P Y T H O N
PYTHON
INTRODU CTI ON
ENGLISH?
PYTHON?
8 /: : CR E AT I VE C ODI NG I N PY THON
as
ide
nal
ter
/in
hts
ug
tho
for
!
ed
Us
.
ots
sp
nd
na
tio
ca
p pli
ra
the
Installing Python
In order to use the Python language,
you need to use a Python interpreter on
your computer. The interpreter reads,
understands, and runs the Python code. You
also need a tool with which you can type
and save your code.
Pseudocode
this is pseudocode
The First Line of Code
Once you’ve installed Python IDLE, run the application. You
should see the Python shell window. The window shown at left
is from a Mac, but versions on other platforms will look similar.
Python 3.6.1 Shell You should see the prompt:
>>>
10 /: : CR E AT I VE C ODI NG I N PY THON
PRINT HELLO
‘HELLO’
FUNCTION
Python Functions
The print code above is called a print function in computer
programming languages. A function is code that does
something. You may have seen functions in math or in a
spreadsheet application (for example, the “average” function
in a spreadsheet takes in a set of numbers and gives you their
average). Think of Python functions as black boxes that can do
something. You do not have to know how they do their magic,
just how to use them. We do not need to know how print
function works to put the text on the screen.
I NTRODUCTION : : / 11
Problem Solving:
Planning Your Code by Writing Algorithms
Learning the functions and syntax of a programming language
so you can use it to give instructions to a computer is just
one part of coding. The other, usually more difficult, part is to
understand what instructions to give to solve a given problem.
Pseudocode
Set total to 0
Repeat 10 times the following
Get number from user
Add number to total
Print the total to the screen
No
I NTRODUCTION : : / 13
Print
1
customized
messages
based on user
input.
Create custom
calculators
to do your
math chores.
Use your
creativity
to generate
silly stories
or fun songs.
Use variables
to store
information
CREATE
YOUR OWN
CHATBOTS
Crunch
numbers with
powerful math
functions.
BI G I D EA
STORI N G DATA
W I TH VARI ABLE S
I need to store 0
the player’s
Value of the
score. I will use
variable
a variable.
player_score
Name of the
variable
NESTING QUOTES
player_score = 0
If the text uses single or double quotes, you must
use the other kind of quotation mark around it.
Read this as “the player_score variable is set to 0,” or “the
player_score variable is assigned a value of 0.” Do not read For example:
it as a mathematical equation or the next example will be very
confusing! s = "Shelly's house"
As the game runs, the score changes, so the value in the action = 'She shouted "Go away!"'
player_score = player_score + 1
For example:
>>> player_score = 0
>>> player_score
Adding strings is often used to create new
0
messages or information in a program. Sometimes
>>> player_score = player_score + 1
a program may start with an empty string, shown
>>> player_score
as '', and add new information as it runs.
1
name = 'Zoe'
Zyxo This will not work because the variable name has spaces. You
will get a syntax error—Python telling you that it does not
understand.
alienName = 'Speedy'
alien_name = 'Speedy'
Then, type in your name and press Enter. If you type the
variable name in the Python shell, you can see that the value
stored in it is the information you entered. See below on how
this works.
hello, world!
print(23, end=',')
For whole numbers (known as integers in Python):
print(23)
print(3.14)
print(player_score)
In this book, all comments will be shown using bold text. As you’re trying out
the example code on your computer, you do not have to enter the comments.
You will find far more comments in the code in this book than what an average
programmer may use because here they are used as a teaching tool to explain
more about the code.
22 /: : CR E AT I VE C ODI NG I N PY THON
BI G I D EA
D OI N G MATH
ON THE COMPU TER
Computers can crunch through numbers and do complex math. That’s how they
were first used, and it continues to be one of the most popular reasons to write
programs. Today, we are interested in computing the large amount of data we
generate each day as we use websites and apps. Having the ability to write a custom
program to analyze data is useful in many applications.
Calculating in Python
The Python shell can be used as a powerful calculator. Type the following into the
Python shell to experiment with basic math operations. Remember, you do not need
to type in the comments—anything after and including #.
Using variables, we can store some numbers in memory and then use them in math.
For example:
width = 100
height = 20
area = width * height # area is width multiplied by height
print(area)
Please note that the above variables have numbers without a decimal point (known
as integers).
You can also use numbers with decimal points, known as floats. Try the following in
the Python shell:
distance = 102.52
speed = 20
time = distance / speed
time
The variable number in the example (see below) appears to To treat the user entry as an integer, you must explicitly
be an integer 2. However, it is actually text—a string “2”. You convert it from a string to an integer using the int function.
can see it by entering number in the Python shell to see that it For example, to convert the variable in this example to an
has quotation marks around it. In the example shown, the user integer and store it again in the same variable, number,
entered 2, and it appears as ‘2.’ So adding two strings results in do the following:
concatenating the strings (combining two pieces of text); the
‘2’ and ‘2’ become ‘22’.
number = int(number)
The file ending in .py indicates that it is a Python file. You can run this Python file
by clicking on Run > Run Module and also from a command line interface on any
computer that has Python installed. For example, you can run the project from a
terminal window on Unix or Mac using python3 Chatbot.py.
Pseudocode
Get current year from user
Get chatbot age from user
Print guess is correct
Convert chatbot age to integer
Set years to 100 - chatbot age
Print I will be 100 in years
Step 2: Convert current year to integer
Add Code for the Introductions Print That will be current year + years
To start, the chatbot introduces itself using print statements
and asks the user for their name using an input statement. The Python Code at End of Step 3
name entered by the user is stored in a variable called name
and used again later to print a custom message. # get year information
year = input('I am not very good at dates. What \
Pseudocode
is the year?: ')
Print introduction to the chatbot
print('Yes, I think that is correct. Thanks! ')
Get name from user
Print hello name # ask user to guess age
myage = input('Can you guess my age? - enter a \
Python Code at End of Step 1 number: ')
print('Yes you are right. I am ', myage)
# chatbot introduction
print('Hello. I am Zyxo 64. I am a chatbot') # do math to calculate when chatbot will be 100
print('I like animals and I love to talk about food') myage = int(myage)
name = input('What is your name?: ') nyears = 100 - myage
print('Hello', name, ', Nice to meet you') print('I will be 100 in', nyears, 'years')
print('That will be the year', int(year) + \
nyears)
Add the code above to your file and then test it by clicking on
Run > Run Module.
Add the code above to your file and then test it by clicking on
Run > Run Module.
28 / : : CR E AT I VE C ODI NG I N PY THON
Step 4:
Use Data Stored for Simple Fill-in
Template Responses
We can now ask and respond to the user on a few topics, using the data entered by
the user where possible in the conversation. Here is an example of a conversation on
food and another one on animals. Notice how the responses entered by the user are
I will be 100 stored in variables and reused in the print statements.
in 2104
# food conversation
print('I love chocolate and I also like trying out new kinds of food')
food = input('How about you? What is your favorite food?: ')
print('I like', food, 'too.')
question = 'How often do you eat ' + food + '?: '
howoften = input(question)
print('Interesting. I wonder if that is good for your health')
# animal conversation
animal = input('My favorite animal is a giraffe. What is yours?: ')
print(animal,'! I do not like them.')
print('I wonder if a', animal, 'likes to eat', food, '?')
Add the code above to your file and then test it by clicking on Run > Run Module.
Yummy!
I like chocolate.
What about you?
How you are Add the code above to your file and then test it by clicking on
feeling? Run > Run Module.
Step 6:
Close with a Custom Goodbye
Close the chatbot conversation with a custom goodbye using the
user’s name.
# goodbye
print('It has been a long day')
print('I am too tired to talk. We can chat again later.')
print('Goodbye', name, 'I liked chatting with you')
Add the code above to your file and then test it by clicking on
Run > Run Module.
GOODBYE
3 0 /: : CR E AT I VE C ODI NG I N PY THON
How Can You Make This Chatbot Better?
One of the biggest problems with this project’s code is that the
computer does not have any choice on what output to give.
It cannot decide to do a different output based on the input.
In order to do this, the chatbot must make decisions. We will
learn to do this with conditional statements in Chapter 3.
USEFUL CHATBOTS
There are several chatbots in use today that can
handle simple conversations and are used in sales,
customer support, and other applications. With
more advances in computing, chatbots understand
not just typed text but also human speech.
They can rely on large amounts of data to reply
intelligently and can respond not just in text but in
a human’s voice.
Experiment 1:
Mad Libs
Using the idea of storing user input into variables and using
them in new output, you can create a version of the classic
Mad Libs game.
Pseudocode
Get words for song from user
Print song with responses filled into template
Sample Run
Enter something plural that is red. example roses: cherries
Enter something plural that is blue. example violets: oceans
Enter something plural you love. example puppies: baby pandas
Enter a verb such as jumping, singing: dancing
-------------------
cherries are red
oceans are blue
I like baby pandas
But not as much as I love dancing with you!
Pseudocode
Get inches from user
Convert inches to integer
Set cm to inches x 2.54
Print cm
Get pounds from user
Experiment 4:
Convert pounds to integer
Restaurant Bill Calculator
Set kg to pounds / 2.2
Ask the user for the total of the restaurant bill, what
Print kg
percentage tip they want to give, and the number of people
Get fahrenheit from user
the bill is to be shared between. Give the total tip and total
Convert fahrenheit to integer
amount, followed by the tip amount per person and total of the
Set celsius to fahrenheit - 32 / (9/5) bill per person.
Print celsius
Pseudocode
Sample Run
Get bill amount from user
Enter distance in inches: 102
Get tip percentage from user
102 inches is equal to 259.08 cm
Get number of people from user
Enter weight in pounds: 145
Convert all user input to integers
145 pounds is equal to 65.91 kg
Set tip amount to tip bill amount x ( percentage / 100 )
Enter temperature in Fahrenheit: 70
70 Fahrenheit is equal to 21.11 Celsius
Set total amount to bill amount + tip amount
Print tip per person , tip amount / number of people
Print total per person , total amount / number of people
Sample Run
What is the total on the bill?: 55
What % tip would you like to give?: 15
How many people are sharing the bill?: 4
Tip amount = 8.25
Total bill = 63.25
--------------------------
Tip amount per person = 2.06
Total amount per person = 15.81
3 4 / : : CR E AT I VE C ODI NG I N PY THON
Experiment 5:
Paint Calculator
Ask the user for the length, width, and height of a room in feet
and ask for the number of doors and windows. Give them the
total area to be painted and the amount of paint needed for
the walls, assuming you can subtract 20 square feet for each
door and 15 square feet for each window and that the paint
coverage is 350 square feet per gallon.
Pseudocode
Get height, width, length from user
Get number of windows, doors from user
Set wall area to (2 x length x height) + (2 x width x height)
Set NoPaintArea to 20 x doors + 15 x windows
Set PaintArea to wall area - NoPaintArea
Print PaintArea
Set gallons to wall area / 350
Print gallons after rounding to 2 places
Sample Run
Enter length of the room in feet: 24
Enter width of the room in feet: 14
Enter height of the room in feet: 9
Enter number of doors: 2
Enter number of windows: 4
Total surface area to paint 584
Number of gallons of paint needed 1.67
2
of colors
to create
rainbow art.
Use the
Python turtle
to create
artwork.
Experiment
with shapes,
backgrounds.
Use loops to
repeat shapes and
create intricate
geometric
patterns that
are only possible
in code.
CREATE YOUR
OWN ART
MASTERPIECES
Use your
creativity
to make
drawings of
faces, houses,
and more.
BI G I D EA
T U RTLE GRAPHI CS
import turtle
WHY A TURTLE?
Turtle graphics was inspired by a robot called a turtle
that was controlled by the LOGO programming language.
LOGO was developed by Seymour Papert, Wally
Feurzeig, and Cynthia Solomon in 1967. Their work
continues to inspire many programming languages used
in education today.
y axis
CHANGING THE
x = −400, y = 300 x = 400, y = 300
TURTLE’S SHAPE
You can change the turtle’s shape from the
classic triangle to a more realistic-looking
turtle by entering:
x = 0, y = 0 x axis shelly.shape('turtle')
The center of the window is the x coordinate 0 and the y coordinate 0. See the
diagram above for other sample points in the turtle graphics window.
Pseudocode
repeat 4 times the following:
move 100 steps forward
turn 90 degrees to the left
You should see the turtle draw a square in the turtle graphics Adding Color
window again and print the numbers 0, 1, 2, and 3 in the To color in the square, you must call the function begin_fill
Python shell, as shown below. and set a color before the shape is drawn and then end with an
end_fill function.
0
Below is the complete code required to create a red square. You
1
can enter this in the Python shell line by line or create a new file
2
in the editor and run it.
3
# red square
Remember, the variable is called i in these examples, but you
import turtle
can use any variable name.
shelly = turtle.Turtle()
shelly.begin_fill() # start filling shape
shelly.color('red') # use color red
for i in range(4):
shelly.forward(100)
shelly.left(90)
Nested Loops
Look at this shape. Can you see it is a series of squares, each
turned a little (exactly 60 degrees, actually)? To make this,
we can use the loop above to make the square and then
repeat that loop six times, with a 60 degree turn in between
each repetition. We will repeat something that itself repeats.
Move forward
Turn left
Here is the pseudocode to draw this shape. As you can see, the loop for the square is
inside the loop that repeats 6 times.
Pseudocode
repeat 6 times the following:
repeat 4 times the following:
move 100 steps forward
turn 90 degrees to the left
turn 60 degrees to the right
Experiment by changing the numbers in the code above. Instead of the outer loop
repeating 6 times, what happens if you change it to 100 times? What else will you
need to change to make the squares closer together?
A computer can store a collection of items in a list. In this To get to each color, the computer can use an index or counter
chapter, we will store the names of colors that we need for to step through the list, pulling out one item at a time.
a rainbow drawing into a list called colors. A list is a special
To store the color red in the first item in the list called colors,
variable that has multiple items, which we can access one at a
the computer assigns red to the 0th position in this list.
time. Think of a list as a storage location that looks like a series
of boxes or shelves in a bookshelf. To get the color red, the computer can then access item 0 in
the list.
Computers number items in a list starting at 0. The first item
is the 0th item in the list.
t
us r
m be
I
em se
m
re he ill
l t I w
al . t!
rs lis
o lo a
c e
ak
m
COLORS
4 4 / : : CR E AT I VE C ODI NG I N PY THON
How to Set Up a List in Python
The code to set up the list is as follows: To get each color in order, you need to get the 0th color, 1st
color, 2nd color, and so on—basically the color corresponding
to the counter in the loop. If the counter in our loop is i, we
colors = ['red', 'green', 'blue']
would use the following to get the ith color.
Notice how the list is enclosed with square brackets and how
shelly.color(colors[i])
each item, in this case name of color, is separated by a comma.
Because each color name is a piece of text, it is written in
quotation marks. Try this by entering the following code. You should see three
lines, one for each color printed in the Python shell.
Lists in Python are indexed starting at 0. So to access the color
red, we need to get the 0th item in the list, which is accessed
by using colors[0]. Type the following, one line at a time, into colors = ['red', 'green', 'blue']
the Python shell to test it out: for i in range(3):
shelly.color(colors[i])
shelly.forward(50)
colors = ['red', 'green', 'blue']
print(colors[i])
colors[0]
colors[1]
We will use this idea in our project to draw rainbow patterns.
This is what you should get: Note: Python lists are very powerful, and we can use them in
many ways. We will learn more about using lists in Chapter 4.
>>> colors = ['red', 'green', 'blue']
>>> colors[0]
'red'
>>> colors[1]
'green'
You can change the color for your turtle by taking a color from
the list. For example, to get red you would use:
shelly.color(colors[0])
Start a new file called Art.py, enter the following code, and run
it to make sure you get a turtle. Add a comment line on the
top to remind you of the project. Adding comments is good
programming practice.
Pseudocode
repeat 6 times the following:
move 100 steps forward
Step 1: hexagon with triangular turtle
turn 60 degrees to the left
4 6 /: : CR E AT I VE C ODI NG I N PY THON
Step 2: Repeat the Hexagon
Using a Nested Loop
Now that we have a hexagon using a loop, we can put You can select the for loop code from your previous project
this hexagon code inside another loop that repeats, to get and press Tab to indent it (or select and click on Format >
a number of hexagons arranged in a circle, each slightly Indent Region on IDLE).
overlapping each other.
Then, add the for n in range(36): on top and the
Modifying the pseudocode from Step 1, we can turn each shelly.right(10) below it to handle the other part of the
hexagon just 10 degrees from the previous one. To complete pseudocode.
the circle, we need to do this a total of 360 ÷ 10 = 36 times
Remember, the comments after the # are optional. They only
(360 is the total number of degrees in a circle).
explain to the programmer what the code is doing.
Pseudocode To complete Step 2, your Python code should look like this:
repeat 36 times the following:
repeat 6 times the following: # make a geometric pattern
move 100 steps forward import turtle
turn 60 degrees to the left shelly = turtle.Turtle()
Turn at 10 degrees to the right for n in range(36):
# repeat 6 times - move forward and turn
for i in range(6) :
shelly.forward(100)
Python Turtle Graphics
shelly.left(60)
shelly.right(10) # add a turn
4 8 / : : CR E AT I VE C ODI NG I N PY THON
Python Turtle Graphics
Step 4:
Add Small White Circles
Around the Pattern
You can also make the turtle go to the outer edge of the
pattern, make a small circle, return to the center, and then
repeat, going all the way around the pattern. This is fun
to watch, and it adds an extra detail to the art that’s very
easy to do in code but not so easy to create using any
other art medium.
Experiment 1:
Create a Row of Colored Squares
Start with this pseudocode to try creating a row of colored Python Turtle Graphics
squares:
Pseudocode
repeat 6 times the following:
Set color from list
Repeat 4 times the following:
Move forward 20
Turn left 90
Put pen up
Move forward 30
Put pen down
Hide turtle
Experiment 3:
Make a Green Face with Circles
Can you make this green face using a series of circles? To help Python Turtle Graphics
get you started, here’s the code for making one eye:
shelly.goto(-30,100)
shelly.begin_fill()
shelly.color('white')
shelly.circle(30)
shelly.end_fill()
shelly.begin_fill()
shelly.color('black')
shelly.circle(20)
shelly.end_fill()
5 0 /: : CR E AT I VE C ODI NG I N PY THON
Experiment 2:
Make a House with Starter Code
Start with the following code, which creates one filled gray Python Turtle Graphics
# make a house
import turtle
turtle.bgcolor('blue')
shelly = turtle.Turtle()
# make the first big square for house
shelly.begin_fill() # start fill of color
shelly.color('gray')
for i in range(4):
shelly.forward(100)
shelly.left(90)
shelly.end_fill() # end fill of color
shelly.penup()
shelly.goto(-20,100) # move turtle to next area
shelly.pendown()
# make a red triangle roof
shelly.begin_fill() # start fill for roof
shelly.color('red')
shelly.left(60)
shelly.forward(140)
shelly.right(120)
shelly.forward(140)
shelly.right(120)
shelly.forward(140)
shelly.end_fill() # end fill of color for roof
# make a window
shelly.penup()
shelly.goto(25,80) # move to window position
shelly.pendown()
shelly.begin_fill() # start filling window color
shelly.color('yellow')
for i in range(4):
shelly.forward(20)
shelly.left(90)
shelly.end_fill() # end filling window color
# hide the turtle when done
shelly.hideturtle()
Pseudocode
repeat 36 times the following:
Make a circle of size 100
Turn 10 degrees to the right
Experiment 5:
Circle of Circles
Change the code at end of Step 4 to make multiple circles Python Turtle Graphics
coming back. Use the following:
Pseudocode
repeat 36 times the following
Lift pen
Move forward 200
Repeat 6 times
Put pen down
Make a circle of size 5
Put pen up
Move back 20
Move back to center 80
Turn 10 degrees to the right
Hide turtle
Repeat
tasks until
you are
ready to
quit.
Use your
creativity and
write your own
interactive
fiction. Make a
custom quiz
game for
friends and
family.
CREATE
YOUR OWN
ADVENTURE
GAMES
BI G I D EA
COMP U TE RS U N DE RSTAN D
T RU E AN D FALSE
Python is
simple to
True.
learn.
24 is an
even
number.
True.
312 is
less than
123.
False.
True
R is equal to 0. Print to screen that n is even.
False
>>> name = 'Zoe' # set the variable name to the value Zoe
>>> name == 'zoe'
False
>>>
We can also use other comparison operators to check if something is true or false.
Here are some examples.
x < 2
choice == 'yes'
player_score > 100
Take an umbrella.
I have an
AND OPERATOR
umbrella.
If we know that “It is raining” is true AND we know that “I have
an umbrella” is also true, we know we can take our umbrella
with us when we step outside.
OR OPERATOR
If we know that “It is windy” is true OR if we know that “It is
cold” is true, we can decide that we should take a jacket. We
will also take our jacket if it is cold, if it is windy, or if it is both
cold and windy.
NOT OPERATOR
If we know that “It is warm outside” is false (it is NOT true),
we can decide that we should take a jacket.
For example: The game can proceed if both the number of lives (stored in variable
lives) and amount of time left in game (stored in variable game_time) are greater
than 0.
For example: The game must end if either number of lives (stored in variable lives)
is equal to 0 or if there is no time left; that is, the amount of time left in the game
(stored in variable game_time) is equal to 0.
True . . . If blo
We make decisions and execute different actions based on
c k of code
something being true or false.
For example, consider a decision you may make at breakfast e blo ck of code
time: If there are eggs in the refrigerator and I have time False . . . Els
(both have to be true), I will make a fried egg for breakfast
and then sit down and eat it. Else, I will take a granola bar to
eat on the way. Based on the condition being true or false,
?
you do different actions.
Make
True instant
Make fried eggs. Make toast.
I have eggs in the refrigerator oatmeal?
Eat eggs and toast for breakfast.
AND I have time.
False Take a
granola
bar to
Conditional (If-Else) Statements >>> day = input('enter day of the week ')
Try this in the Python shell: enter day of the week monday
>>> if day == 'saturday' or day == 'sunday':
It is wet outside
Wear rain boots
Take an umbrella
>>>
Run the above code again, and this time set raining to be False.
Nothing will print.
INDENTED CODE
Once you type in the colon in the conditional statement,
all the lines of code after it must be indented to denote it
else
if
as the block of code that must be run.
Python is very picky on indentation; it should be the same
amount for all the lines of code that are part of the block.
It is best to allow the IDLE editor to help with this, instead
of typing in your own spaces or tabs.
Nested Conditionals
Often, we may check on another condition after the first one
and then decide further. There are no eggs or there is not
enough time to make fried eggs for breakfast, so we now
check to see if there is time to make oatmeal. We can add an
if-else statement inside another one.
False
False
Guess the
number.
83?
6 4 / : : CR E AT I VE C ODI NG WI TH PY THON
Elif Statements
Set the alarm?
When the problem requires different code blocks for multiple
Do I have class?
conditions, we can use the elif construct in Python instead of
Carpool today?
multiple nested conditions.
It depends on the
In the example below, a set of code is run for Monday and day of the week.
Wednesday, another is run for Tuesday and Thursday, another
is run for Friday, and a final one is run for Saturday and Sunday.
Enter this code into a new file called week.py.
The flowchart at right has a loop—you can see the line going
back. The decision box at the top of the loop is the condition to
be tested in the conditional loop.
Here is the code for the flowchart. Enter it in a new file called
guessNumberVersion2.py.
6 6 / : : CR E AT I VE C ODI NG WI TH PY THON
Set secret_number
Here is a flowchart for this modified version of the game.
True
n equals secret_number? Print “done” STOP
False
True
n > secret_number? Print “too high”
False
STRUCTURE OF A
CONDITIONAL LOOP
All conditional loops are of the form:
Pseudocode
Set initial condition
While condition is true :
Code to be run each time inside loop
Change condition
This is a sample—you can customize it You are visiting Santa Cruz, California.
to make it your own adventure game. You go on an evening hike alone in the mountains.
You can extend it with more items, You can pick one item to take with you -
# adventure game
print('Welcome to the Santa Cruz Mountain Adventure Game!')
print('*************************************************')
print('You are visiting Santa Cruz, California.')
Get choice of item print('You go on an evening hike alone in the mountains.')
from the user.
print('You can pick one item to take with you - ')
print('map(m), flashlight(f), chocolate(c), rope(r), or stick(s): ')
item = input('What do you choose?: ')
print('You hear a humming sound.')
choice1 = input('Do you follow the sound? Enter y or n: ')
if choice1 == 'y':
Follow the sound?
print('You keep moving closer to the sound.')
Yes No
print('The sound suddenly stops.')
print('You are now LOST! ... ')
print('You try to call on your phone, but there is no signal!')
Print-you are now lost. Print-you return;
sound follows you. else:
print('Good idea. You are not taking risks. ')
print('You start walking back to the starting point.')
print('You realize you are LOST! ')
print('The sound is behind you and is getting louder. You panic! ')
7 0 /: : CR E AT I VE C ODI NG I N PY THON
Step 2:
Add a Loop ?
Now that we have created two different possibilities, we will add
more code to extend the story. In this step, we add to the else
section (in which the user starts walking back and the sound
gets louder).
We give the user a choice to run or call for help, but using a while
loop, we only let them proceed if they choose to run.
After the else part in Step 1, that is, right after this line of code:
print('The sound is behind you and is getting louder. You panic! ')
action = input('Do you start running (r), stop to make a call (c)?: ')
while action == 'c':
print('The call does not go through')
action = input('Do you want to run (r), or try calling again (c)?: ')
print('You are running fast. The sound gets really loud')
No
Action = c? Print-you start running.
Sound gets louder.
Yes
h ich
W
y?
wa
Step 3:
Add a Choice of Direction
In the if part of Step 1 (when the user follows the sound), we
can ask for a choice of direction once the sound stops.
Get direction
Yes Yes
North? Reach cabin Map? Use map to find way.
No No
Yes
West? Hurt your leg STOP
You lose.
STOP
No You win.
No
Yes Yes
South? Reach bridge Rope or stick? Fix bridge and return.
No
No
Yes
Reach highway Flashlight? Signal for help.
7 2 /: : CR E AT I VE C ODI NG I N PY THON
After the if part in Step 1, that is, right after this line of code:
direction = input('Which direction do you go? north, south, east, or west: ')
if direction == 'north':
print('You reach an abandoned cabin.')
if item == 'm':
print('You use the map and find your way home.')
print('CONGRATULATIONS! You won the game. ')
else:
print('If you had a map, you could find your way from here.')
print('---You are still lost. You lost the game.---')
elif direction == 'south':
print('You reach a river with a broken bridge.')
if item == 'r' or item == 's':
print('You chose an item that can fix the bridge.')
print('You fix the bridge, cross over, and find your way home')
print('CONGRATULATIONS! You won the game.')
else:
print('If you had a rope or a stick, you could fix the bridge.')
print('---You are still lost. You lost the game.---')
elif direction == 'west':
print('You are walking and trip over a fallen log.')
print('You have hurt your foot. You sit down and wait for help.')
print('This could be a long time. You are still lost.')
print('---You lost the game.---')
else:
print('You reach the side of the highway. It is dark.')
if item == 'f':
print('You use the flashlight to signal.')
print('A car stops and gives you a ride home.')
print('CONGRATULATIONS! You got out safely. You won the game.')
else:
print('If you had a flashlight, you could signal for help.')
print('---You are still lost. You lost the game.--')
What is my favorite
Woman helps you.
programming language?
Yes
Step 4: Python?
Yes
Chocolate
Make the User Answer a Question
to Determine the Next Action
No No
Add a puzzle or quiz question that the user must answer correctly
to determine the next action. Add this after the user is
STOP
running fast, after the code in Step 2. You lose.
After this while loop, when you are running fast, that is,
after the line:
print('You are running fast and then the sound gets really loud')
We can improve the step at which the user must type in “python” by allowing
them to type in the answer using uppercase, lowercase, or a combination—that is,
“Python”, “python,” or “PYTHON.”
One way to do this is to check for each possible user input. So we can change this
part:
if answer == 'python':
to:
To make the game run better, you can slow down the output by inserting a 1 Change the actual text of the story to a
pause. This allows the user to read and makes it more dramatic. For example, better story.
in the beginning of the story, just before you tell the user they are lost, you can 2 Change or add more items to choose in
stop for few seconds before you continue. the beginning.
To insert this pause, use the sleep function, which is part of another Python 3 Change or add more questions asked
module—the time module. To use a pause in your code, insert the following on by the woman and the resulting
top of your file: actions.
4 Add more puzzles in the form of
import time questions and items to be collected.
5 Add more error checking; check if all
Then, at any place you want to pause, enter the following code. The number in input is valid.
parentheses is the number of seconds. For a 3-second pause, use: 6 Add more ways for the user to respond;
instead of just y or n, maybe allow yes
time.sleep(3) and no.
7 Add an energy variable that changes as
Try changing the code in Step 1 to: you move through various levels.
8 Add more pauses, using the sleep
if choice1 == 'y': function, to make the game run better.
print('You keep moving closer to the sound.') 9 Add some text graphics to make the
print('The sound suddenly stops.') output look better.
time.sleep(3) # add a 3 second pause here for user to read
Adding more complexity and decision-
print('You are now LOST! ... ')
making to the story will make it better.
time.sleep(3) # add a 3 second dramatic pause here
Use as many ideas as possible to expand
print('You try to call on your phone, there is no signal!')
your game.
7 6 /: : CR E AT I VE C ODI NG I N PY THON
Experiment 2 :
Dog or Cat to Human Age Calculator
Many people multiply the age of a dog by 7 to get the
equivalent age in human years. A more accurate calculation
for the age of dogs and cats in human years is as follows.
Dogs:
■ 1st dog year = 12 human years
■ 2nd dog year = 24 human years
■ Add four years for every year after that.
Cats:
■ 1st cat year = 15 human years
■ 2nd cat year = 24 human years
■ Add four years for every year after that.
Sample Run
Enter dog or cat: cat
Enter age of animal: 4
Human age of cat is 32
7 8 / : : CR E AT I VE C ODI NG I N PY THON
Experiment 3:
Quiz Game
Create a program that asks the user a fixed number of questions on any topic and
then gives them a score depending on how many are correct. Use a list for the
questions and a list for the corresponding answers.
Pseudocode
Set score to 0
Set n to number of questions in list
Repeat n times the following
Print question from list
Get answer from user
if answer is correct
Print Correct
Increase score by 1
else
Print Incorrect
Print the correct answer
Print score.
Pseudocode
Get count by from user
Set n to 0
Get user choice - quit or not
While user choice is not quit do the following
Print n
Increase n by count by
Get user choice - quit or not
SAMPLE RUN
Enter number you want to count by :7
Enter return to continue or q to quit:
0
Enter return to continue or q to quit:
7
Enter return to continue or q to quit:
14
Enter return to continue or q to quit:
21
Enter return to continue or q to quit:
28
Enter return to continue or q to quit:
35
Enter return to continue or q to quit:
42
Enter return to continue or q to quit:q
Sample Run
How are you feeling today?: sad
Sorry to hear you are sad. Why are you feeling
this way? :
4
computer
poems that
games.
surprise your
friends.
Create art
that changes
each time the
program runs.
Use your
creativity
and create
your own
games of
chance.
Build your own
functions to
reuse code in
powerful ways.
CREATE YOUR
OWN DICE
GAMES
Challenge
your friends
to your
custom word
games.
BI G I D EA
CRE ATI N G
YOUR OWN FU NCTI ONS
We have already seen several built-in Python functions, How Functions Are Used in Python
including print, input, and of course, the turtle functions. Now,
Functions are created in Python using the keyword def, the
we will learn how to make our own functions.
name of function, any parameters—information the function
Functions allows us to name a block of code and then reuse it takes—within parentheses, and then a colon to separate the
later by using the name. block of code that must be indented below it. Again, IDLE will
auto-indent any line after entering : .
A simple example is the code we wrote in Chapter 2 for
creating a square with the turtle. If we name the code square, Let us look at the example of creating a square using the turtle.
we (or anyone who uses our code) can create a square at any We saw the following code in Chapter 2:
time, by just calling it by name.
There are two parts to using your own functions: import turtle
shelly = turtle.Turtle()
1 Defining the function. Think of this as teaching the
computer a new word. In the example above, we teach the
for i in range(4):
computer how to respond to the word square by making a
shelly.forward(100)
square.
shelly.left(90)
2 Calling the function. Think of this as using the new word
that you have made.
We can take the code that draws the square and give it the
In addition to making reusing code easier, functions help us name square using the keyword def. We can then call this
organize our code and share it with others. function a few times by using square() to make squares.
84 / : : CR E AT I VE C ODI NG I N PY THON
This is the name of the function.
Try this by creating a new file called myfunctions1.py and the code below:
# my functions
import turtle
shelly = turtle.Turtle()
As you can see in the code above, we do not write out the
lines of code to make the three squares each time. The code Python Turtle Graphics
Copy the code from the previous project into a new file called
myfunctions2.py and change the square function to use a size
as a parameter. See the code below. The name of the parameter in
this example is s, but you can pick any name. Inside the code
for the function, s is used instead of a fixed number 100, so it
draws a square on any size that is given to it as a parameter.
To use the square, you must now enter the size needed as a
parameter. So square(100) makes a square of size 100;
square(200) makes a square of size 200.
import turtle
shelly = turtle.Turtle()
The square function can be used anywhere you use a Python function. For example,
you can use square function inside a for loop. What does the following make?
for i in range(25):
square(i)
shelly.forward(i)
For example, we can create a function that takes a list of scores and returns their
average. In a new file called myfunctions3.py, enter and run the following:
Here is another example in which the function returns a list of cards made from
two lists. This can be used to create a card game—see the Experiment and Extend
section.
def make_cards():
cards = [] # start with empty list and add cards
for s in suits:
for i in cardno: # for each card number in each suit
cards.append(i + '-' + s)
return cards
my_cards = make_cards()
print(my_cards)
For example, to improve the number guessing game from Chapter 3, we may
want the computer to pick a number between 1 and 100 at random, instead
of writing it in our code. This way, it is different each time we run the program
and even the programmer does not have the correct answer.
import random
To select a number at random between a start range and an end range, use:
random.randint(start of range, end of range).
random.randint(1,100)
hello
Nico
CO
TR
IS LE
NI
HA KY
NAMES
CREAT E YOUR OW N DICE GA M E S : : / 8 9
This is the variable that will become each item in
the list for each time the loop runs; it is called j
here, but you can use a different variable name.
We can use this same idea for any list that we use.
Strings work in a similar way: the loop is per character in the
For example: string. Here is an example.
P
y
t
h
o
n
In the sample run below, the game is for six dice. The user gets
a roll of 4, 6, 5, 6, 2, and 5 and decides to hold all except the
2. They enter choices using ”-“ to hold and “r” to roll again.
After the user gets a new roll, the computer rolls, following a
strategy in which anything below 5 must be rerolled. In this
game, the computer wins.
# dice game
CHOOSING GOOD
FUNCTION NAMES
The names of the function must not have spaces or special
characters. You can use any name, but picking one that
describes what the function does is good programming
practice since it makes the code easy to read and change
later. So, while you can name the code that decides on the
winner with a function called Icecream, it is best to use
something like findwinner, or to make it more readable,
we can use find_winner or FindWinner. Most Python
programmers use lower case with “_” where needed for
readability, so in this book we will use names like find_
winner for our functions.
We can then use the above function for the user and for the computer.
Add this below the code entered in Step 1:
# step 2 in main program area - roll dice Run the program, and you should have the
# User turn to roll beginning part working.
user_rolls = roll_dice(number_dice)
print('User first roll: ', user_rolls) Sample Run
# Computer's turn to roll Enter number of dice:6
print('Computers turn ') Ready to start? Hit any key to continue
computer_rolls = roll_dice(number_dice) User first roll: [6, 3, 6, 4, 2, 3]
print('Computer first roll: ', computer_rolls) Computers turn
Computer first roll: [5, 6, 4, 4, 3, 5]
The sum function for lists makes finding the sum of a list of
numbers easy. Once we have the total for the computer and
the user, we can use a conditional statement to determine
and print the winner. Add this function below the function
roll_dice.
Now, call this function just after the code in Step 2 in the main
program area using:
Sample Run
Enter number of dice:6
Ready to start? Hit any key to continue
User first roll: [4, 4, 1, 4, 5, 3]
Computers turn
Computer first roll: [1, 5, 2, 6, 2, 4]
Computer total 20
User total 21
User wins
9 4 /: : CR E AT I VE C ODI NG I N PY THON
Step 4: Step 5:
Ask the User to Hold or Roll Again Create a Function that Rerolls
We can now ask the user if they want to hold or roll each of Now that we have the user choices as a string, we can use
the dice after their initial roll. We will use a string for this user that string and the original dice roll, which was stored as a list,
input; the user enters a - to hold and r to roll. We can loop to create a new version of the list. Because we will do this for
through this user input to decide which dice must be rerolled both the user and the computer, we will again use a function.
to recalculate the list. This function needs to know which list is to be modified and
which set of choices is being used to modify the list. We must
We will also use a while loop to do some error checking and
also add import time at the top to add the pause in the game
make sure the user enters the correct number of holds and
here. Add this function toward the top of the file after the
rolls and force them to reenter data if necessary. This error
other functions.
checking is important so the rest of the game works.
Here is the code to be added after the code for the user rolls,
def roll_again(choices, dice_list):
just before the computer rolls.
print('Rolling again ...')
time.sleep(3)
# step 4 - get user choices for i in range(len(choices)):
user_choices = input("Enter - to hold or r to \ if choices[i] == 'r':
roll again :") dice_list[i] = random.randint(1,6)
# check length of user input time.sleep(3)
while len(user_choices) != number_dice:
print('You must enter', number_dice, \
Now that we have a roll again function, call this function after
'choices')
the user makes their choices, as follows:
user_choices = input("Enter - to hold or r \
to roll again :")
# step 5 - roll again based on user choices
roll_again(user_choices, user_rolls)
print('Player new Roll: ', user_rolls)
Run the program. The user can now decide what to hold and
what to reroll, and this determines the next roll.
Sample Run
Enter number of dice:6
Ready to start? Hit any key to continue
User first roll: [5, 3, 1, 1, 4, 5]
Enter - to hold or r to roll again :--rr--
Rolling again ...
Player new Roll: [5, 3, 4, 1, 4, 5]
Computers turn
Computer first roll: [4, 4, 2, 3, 5, 4]
Computer total 22
User total 22
It is a tie!
Strategy 2: Roll only if the number is less than 5; we will need to use an if-else
statement here.
We can implement each strategy using a function that gives the choices as a
string. You can add one or both to the top of your file. A new string is created called
choices and returned from the function.
def computer_strategy1(n):
# create computer choices : roll everything again
print('Computer is thinking ...')
time.sleep(3)
choices = '' # start with an empty list of choices
for i in range(n):
choices = choices + 'r'
return choices
def computer_strategy2(n):
# create computer choices: roll if < 5
print('Computer is thinking ...')
time.sleep(3)
choices = '' # start with an empty list of choices
for i in range(n):
if computer_rolls[i] < 5:
choices = choices + 'r'
else:
choices = choices + '-'
return choices
9 6 / : : CR E AT I VE C ODI NG I N PY THON
Now, just after the computer rolls, call one of these strategies to create a new list of
choices and use it in the roll_again function as follows. Add this code just before
the call to find_winner, which you added in Step 3. Remember, finding the winner is
the last line in the project. Check the complete project code online (see page 138) to
make sure you have added the code in the right order.
# step 6
# decide on what choice - using one of the strategy functions
computer_choices = computer_strategy2(number_dice)
print('Computer Choice: ', computer_choices)
# Computer rolls again using the choices it made
roll_again(computer_choices, computer_rolls)
print('Computer new Roll: ', computer_rolls)
This dice game is yours. You can customize it and make it unique using your
creativity and some Python code.
Experiment 1:
Create Abstract Art
Use random colors, randomly sized circles, and randomly sized Python Turtle Graphics
squares to create abstract art that is different each time you
run the program.
Pseudocode
Import turtle module
Import random module
Create turtle
Create a list of colors using a list like in chapter 2
Do the following 100 times
Move turtle forward random amount between 0
and 360
Start filling color
Set up random fill color
Set size to random amount between 10 and 50
Draw square using square function with size
End filling color of square
Move turtle forward random amount between
20 and 100
Turn turtle a random number between 0 and 360
Start filling color
Set up random fill color
Draw a circle with random amount between
5 and 30
End filling color of circle
Pseudocode
Import turtle module
Import random module
Create turtle
Create a list of colors
Copy the function code from below
Set background color to blue
Do the following 10 times
Set x to a random between -200 and 200
Set y to a random between -200 and 200
Set wall_color to random color from list
Set roof_color to random color from list
Call function house with parameters x, y, wall_color, roof_color
def scramble(w):
# turn string into list letters
letters = list(w)
random.shuffle(letters)
# build scramble_word using letters
scramble_word = ''
for i in letters: python!
scramble_word = scramble_word + i
return scramble_word
Other Experiments
Try to make:
■ A fortune teller
■ Rock, Paper, Scissors
■ A countdown timer that allows the
user to enter the timer amount in
number of seconds and then
counts down from that number
to 0
? ??
h?
p on
yt
BI G I D EA
G RAPHI CAL U SE R
INTERFACES (GU I )
PRESS HERE
window.mainloop()
Because we must connect code to the button, we create a ADDING WIDGETS TAKES
function that runs when the button is clicked. Let’s call this TWO STEPS
function hello_function and place it before the code to
create the widgets. Using a widget such as a button in a GUI program
requires two steps:
# function called when button is clicked 1 Creating the widget by calling the Tkinter function
def hello_function(): and placing it into a variable.
print('Hello, World') # prints to Shell 2 Placing the widget on the screen using Tkinter’s
# change display widget to show this text layout functions. There are different ways to place
display_area.config(text = "Hello, World", \ these on the screen; in this book, we will use the
fg="yellow", bg = "black") basic layout method called pack(). Other more
complex layout methods allow for more control
over the appearance and placement of the widgets.
My First GUI
Now that we have objects, we want to control them in Using Keyboard Controls in Python
different ways. For example, we may want to move an object
We must create a function that will handle the keyboard
when the user clicks on the arrow keys.
inputs and connect or associate (bind) it to the canvas.
Just like we did for the button, we need to create a function to
For example, let’s say the red circle moves to the right and left
run when a key is pressed, and we must associate or connect
with direction from the arrow keys. We can create a function
(bind) this function so that it handles the keyboard inputs.
called move_circle that decides what key has been pressed
Because each keyboard input is considered an event, these
and then changes the x and y amounts in the circle to move it.
functions are called event handlers. The association of this
function to the object is called a binding. We use a canvas To move to the right, we need to change x by a positive
bind function to make this association, or binding, between amount; to move to the left, we move the x position by a
the event handler function and the keyboard. negative amount.
Here is the code for this function. Add this after the
hello_function code in the FirstGUI.py file.
Add this canvas bind code just before the final GUI main loop.
Run the FirstGui.py file and see if the circle moves with the
arrow keys.
! occur in a loop (i.e., the character moves, enemies appear, etc.) but
we also want the screen to be updated and events such as mouse
clicks handled. If the GUI mainloop is the last line of code, it will be
running continuously, not giving us a chance to run any other code.
In order to allow other actions to run in a loop, in addition to the
main GUI event loop, we can schedule them with the GUI module.
window.after(100, move_candy)
EXIT
P ROJ ECT
CR EATI N G YOU R OWN
A RCAD E -STY LE GAME
11 6 / : : CR E AT I VE C ODI NG I N PY THON
The Candy Monster Game
# make window
window = Tk()
window.title('The Candy Monster Game')
Score: 0
# create a canvas to put objects on the screen Level: 1
canvas = Canvas(window, width=400, height=400, bg = 'black')
canvas.pack()
When you run the code at this step, a basic game window with instructions,
similar to the one shown, should appear.
Pseudocode
• Set candy_list, bad candy_list as empty lists
• Set candy_speed to 2
• Set list for candy colors.
• Define function make_candy()
Set x to random position
Set y to 0
Set c to random color
Create canvas oval with x, y, c
Add oval to candy_list
If color is red, add to bad candy_list
Schedules make_candy again
• Define function move_candy()
while there is candy in candy_list
Increase y
If y > edge of screen,
Set y to 0, x to random position
Schedules move_candy again
Here is the code for this step. Add this to GUIGame.py before
the final GUI main event loop and test it. Because we have not
yet scheduled the make_candy and move_candy functions,
nothing will change from the first step.
11 8 /: : CR E AT I VE C ODI NG I N PY THON
# variables and lists needed for managing candy
candy_list = [] # list containing all candy created, empty at start
bad_candy_list = [] # list containing all bad candy created, empty at start
candy_speed = 2 # initial speed of falling candy
candy_color_list = ['red', 'yellow', 'blue', 'green', 'purple', 'pink', \
'white']
While there is item in # end game but after user can see score
window.after(2000, end_game_over)
candy_list
# do not check any other candy, window to be destroyed
If item is hit by character
return
If item is in badcandy_list
# check if it hit any good candy
Set up Game over screen
for candy in candy_list:
Schedule end_game_
if collision(mychar, candy, 30):
over canvas.delete(candy) # remove from canvas
Else # find where in list and remove and update score
Call update_score_level candy_list.remove(candy)
update_score_level()
# schedule check Hits again
window.after(100, check_hits)
Here is the code for this step. Add this code to your file again
FRAMES PER SECOND just before the final GUI main event loop line. Because the
move_character function has not been scheduled, there will
Frames Per Second (FPS) is an indication of how quickly
again be no change when the program is run.
images are updated on the screen. It refers to how many
images (frames) you can see each second. In games,
users can expect 60 frames per second. In this game, to
provide a smooth movement, we will handle the keyboard
input at 60 FPS, which is every 1/60 second (1/60 * 1000
milliseconds = approx. 16 ms). This is the reason the
move_character function is scheduled every 16 ms. You
can experiment with this number and make it higher on
slower computers (e.g., 30 frames per second may also
be acceptable; that computes to 1/30 = 33 ms).
Step 6:
Start the Game!
Schedule End of Instructions and
Functions to Make Candy, Move Candy, # Start game loop by scheduling all the functions
Check Hits, Move Character, and Start the window.after(1000, end_title) # destroy title and instructions
Game Loop window.after(1000, make_candy) # start making candy
Schedule a call to destroy the title and starting window.after(1000, move_candy) # start moving candy
instructions and then schedule a call to all the window.after(1000, check_hits) # check if character hit a candy
functions needed to run the game (make_candy, window.after(1000, move_character) # handle keyboard controls
move_candy, check_hits, and move_character).
Finally, make sure the main game loop is still the
last line of code, so all events are handled.
Experiment 1: Experiment 2:
Make a Password Generator Make a Song Lyrics Generator App
Create an app in which the user clicks on a button to produce Add a graphic user interface to the song lyrics generator project
a randomly generated password. Create the password by from Chapter 1. Create an app in which the user answers some
combining common words, separators, and numbers. questions and clicks on a button to generate a song based on
their entries. Add an image on the button using code as follows
Pseudocode (where musicNotes.gif is an image in the same folder as the
Import Tkinter and random modules Python file. You can get this image from the website listed on
Set up word list and separators list page 138 or make your own image).
make_password function
Get random word from word list button_image = PhotoImage(file="musicNotes.gif")
Add to random item from separator list
Set up GUI window button = Button(window, text = 'Create \
Set up button with make_password callback Song',image = button_image, compound = TOP, \
command = create_song)
Code Hint button.pack()
You may also have to add an empty label to add some space on
the top of the app using:
top_label = Label(window,text='',bg="MediumPurple1")
top_label.pack()
Password Generator
Generate Password
phone$jump64!
A new graphic for the player; for example, you could use the
stick figure gif file available at the website listed on page 138
and change the code to use this image.
Time: 0
player_image = PhotoImage(file="stickfigure.gif")
Level: 1
mychar = canvas.create_image(200,360,image = \
player_image)
spider_image = PhotoImage(file="spider.gif")
yposition = random.randint(1,400)
spider = canvas.create_ \
image(0,yposition,image = spider_image)
# add spider to list
spider_list.append(spider)
Here is the additional code you will need to add so the player
can move in all four directions and cannot escape into the
Time: 9 edges. In the check_input, add the following:
Level: 1
if key == "Up":
move_direction = "Up"
elif key == "Down":
move_direction = "Down"
: : / 129
Expand Your Knowledge of Python with These
Additional Concepts
In addition to learning more ways to use the concepts covered in this
book—lists, conditionals, loops, and so on—you can expand your
knowledge of Python with some concepts that aren’t covered in this book.
Here are a few to look at next.
Dictionaries
These are lists that are not ordered and each item is a key-value pair.
This can be useful in many projects. Here is a simple example of using
a dictionary called scores to keep track of scores of different players.
The key is the name of the player and the value is the score. This is much
easier than using multiple variables or a list.
files
Exception Handling
diction aries
We did some basic error checking in the projects in this book—for
example, in the Chapter 4 dice game project, we checked to make sure
the user entered the correct number of choices. However, there are many
other errors that can occur when a project runs. Errors that are detected
lin on
when the program runs are called exceptions. To make a robust program,
g
nd ti
we want to exit the program gracefully with an error message in all cases.
ha cep
try:
l
sica
phy uting
candy = input('Enter amount of candy ')
p
persons = input(‘Enter number of people ') com
print('Candy per person is', int(candy) // int(persons))
except:
print('Error. Unable to calculate candy amount')
scores = fhandle.read()
c
print(scores)
fhandle.close()
s
advanced
games
Extend Your Python Powers by Using Other Standard
Python Modules
d
an ata There are several modules in the Python Standard Library and are part of the Python
al
ys download. We have already used the following in this book:
is
These standard modules are a good start. You can extend your skills with these
additional modules that are also part of the Python Standard Library:
W H AT’S NE X T? : : / 13 1
Master Programming Tools to Make
Coding Easier
While using IDLE, you must have noticed how it helps you
write Python programs by indenting code as needed, color
coding different parts of Python, and highlighting syntax
errors. Here are some other tools in IDLE that can make
programming even easier.
Debugger
For most of the projects in this book, if you add a small amount
of code at every step as suggested, and then test each step
before going to the next, you probably won’t come across
errors that are too difficult to find or fix. However, to make
coding easier, especially on larger projects, you should learn
to use a debugger. A debugger is a tool that helps test and
find bugs in your code in many ways. For example, it lets you
run the code one line at a time, stop the code running when it
reaches a certain line, and displays the value of the variables in
the program at any point. IDLE has a debugger built in, which
you can find in Python Shell by clicking on Debug On.
W H AT’S NE X T? : : / 13 3
Learn How to Get Help Get Inspired! Check Out How Other
As you do more coding projects on your own, you may have Programmers Are Using Python
questions. There are many ways to get help: Python is used successfully in many applications across the
world. Here are a few examples. See more under success
■ Built-in offline Help pages. When on the Python shell, click
stories on Python.org.
on Help, then click on Python Docs, and you will be able
to access the offline Help pages for Python. You can either ■ 3-D models and 3-D animation. Python integrates with
enter a search term in the search box or read the tutorial or Blender (blender.org), a free and open 3-D animation tool.
Python documentation. Artists and animators use Python to automate tasks and
■ Ask other programmers. Search on the Internet to see if build models and animations in Blender that would not be
someone else posted the same question. A popular site possible without code.
used by programmers to ask questions and share solutions ■ Web applications. Many parts of the Internet—including
is Stack Overflow (stackoverflow.com). Google, YouTube, and Twitter—use Python in some way.
■ Search using Google with Python as your first word. Python programmers continue to build Web applications
Example: “python turtle circle” will provides links to the using Python since it is fast, secure, scalable, and easy to
Python.org documentation and tips on other tutorials or use because of access to many powerful Python frameworks
answers by other Python programmers (often on Stack like Django and Flask.
Overflow). ■ Scientific research. Several scientists use Python to analyze
■ Visit Python.org, which is a good starting point to find other data in their research because of data science packages
Python resources. like NumPy and Matplotlib. There are also Python libraries
available that can handle specific kinds of scientific data; for
example, the Biopython Project provides Python tools for
Expand Your Coding Skills by Learning computational molecular biology.
Object-Oriented Programming
■ Artificial intelligence and machine learning. Python
When you write larger projects and/or work with others, programmers are building intelligent applications that use
you will find it easier to divide and manage your work using machine learning to recognize faces, understand speech,
a different way of programming called object-oriented detect objects, recommend products, find fraud, and much
programming. Instead of focusing on the functions and order more. Python provides access to several powerful machine
of running the program, this approach looks at the project as learning libraries and packages like TensorFlow and scikit-
different objects, where each object contains both how the learn.
data is stored and how it is manipulated. Object-oriented
■ Creating Music. Python can be used in music projects
programming is done in Python using classes.
in different ways. For example, FoxDot provides a rich
environment to create music.
Algorithm: A set of steps listed in order Condition: A Boolean expression that Floats: Decimal numbers like 4.23 are
to do a task—for example, the recipe evaluates to true or false—for example, called floats.
to make a cake or the steps to find the score > 100 can be true or false
average of a list of scores depending on the value of the score at Flowcharts: A visual way of showing an
that point in the game algorithm
Autocomplete: Automatically shows
all the possible ways to complete Conditional: Statement that is run based Function: This is code that has a name
the code—for example, the possible on something being true and false—if and does something and in some
functions for a string. IDLE, and other then else statements are conditionals. cases, takes in information. Python has
IDEs have auto-complete to make standard functions like print, input, etc.
coding easier Conditional loop: A set of instructions
that repeat so long as a condition is FPS: Frames per second, an indication of
Binding: Connecting a function that true—for example, while score < 10 is how fast the screen updates per second
will be run for an event or an object— a conditional loop that runs the block
GIF: A file format for images, used in the
for example, binding the function that of code that follows till the score is less
Chapter 5 examples in this book
moves a character when a key is pressed than 10
to the keyboard object GUI: Graphical user interfaces allow a
Data: Information stored by the
user to interact with the computer using
Boolean: A statement that is either true computer
graphical elements like icons and not
or false—for example, 5 > 3 is true but 3
Debugger: A tool that helps in testing just using text.
> 5 is false
and finding bugs in a program
Global variables: Variables that can be
Bugs: Mistakes in the code that cause
Debugging: Finding and removing a bug accessed by all parts of the program
the program to run differently than
expected or mistake in the code
Imports: A way to give access to the
Event-driven programming: Where functions and definitions in a module
Canvas: Part of the application window
the program or code runs based on an in Python
used to display shapes, images, etc.
event (an action by a user or some other
Integers: Whole numbers like 43 are
Chatbot: A program that talks to program)
known as integers.
humans using text
Event handler: A piece of code that
IDE: Short for integrated development
Code: Set of instructions in a language runs when an event is triggered—for
environment, IDE is an application that
the computer understands to do a example, a function that displays “Hello”
allows users to enter and edit code as
particular task when a button is clicked is the event
well as run it. It provides tools to make
handler for the button click event
Comments: Notes for the programmer coding easier. An example of IDE is IDLE.
to make the code easier to understand Exceptions: Errors that can occur when
Interpreter: Reads code written by user
and change later—in Python, these are a program is running that can cause it
and runs it on the machine
entered by adding a # before them. to stop
Local variables: Variables that can be
changed or used only within a function
: : / 13 7
RE SOU RCES
Python
Download Python for free, get help with Python problems and questions, and learn
more about programming.
www.python.org
www.creativecodinginpython.com
Quarto Knows
View and download the complete code for all of the projects in this book, as well as
images used in the projects, from the publisher’s website.
www.quartoknows.com/page/creativecoding
www.computersforcreativity.com
Thank you to my husband and best friend, Vijay, for encouraging me to write this
book and supporting me at every step. Thanks to my daughter Trisha and my son
Kyle for giving their honest feedback on what is “cool” and fun, and helping me
transition from a computer programmer to teaching middle school kids. Without
them, I would never have been able to design projects for my classes or for this book.
Special thanks to Kyle for his video game expertise. My gratitude to my mother for
teaching me the joy of hard work, and for the wonderful meals over my summer
writing months. Thank you to my friends and extended family for your warm
reception to my book project and your valuable technical advice.
And finally, and most importantly, thanks to the many hundreds of students who
have learned to code in my classes over the years. Your excitement to learn and your
creative projects inspired me to write this book.
: : / 13 9
A B OU T THE AU THOR
: : / 141
reroll function, 95 restaurant bill calculator, 34 reroll, 95
roll function, 93 song lyrics generators, 33, 124 return values with, 87
strategies, 96–97 two-player games, 127 sleep, 76
dictionaries, 130 unscramble word game, 101 square, 84–85, 86
dir function, 132 voting app, 125 sum, 94
dog or cat to human age calculator, 78 turtle graphics, 38, 39
F
E False value, 56–58, 59–60 G
elif statements, 65 Feurzeig, Wally, 38 geometric art project
ELIZA chatbot, 26 files, 131 background color, 48
end characters, 21 find_card_order function, 100 hexagon, 46
end_fill function, 41 floats nested loop, 47
errors calculating, 24 rainbow colors, 48
debugger tool, 132 print function and, 21 repeated hexagon, 47
debugging, 11, 132 flowcharts, 13 white circles, 49
exception handling, 130 forced stops, 43 gif files, 110, 116
runtime errors, 11 frames per second (FPS), 122 global variables, 120
syntax errors, 11, 17 functions Google, 134
event-driven programming, 104 autocomplete feature, 132 green face with circles, 50
event handlers, 104, 111 begin_fill, 41 GUI (graphical user interface)
exception handling, 130 binding, 111 action scheduling, 114
Exit button, 115 calling, 84 canvas objects, 110
experiments choices, 96–97 clickable buttons, 107–109
abstract art, 98 creating, 84–87 entry widget, 113
arcade-style survival game, 126–127 defining, 84, 93 event loops, 104, 105
card game, 100 dir, 132 exiting, 115
changing landscapes, 99 end_fill, 41 gif files, 110
chatbot extension, 81 event handlers, 104, 111 keyboard controls, 111
circle of circles, 52 find_card_order, 100 loops, 114
colored squares, 50 global variables, 120 mouse controls, 112
counting by 2s, 3s, or multiple input, 19 Tkinter module, 104
numbers, 80 int, 25 user data, 113
dog or cat to human age calculator, 78 local variables, 120 widgets, 107
green face with circles, 50 lower( ), 75 window, 106
house with starter code, 51 makeSpiders, 126
Mad Libs, 32
overlapping circles, 52
move_character, 112, 122, 127
H
move_circle, 111
hashtag (#), 22
paint calculator, 35 move_coins, 114
“hello, world” program, 10
password checker, 77 naming, 84, 92
Help pages, 134
password generator, 124 parameters, 84, 86
house with starter code, 51
poem generation, 100 print, 11, 21, 40
quiz game, 79 random, 93, 101
INDE X : : / 143