CREATIVE
CODING IN
PYTHON
225269 - Creative Coding in Python_001-144.indd 1
13/9/18 11:27 AM
225269 - Creative Coding in Python_001-144.indd 1
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:1
CREATIVE
CODING IN
PYTHON
225269 - Creative Coding in Python_001-144.indd 2
13/9/18 11:27 AM
225269 - Creative Coding in Python_001-144.indd 2
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:2
CREATIVE
CODING IN
PYTHONPR30+ OGRAMMING PROJECTS IN ART, GAMES, AND
MORE
SHEENA VAIDYANATHAN
225269 - Creative Coding in Python_001-144.indd 3
13/9/18 11:27 AM
225269 - Creative Coding in Python_001-144.indd 3
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:2
Text
Page:3
© 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.
First Published in 2019 by Quarry Books, an imprint of The Quarto
Group, 100 Cummings Center, Suite 265-D, Beverly, MA 01915,
USA.
T (978) 282-9590 F (978) 283-2742 QuartoKnows.com
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 specialsales@quarto.com 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
Digital edition published in 2019
eISBN: 978-1-63159-582-0
Library of Congress Cataloging-in-Publication Data is available
Design: Landers Miller Design
Illustration: Landers Miller Design
Printed in China
225269 - Creative Coding in Python_001-144.indd 4
13/9/18 11:27 AM
225269 - Creative Coding in Python_001-144.indd 4
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:4
To my father,
who inspired me and made me
believe I could always do more
than I thought was possible.
225269 - Creative Coding in Python_001-144.indd 5
13/9/18 11:27 AM
225269 - Creative Coding in Python_001-144.indd 5
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
T
225269 - Creative Coding in Python
itle:
Page:4
Text
Page:5
CONTENTS
INTRODUCTION
CREATE YOUR
CREATE YOUR OWN
8 What Is Coding?
OWN CHATBOTS
ART MASTERPIECES
8 Why Learn to Code?
1Big Ideas 2Big Ideas
8 Why Python?
16 Storing Data with Variables
38 Turtle Graphics
9 Installing Python
19 Getting Data from the User
40 Loops
10 The First Line of Code
20 Outputting Data on a Screen
44 Storing Data in Lists
11 Python Functions
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
PYTHON
PYTHON
225269 - Creative Coding in Python_001-144.indd 6
13/9/18 11:27 AM
225269 - Creative Coding in Python_001-144.indd 6
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:6
CREATE YOUR OWN
CREATE YOUR OWN
CREATE YOUR OWN
ADVENTURE GAMES
DICE GAMES
APPS AND GAMES
3Big Ideas 4Big Ideas 5Big Ideas
56 Computers Understand True and
84 Creating Your Own Functions
104 Graphical User Interfaces (GUI)
False
88 Computers Can Pick Items at
105 GUI Event Loop
59 Computers Can Combine True
Random
106 GUI Starts with a Window
and False
89 Looping Through a List or a String
107 Clickable Buttons
61 Code Based on Conditions
Project
110 Adding Shapes, Text, and Image
66 Computers Can Loop Based
91 Creating Your Own Dice Game
Objects on the Screen
On a Condition
111 Moving Objects Based on
Next Steps
Project
Keyboard Controls
98 Experiment and Extend
69 Creating an Adventure Game
112 Moving Objects Based on
Mouse Clicks
Next Steps
113 Getting Data from the User
77 Experiment and Extend
114 GUI Can Schedule Code to Run
115 Exiting a GUI Program
Project
116 Creating Your Own
Arcade-Style Game
Next Steps
124 Experiment and Extend
128 What’s Next?
136 Glossary
138 Resources
139 Acknowledgments
140 About the Author
141 Index
225269 - Creative Coding in Python_001-144.indd 7
13/9/18 11:27 AM
225269 - Creative Coding in Python_001-144.indd 7
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:6
Text
Page:7
INTRODUCTION
ENGLISH?
PYTHON?
What Is Coding?
0100101?
Coding is a way to tell a computer what to do. It’s the process of
creating instructions in a language a computer understands.
PYTHON?
Think of coding as “talking” to a computer to solve a problem or to
make something, like a game or an app.
The language we use to talk to the computer is the programming
language, and the set of instructions is called a program, or the
code.
Why Learn to Code?
Coding is a powerful tool. It allows you to express your creativity as
you make your own apps, tools, and games.
Why Python?
Coding allows artists and makers to create art and make There are
hundreds of computer programming languages, wonderful objects
that are only possible with code.
each with its own special purpose, as well as advantages and
disadvantages. Python was created in the late 1980s by Guido
Learning to code helps you understand the digital world van Rossum
and is named after the British comedy television around you. The
world today runs on code, from apps on a show Monty Python’s
Flying Circus. It has nothing to do with smartphone, to online
shopping websites, to automated teller the snake!
machines (ATMs). Because computing has had an impact on virtually
every industry, understanding code will better prepare Python is used
to build applications on the Internet, in you for any kind of job.
scientific research, and to create games, art, movies, and more.
Some famous applications that have been built using Coding involves
problem solving. Writing code requires Python include YouTube,
Google, Instagram, and Spotify.
you to break down a problem into steps, use math and logic Python is
a popular language for several reasons, including: to develop a
solution, and then test and make changes to solve the problem.
Learning to code engages students of all 1 It’s easy to learn and use.
ages and helps them understand math, science, language, 2 It’s
simple and powerful. Just a few lines of code are and more.
needed to do a task.
3 It’s free and open source—which means it enjoys a massive
community of users and developers who
contibute to extending it to a wide variety of applications.
4 It runs anywhere, including Windows, Macs, Linux, and Raspberry
Pi.
8 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 8
13/9/18 11:27 AM
225269 - Creative Coding in Python_001-144.indd 8
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:8
internal ideas
or thoughts/
Used f
ate shape)
ed as needed (its a seper
ther application and spots.
ow can be adjust
or fur
ectional arr
ations and be used f
omment bubbles. Dir
e used in multiple illustr
Chat bubbles or c
ws ar
Windo
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.
When you download Python for free from
python.org, you will get IDLE (Integrated DeveLopment Environment),
which lets you
create, save, interpret, and run your code.
HOW TO USE THIS BOOK
IDLE is an example of an offline integrated
The Python code and pseudocode are shown in a
development environment (IDE) for
different font from the rest of the text. Comments programmers. There
are also a few online
in the code are shown in bold. The output of a
versions of Python. You can use a different
program is shown under the heading Sample Run.
IDE to enter and run your Python code, but
In places where the code does not fit in one line, a \ the screenshots
and examples in this book
is used to show that it wraps.
will show code in the Python IDLE.
Currently, there are two major versions of
this is code # and this is a comment
Python: Python 2 and Python 3. This book
when code runs really long and wraps \
uses Python 3.
into a second line look for a backslash \
at the end of a line
Pseudocode
this is pseudocode
225269 - Creative Coding in Python_001-144.indd 9
13/9/18 11:27 AM
225269 - Creative Coding in Python_001-144.indd 9
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:8
Text
Page:9
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:
>>>
It’s ready for you to enter code.
The Python shell is a place to experiment with snippets of code
because the code runs immediately. Unless you choose to save it,
code in the Python shell is lost once you close IDLE.
You’ll use the Python shell to test and learn the Python code that’s
listed in the Big Ideas sections in this book. For the projects, you’ll
use IDLE to enter code into a file that can be saved, changed, and
run multiple times.
It’s traditional to start learning to program with a classic “hello, world”
program. The goal is just to get the computer to put up those words
on the screen. There are variations on this simple program—from
adding an “!” to using uppercase—but in this book, we use one of the
earliest versions of the phrase, “hello, world“.
In Python, in order to print anything to the screen—that is, to have
text appear on the screen—simply type in the word print with the text
to be printed in quotation marks inside COLORS FOR DIFFERENT
parentheses.
PARTS OF CODE
So to start, in the Python shell at the prompt >>>> , type in the To
make coding easier, IDLE can show different
following:
parts of the code in different colors. For example, the color of “hello,
world”, which is a Python string, print('hello, world')
may be colored green, and the color of “print”,
which is a Python function, may be purple. These
colors and fonts can be customized by the user by
The code is case sensitive—it should be typed in all lowercase
clicking on the IDLE settings.
letters—and the text can be in either single quotes or double quotes.
The computer should reply with “hello, world.” It will then return to the
prompt, waiting for more. Go ahead and type in more print
statements.
10 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 10
13/9/18 11:27 AM
225269 - Creative Coding in Python_001-144.indd 10
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:10
‘HELLO’
PRINT
FUNCTION
HELLO
Information on what to
Prints information on the screen
put on the screen
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.
Sometimes, functions take information, and sometimes, they return
information. For example, the print function takes information on what
to print (the text in quotation marks) and it does just what we expect:
it prints this information to the screen.
You will see an error message in the color set by IDLE—for
Throughout this book, we will use the word function instead example,
red— on the Python shell. As you can see, missing of command or
code as we introduce the Python programming a closing quotation
mark or using an uppercase P in the print language.
command will not work.
When you code in Python, you will be using many functions
Computers are picky! Even a small mistake in the code gives that are
available in the Python language. In Chapter 4, you an error known
as a syntax error. This means the language will learn to make your
own functions.
was not used exactly as it is defined; the error has to do with the
syntax of the language.
Computers Are Picky:
Syntax errors are usually easy to fix, especially because there
Understanding Errors
is either a helpful colored line next to the error or the error Type in the
print code from before again, but this time make message explains
what the computer does not understand.
a mistake—a wrong spelling or a missing quotation mark, for Once all
the syntax errors are fixed, the computer program example. What
happens?
may still not run as expected. This kind of an error is called a runtime
error. It is due to a mistake in the way the code
>>> print('hello, world)
is being used or the way the problem is being solved. These mistakes
are called bugs in the code. Some bugs are easy to SyntaxError:
EOL while scanning string literal
fix, and others can take a long time. Finding and fixing these
>>> Print('hello, world')
bugs is called debugging, and it is a critical part of learning
Traceback (most recent call last):
to code.
File "<pyshell#2>", line 1, in <module> Print('hello, world')
NameError: name 'Print' is not defined
>>>
INTRODUCTION ::/ 11
225269 - Creative Coding in Python_001-144.indd 11
13/9/18 11:27 AM
225269 - Creative Coding in Python_001-144.indd 11
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
T
225269 - Creative Coding in Python
itle:
Page:10
Text
Page:11
Page:
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.
Anytime you create something or solve a problem on the computer,
you must give the computer instructions. These instructions must be
defined clearly in the order in which the computer must follow them.
The set of steps, in order, needed
Pseudocode
to do any task on the computer is called an algorithm.
This is an algorithm written in an informal, simple natural We use
algorithms in everyday life, though we may not call language, such as
English. It often uses indentation to organize them algorithms. For
example, to make a cake, we follow a the instructions.
recipe, a series of steps in order. That recipe is an algorithm.
For example, here is pseudocode for setting the table for four To
solve problems and write good code, computer
people.
programmers plan ahead by writing down the steps—the algorithm—
using one of two methods: pseudocode or
Pseudocode
flowcharts.
Repeat 4 times the following
Go to next empty place on table
Put a bowl at this place
Place a napkin to the left of the bowl
Place a spoon to the right of the bowl
Here is pseudocode for adding ten numbers entered by the user and
printing them to the screen.
Pseudocode
Set total to 0
Repeat 10 times the following
Get number from user
Add number to total
Print the total to the screen
The instructions that are indented are repeated. In the latter example,
the two indented steps—getting a number from the user and adding it
to the total—are repeated 10 times.
The computer then prints the total after the repetition is completed.
12 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 12
13/9/18 11:27 AM
225269 - Creative Coding in Python_001-144.indd 12
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:12
Flowcharts
This is an algorithm written in a visual way using a diagram of boxes
and arrows to show the order of instructions. The box shapes that will
be used in the flowcharts in this book are: Used to start or stop
the program
Used for any instructions
Oval = Start or End
Rectangle = Process
Used for a decision that is
Used for input or
true/false or yes/no
output of information
Diamond = Decision
Parallelogram = Data
Here is an example of a flowchart for deciding if the password
entered by user matches the word “Python“. For simplicity, the start
and stop box shapes are not included in each flowchart in this book.
Ask the user to enter
a password.
Is password equal
Yes
Print to screen that the
to “Python“?
password is correct.
No
Print to screen that
the password is incorrect.
STOP
INTRODUCTION ::/ 13
225269 - Creative Coding in Python_001-144.indd 13
13/9/18 11:27 AM
225269 - Creative Coding in Python_001-144.indd 13
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:12
Text
Page:13
Print
customized
messages
based on user
input.
Create custom
calculators
to do your
math chores.
Use your
creativity
to generate
silly stories
or fun songs.
225269 - Creative Coding in Python_001-144.indd 14
225269 - Creative Coding in Python_001-144.indd 14
13/9/18 11:26 AM
Text
1 13/9/18 11:27 AMTitle: T225269 - Creative Coding in Pythonitle:
Page:14
Print
customized
messages
based on user
input.
Use variables
to store
information
from the user.
CREATE
YOUR OWN
CHATBOTS
Crunch
numbers with
powerful math
functions.
225269 - Creative Coding in Python_001-144.indd 15
13/9/18 11:27 AM
225269 - Creative Coding in Python_001-144.indd 15
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:14
Text
Page:15
BIG IDEA
STORING DATA
WITH VARIABLES
I need to store
0
the player’s
Value of the
score. I will use
variable
a variable.
player_score
Name of the
variable
Computers store information in memory so it can be used in
programs. We call this information data. Sometimes, this data is
provided by the user, and sometimes, it is generated as the program
runs.
The data is stored in variables. Think of a variable as a box in the
computer’s memory. The name on the box is the name of the
variable, and the contents of the box is the data that is stored, known
as the value of the variable. You may have used variables in a math
class, where they also represent data (an unknown number) but do
not directly correspond to a storage location.
For example, a computer program may need to keep track of a
player’s score during a game. This can be stored in a variable called
player_score. The image above shows an initial value of 0 (the score
at the start of the game) being stored in the player_score variable.
225269 - Creative Coding in Python_001-144.indd 16
13/9/18 11:27 AM
225269 - Creative Coding in Python_001-144.indd 16
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:16
WATCH YOUR SPELLING
If you try to access a variable that has not been
assigned any value, you will get an error. So in the Storing Variables
in Python
example on this page, you will get an error if you In Python, a simple
equal sign is used to store data in a misspell the name of the
variable. If you enter
variable.
“Player_Score,” for example, it will show an error because the
variable name that was assigned is
To store the starting score of 0 in a variable with the name
“player_score.” Variable names are case sensitive.
player_score, we use the following:
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!"'
variable must be changed. For example, the program may need to
increase the player’s score value by 1. The computer takes the old
value stored in the variable player_score, adds 1 to YOU CAN ADD
STRINGS
it, and stores it back in player_score. The Python statement that
does this is:
Python strings (text) can be added together to
make longer strings.
player_score = player_score + 1
For example:
To look at the what is stored in the variable at any time, you
>>> name = 'Zoe'
can just type in the variable name in the Python shell. It will
>>> message = 'likes to code'
return the value. So, type in player_score after each line.
>>> name + message
'Zoe likes to code'
>>> player_score = 0
>>> player_score
Adding strings is often used to create new
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.
If the information to be stored is text, single or double quotes are
needed. Text is known as strings in Python.
name = 'Zoe'
CREATE YOUR OWN CHATBOTS ::/ 17
225269 - Creative Coding in Python_001-144.indd 17
13/9/18 11:27 AM
225269 - Creative Coding in Python_001-144.indd 17
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:16
Text
Page:17
CHOOSE A GOOD NAME
The name of the variable should be something that makes it easy to
remember what kind of data it stores. You could use icecream as a
variable name for the player’s score, but player_score is more
descriptive and considered good programming practice. Similarly, you
could use x as the name of the variable for the score, but a longer
name such as
A variable name must follow some rules:
player_score helps you remember how it is
being used.
➔ It cannot have spaces or special characters
For longer names, Python programmers usually use
such as #, @, or the like.
lowercase text with an underscore, “_”, to improve
➔ It cannot start with a number.
readability—for example, player_score. However, in
➔ It cannot be a word used as a Python function,
some cases, programmers may use mixed case, like
for example print.
playerScore.
Let’s take a look at some examples.
alien name = 'Speedy'
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.
>>> alien name = 'Speedy'
SyntaxError: invalid syntax
However, you can use an underscore character or combine What is
your
upper- and lowercases to make longer names.
name?
alienName = 'Speedy'
This works; the variable name has no spaces.
alien_name = 'Speedy'
This also works; the variable name has no spaces.
18 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 18
13/9/18 11:27 AM
225269 - Creative Coding in Python_001-144.indd 18
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:18
BIG IDEA
GETTING DATA
FROM THE USER
Computers get information from users in different ways. A user may
provide information by typing into a keyboard, for example, or by
clicking a mouse.
This data is usually stored in a variable so it can be used later.
This is the name of the variable that will get the information entered
by the user. The information is always a string.
This is the prompt given to the user.
name = input('What is your name?')
Inputting Data in Python
To get information from the user via the keyboard, use the input
function. This function takes the prompt given to the user and returns
the information received from the user into a variable. For example:
Type the following into the Python shell:
name = input('What is your name?')
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.
>>> name = input('What is your name?')
What is your name?Nico
>>> name
'Nico'
Note that the data entered by the user is always a string.
CREATE YOUR OWN CHATBOTS ::/ 19
225269 - Creative Coding in Python_001-144.indd 19
13/9/18 11:27 AM
225269 - Creative Coding in Python_001-144.indd 19
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:18
Text
Page:19
BIG IDEA
OUTPUTTING DATA
ON A SCREEN
hello, world!
Computers must also output information to users. That output could
be graphics on the screen, a sound on the speakers, or simply text
displayed on the screen.
20 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 20
13/9/18 11:27 AM
225269 - Creative Coding in Python_001-144.indd 20
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:20
Outputting Data in Python
To output any information on the screen, use the print END
CHARACTERS
function. We saw this in the Introduction as the first line of By default,
each print function creates a new line Python code. The print
function can be used to print out text, because the output by default
ends with a new
numbers, data stored in a variable, or a combination.
line character. You can change this by adding
For strings:
your own end characters. This is useful when you
have multiple prints and you do not want them on
separate lines. For example, to separate each print print('hello,
world')
output with a comma, you can use:
print("Shelly's friend")
For whole numbers (known as integers in Python): print(23, end=',')
print(23)
For decimal numbers (known as floats in Python): print(3.14)
For data stored in a variable, use the name of the variable:
print(player_score)
For multiple items, separate them with a comma:
print('Your final score is', player_score)
print('Nice to meet you', username, '.')
This example of a print function uses multiple items, including
variables that have been set earlier.
>>> player_score = 100
>>> username = 'Zoe'
>>> print('Your final score is', player_score) Your final score is 100
>>> print('Nice to meet you', username, '.') Nice to meet you Zoe .
CREATE YOUR OWN CHATBOTS ::/ 21
225269 - Creative Coding in Python_001-144.indd 21
13/9/18 11:27 AM
225269 - Creative Coding in Python_001-144.indd 21
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:20
Text
Page:21
BIG IDEA
ADDING COMMENTS
TO YOUR CODE
What does this
code do?
I forget!
I should have added
comments.
Programmers add comments to make
their code easier to read and change later.
Comments are notes written in a natural
language, such as English, to help you
remember how something was done or to
explain it to other programmers who may
use your code. Good programmers always
add comments so they can easily fix or
change their code later.
Adding Comments in Python
Comments are added by using a # symbol followed by the comment.
The # and anything following it is ignored by the Python interpreter
because it is not Python code, just a human readable note. Here are
few examples.
player_score = 0 # initialize score to 0 at start of game
# get name of user before game starts
player_name = input('Enter your name')
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 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 22
13/9/18 11:27 AM
225269 - Creative Coding in Python_001-144.indd 22
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:22
BIG IDEA
DOING MATH
ON THE COMPUTER
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 #.
350 + 427 # addition
987 – 120 # subtraction
34 * 45 # multiplication is denoted by *
57 / 2 # division is denoted by /
57 // 2 # floor division- it discards the fractional part 57 % 2 #
returns the remainder from the division 3 ** 2 # 3 raised to the
power of 2
round(100/3, 2) # round the result to 2 places (100 - 5 * 3) / 5 #
order of operations works as expected 350 + 427 # addition
987 – 120 # subtraction
CREATE YOUR OWN CHATBOTS ::/ 23
225269 - Creative Coding in Python_001-144.indd 23
13/9/18 11:27 AM
225269 - Creative Coding in Python_001-144.indd 23
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:22
Text
Page:23
Your results should look like the following:
>>> 350 + 427
777
>>> 987 - 120
867
>>> 34 * 45
1530
>>> 57 / 2
28.5
>>> 57 // 2
28
>>> 57 % 2
1
>>> 3 ** 2
>>> round(100/3, 2)
33.33
>>> (100 - 5 * 3) / 5
17.0
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
24 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 24
13/9/18 11:27 AM
225269 - Creative Coding in Python_001-144.indd 24
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:24
Why 2 + 2 Is Sometimes 22!
When the user enters information, it is always text, even if it looks like
a number!
Try entering the following into the Python shell.
number = input("Enter a number: ")
number + number
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)
>>> number = input("Enter a number: ") To get the addition to work as
expected, do the following: Enter a number: 2
>>> number + number
'22'
number = input('Enter a number: ')
number = int(number)
number + number
See the output below of the Python shell experiment demonstrating
the above.
>>> number = input("Enter a number: ") Enter a number: 2
>>> number + number
'22'
>>> number
'2'
>>> number = int(number)
>>> number
2
>>> number + number
CREATE YOUR OWN CHATBOTS ::/ 25
225269 - Creative Coding in Python_001-144.indd 25
13/9/18 11:27 AM
225269 - Creative Coding in Python_001-144.indd 25
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:24
Text
Page:25
PROJECT
CREATE YOUR OWN
CHATBOT
Let’s now make a chatbot, a program that appears to talk intelligently
to a human using text. Using the Big Ideas from this chapter, we will
get user input and then respond to the user by putting information on
the screen. Of course, because we are only in Chapter 1 of this book,
this will be a simple chatbot. There will be ideas in subsequent
chapters that you can use to make this chatbot better.
You can change the actual text of the chatbot responses or questions
to customize it.
Note: There is no error checking for this program because it is the
first program in this book. We assume the user will enter the correct
input at each step. In subsequent chapters, you will learn some ways
to check for errors.
THE ELIZA CHATBOT
A chatbot called ELIZA became famous in the
1960s. It illustrated something computer scientists were interested in
—what it meant for a computer
to be intelligent (learn more by reading about the Turing Test). ELIZA
was successful by looking for
patterns and giving related responses. It was able to fool many
people, who thought it had humanlike feelings.
26 /:: CREATIVE CODING WITH PYTHON
225269 - Creative Coding in Python_001-144.indd 26
13/9/18 11:27 AM
225269 - Creative Coding in Python_001-144.indd 26
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:26
Sample Run of the Chatbot
Hello. I am Zyxo 64. I am a chatbot
I like animals and I love to talk about food
What is your name?: Joe
Hello Joe , Nice to meet you
I am not very good at dates. What is the year?: 2019
Yes, I think that is correct. Thanks!
Can you guess my age? - enter a number: 15
Yes you are right. I am 15
I will be 100 in 85 years
That will be the year 2104
I love chocolate and I also like trying out new kinds of food How about
you? What is your favorite food?: pizza
I like pizza too.
How often do you eat pizza?: every day
Interesting.I wonder if that is good for your health My favorite animal
is a giraffe. What is yours?: turtle turtle ! I do not like them.
I wonder if a turtle likes to eat pizza?:
How are you feeling today?: happy
Why are you feeling happy now?
Please tell me: start of a weekend
I understand. Thanks for sharing
It has been a long day
I am too tired to talk. We can chat again later.
Goodbye Joe I liked chatting with you
Step 1: Create a New File for Your Code
So far, we have used the Python shell to try out a few lines of code.
Now that we are making a project that we want to save and edit
easily, we will use a file to enter the code.
1 Click on File > New File.
2 In the new window, enter a comment—a human readable note to
yourself on what this project is about.
3 Click on File > Save As and save it on your computer with the name
Chatbot.py (or any other name; this is just a suggestion).
4 You can run the code by clicking on Run > Run Module.
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.
CREATE YOUR OWN CHATBOTS ::/ 27
225269 - Creative Coding in Python_001-144.indd 27
13/9/18 11:27 AM
225269 - Creative Coding in Python_001-144.indd 27
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:26
Text
Page:27
Step 3:
Showcase Your Math Coding Skills
To show that your chatbot can do math (and you can try out the
Python math functions), ask the user for the current year and a guess
of the chatbot’s age. Then, respond with the year in which the chatbot
will be 100. (You can easily change this to asking the user for their
age and telling them the year they will What is your
I will be 100
be 100.)
name?
in 2104
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
Step 2:
Print I will be 100 in years
Add Code for the Introductions
Convert current year to integer
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) + \
Add the code above to your file and then test it by clicking on nyears)
Run > Run Module.
Add the code above to your file and then test it by clicking on Run >
Run Module.
28 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 28
13/9/18 11:27 AM
225269 - Creative Coding in Python_001-144.indd 28
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:28
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 stored in variables
and reused in the print statements.
I will be 100
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?
CREATE YOUR OWN CHATBOTS ::/ 29
225269 - Creative Coding in Python_001-144.indd 29
13/9/18 11:27 AM
225269 - Creative Coding in Python_001-144.indd 29
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:28
Text
Page:29
Step 5:
Add in a Conversation About Feelings
Add in some more general comments on how the user is feeling,
responding with a generic comment so the chatbot does not have to
make an actual intelligent response based on the user’s input.
# conversation about feelings
feeling = input('How are you feeling today?: ')
print('Why are you feeling', feeling, 'now?')
reason = input('Please tell me: ')
print('I understand. Thanks for sharing')
How you are
Add the code above to your file and then test it by clicking on Run >
Run Module.
feeling?
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
30 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 30
13/9/18 11:27 AM
225269 - Creative Coding in Python_001-144.indd 30
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:30
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.
To make this chatbot more interesting, we may want to add some
unpredictability so it says something different each time it runs. We
will be able to do that after we look at lists and the random module in
Chapter 4.
The chatbot can be improved by adding in a few pauses so that it
seems like it is thinking. You will learn how to do this in Chapter 3.
At the end of Chapter 3 and again at end of Chapter 4, come back to
this project and add code to make your chatbot a bit more intelligent
and useful.
This chatbot is yours; you can customize it and make it more
humanlike by using your creativity and a bit of Python code.
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 GOODBYE
a human’s voice.
CREATE YOUR OWN CHATBOTS ::/ 31
225269 - Creative Coding in Python_001-144.indd 31
13/9/18 11:27 AM
225269 - Creative Coding in Python_001-144.indd 31
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:30
Text
Page:31
NEXT STEPS
EXPERIMENT AND EXTEND
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.
MAD LIBS
Pseudocode
Get nouns, verbs, etc., from the user
Mad Libs is a classic game invented in the 1950s
by Stern and Price. One player asks others for a list Print Mad Lib
sentences using responses
of words, uses them to fill in blanks in a story, and Sample Run
then reads out the usually funny or silly story or Name an object in
this room: table
sentence. Stern and Price’s original Mad Libs book What kind of food
do you like?: pizza
has the following example:
What is your favorite color: green
”(exclamation)! he said (adverb) as he jumped
Enter a name of a zoo animal: giraffe
into his convertible (noun) and drove off with his (adjective) wife.”
The giraffe jumped onto the green table and flew
across the city to eat pizza at his favorite
restaurant.
32 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 32
13/9/18 11:27 AM
225269 - Creative Coding in Python_001-144.indd 32
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:32
Experiment 2:
Song Lyrics Generator
Create a song by using a template and filling in a series of words that
are entered by the user. Get meaningful entries from the user by
giving hints to make sure the words work well in the song.
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!
CREATE YOUR OWN CHATBOTS ::/ 33
225269 - Creative Coding in Python_001-144.indd 33
13/9/18 11:27 AM
225269 - Creative Coding in Python_001-144.indd 33
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:32
Text
Page:33
Experiment 3:
Unit Converter
Create a program that takes information in inches, pounds, and
Fahrenheit (system of measurements used in the United States) and
then converts it to cm, kg, and Celsius (the metric system of
measurement).
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
34 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 34
13/9/18 11:27 AM
225269 - Creative Coding in Python_001-144.indd 34
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:34
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
CREATE YOUR OWN CHATBOTS ::/ 35
225269 - Creative Coding in Python_001-144.indd 35
13/9/18 11:27 AM
225269 - Creative Coding in Python_001-144.indd 35
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:34
Text
Page:35
Use a list
of colors
to create
rainbow art.
Use the
Python turtle
to create
artwork.
Experiment
with shapes,
colors, sizes, and
backgrounds.
225269 - Creative Coding in Python_001-144.indd 36
225269 - Creative Coding in Python_001-144.indd 36
2 13/9/18 11:27 AM13/9/18 11:26 AMTitle: T225269 - Creative
Coding in Python Text
itle:
Page:36
Use a list
Use loops to
of colors
repeat shapes and
to create
create intricate
rainbow art.
geometric
patterns that
are only possible
in code.
CREATE YOUR
OWN ART
MASTERPIECES
Use your
creativity
to make
drawings of
faces, houses,
and more.
225269 - Creative Coding in Python_001-144.indd 37
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 37
13/9/18 11:26 AM
Title:
T
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:36
Text
Page:37
BIG IDEA
TURTLE GRAPHICS
How To Use Turtle Graphics in Python
First, indicate you’ll be using turtle graphics by entering the following
at the start of your code:
import turtle
Using turtle graphics is a fun way to learn Python and create artwork
using code.
This imports, or brings into your program and makes available, a
module in Python that has all the functions for the turtle.
The virtual turtle is a screen cursor depicted by a triangle Modules of
this kind are extensions to Python that have that can draw on the
screen by entering instructions. These functions for a specific
application; in this case, it’s a module instructions are known as
functions (see Introduction for more with functions to use turtle
graphics.
on Python functions) and they include:
In order to do anything with the turtle, you must first create
➜ Moving in all directions
one and assign it to a variable. Think of the variable as a name
➜ Turning in all directions
for the turtle. In the examples in this book, we call our turtle
➜ Changing colors
“shelly,” but you can use any word or name as the variable.
➜ Lifting and putting down the pen
➜ Moving to any part of the screen
shelly = turtle.Turtle()
These functions can be combined to create complex art pieces. For
example, a function to move the turtle forward 100
Type the above two lines of Python into the Python shell. You steps
creates a line in its path. All movements are relative to should see a
new window open. This is the turtle graphics the turtle’s current
position.
window, with a small triangle turtle in the center.
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.
225269 - Creative Coding in Python_001-144.indd 38
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 38
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:38
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')
x = −400, y = −300
x = 400, y = −300
HOW TO FIND YOUR
LOCATION IN TURTLE
You can now control the turtle by giving it instructions (functions).
Enter the GRAPHICS
following Python functions into the Python shell one line at a time to
see what You can always find out where you are by
they do. To make it easier, move the windows so you can see the
Python shell printing out the current coordinates.
window and the turtle graphics window next to each other and watch
the drawing change as you enter each line of code.
print(shelly.xcor(), shelly.ycor())
shelly.forward(100) # moves shelly forward 100 steps Computer
screens can vary, so some of
shelly.right(90) # turns shelly right 90 degrees the examples in the
book may appear a
shelly.left(60) # turns shelly left 60 degrees little different on your
computer. You can
shelly.backward(100) # moves shelly backward 100 steps check
the size of the screen by entering the
shelly.color('red') # makes shelly draw in color red following in the
Python shell:
shelly.circle(10) # makes shelly draw a circle of size 10
shelly.penup() # makes shelly lift pen
shelly.pendown() # makes shelly put the pen down to draw
turtle.screensize()
shelly.reset() # clears screen and goes back to start position
shelly.goto(35, 80) # move to x coordinate 35,y coordinate 80
shelly.hideturtle() # makes shelly not visible on the screen 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.
CREATE YOUR OWN ART MASTERPIECES ::/ 39
225269 - Creative Coding in Python_001-144.indd 39
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 39
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:38
Text
Page:39
BIG IDEA
LOOPS
Python Turtle Graphics
This can be written in pseudocode more simply as:
Pseudocode
repeat 4 times the following:
move 100 steps forward
turn 90 degrees to the left
Note that in the pseudocode, the two instructions that must be
repeated are indented.
How to Use Loops in Python
To repeat something a fixed number of times, we use a for loop. The
code after the statement with a for in it is Let’s take an example of
the turtle drawing a square on the indented to show that it is the block
that repeats (IDLE will screen like the one shown above.
automatically indent this). The Python code for the above
pseudocode is:
Starting at the turtle’s current location, functions must be entered to
move it and turn it at right angles (90 degrees).
Imagine yourself holding a pen and walking on a large sheet of for i in
range (4):
paper to make marks.
shelly.forward(100)
shelly.left(90)
Here are the commands in pseudocode to make a square of size
100:
Add a print function to the above code so that it prints Pseudocode
the variable i and runs it again. Here’s what your code move 100
steps forward
will look like:
turn 90 degrees to the left
move 100 steps forward
for i in range(4):
turn 90 degrees to the left
shelly.forward(100)
move 100 steps forward
shelly.left(90)
turn 90 degrees to the left
print(i) # Add this NEW LINE
move 100 steps forward
turn 90 degrees to the left
The code above is repetitive. Do you see the pattern? There are two
lines that are repeated 4 times, one for each side of the square.
Computers are good at repeating anything. All programming Move
forward
languages have a built-in ability to repeat a set of instructions Turn
left
called a loop.
Repeat this loop 4 times
40 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 40
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 40
13/9/18 11:26 AM
Title:
T
225269 - Creative Coding in Python
Text
itle:
Page:40
This is a variable that’s a counter in the loop. It’s called i in this
example, but you can use any variable name.
This is the number of times this loop will repeat.
The counter starts at 0 and will go up by 1 till it for i in range (4) :
reaches this number.
shelly.forward(100)
Notice the : at the end of this line. Once entered, shelly.left(90)
the next line of code must be indented to show that it’s the code that
repeats.
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.
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.
# 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)
shelly.end_fill() # end filling shape
MORE ABOUT FOR LOOPS
The for loop in the examples in this chapter are simple and are used
to repeat something a fixed number of Python Turtle Graphics
times. So to repeat something 4 times, we use for i in range(4). The
4 in range(4) is the stop value; by default, the start value is 0, so i
takes the values 0, 1, 2, and 3.
➜ It’s possible to change the start value. For example, for i in
range(1,5) will start counting at 1 and stop at 5. So i takes the values
1, 2, 3, and 4.
Move forward
➜ You can also change the steps of the increment.
Turn left
For example, for i in range(1,10,2) will start counting at 1, stop
before 10, and go up in steps of 2.
So i takes the values 1, 3, 5, 7, and 9.
CREATE YOUR OWN ART MASTERPIECES ::/ 41
225269 - Creative Coding in Python_001-144.indd 41
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 41
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:40
Text
Page:41
Python Turtle Graphics
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.
42 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 42
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 42
13/9/18 11:26 AM
Title:
T
225269 - Creative Coding in Python
Text
itle:
Page:42
HOW TO FORCE YOUR CODE
TO STOP RUNNING
If your code is running and you must stop it at any time, you can
move your mouse to the Python shell and enter a Control+C to break
out and force an abrupt stop of the program. This is helpful when you
realize you have made a mistake in the turtle graphics program and
you do not want it to finish, or as we will learn in Chapter 3, you
create an infinite loop and the program is never going to stop.
Move forward
Turn left
Repeat this loop 4 times
Repeat outer loop 6 times
This is called a nested loop, a loop within a loop.
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
Nested Loops in Python
The code for the above is:
# outer loop repeats the square 6 times
for n in range(6):
# inner loop repeats 4 times to make a square
for i in range(4):
shelly.forward(100)
shelly.left(90)
shelly.right(60) # add a turn before the next square 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?
CREATE YOUR OWN ART MASTERPIECES ::/ 43
225269 - Creative Coding in Python_001-144.indd 43
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 43
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:42
Text
Page:43
BIG IDEA
STORING DATA
IN LISTS
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.
I must
remember
all these
colors. I will
make a list!
red
green
blue
item 0 item 1 item 2
in list in list in list
Red een
Gr Blue
COLORS
44 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 44
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 44
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:44
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 colors = ['red', 'green',
'blue']
i, we
would use the following to get the ith color.
Notice how the list is enclosed with square brackets and how each
item, in this case name of color, is separated by a comma.
shelly.color(colors[i])
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])
CREATE YOUR OWN ART MASTERPIECES ::/ 45
225269 - Creative Coding in Python_001-144.indd 45
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 45
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:44
Text
Page:45
PROJECT
CREATING GEOMETRIC ART
Step 1: Make a Hexagon
To begin any turtle project, import the turtle module so Python Turtle
Graphics
you can use the functions. You must also create a turtle (see page
38).
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.
# make a geometric pattern
import turtle
shelly = turtle.Turtle()
Now, let’s modify the pseudocode on how to make a square (see
page 40) so we can make a hexagon. The number of sides is 6, and
the angle to turn is now 60 degrees.
Pseudocode
repeat 6 times the following:
move 100 steps forward
Step 1: hexagon with triangular turtle
turn 60 degrees to the left
To complete Step 1, your Python code should look like this:
# make a geometric pattern
import turtle
shelly = turtle.Turtle()
# repeat 6 times - move forward and turn
for i in range(6) :
shelly.forward(100)
shelly.left(60)
46 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 46
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 46
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:46
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)
Step 1: hexagon with triangular turtle
shelly.right(10) # add a turn
Step 2: nested loop hexagon
CREATE YOUR OWN ART MASTERPIECES ::/ 47
225269 - Creative Coding in Python_001-144.indd 47
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 47
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:46
Text
Page:47
Step 3:
Change the Background;
Add Rainbow Colors
You can make this drawing more interesting by adding colors The
new line of code to add inside the loop for the hexagon is: and a
background. Here’s the code you need to change the background
color:
shelly.color(colors[i])
turtle.bgcolor('black') # turn background black To use different
colors in the drawing, you’ll need to modify the code so the turtle
color is changed inside the loop. Here’s the In the Big Idea section on
page 44, we saw that the computer final code to make this rainbow
pattern:
can store related items in a list—like a list of colors. We also saw how
colors[0] gives the first item in the list, colors[1]
# make a geometric rainbow pattern
give the second item, and so on. We can use the loop to go import
turtle
from item 0 to item 1 and print all the colors in the list. The “i”
# pick order of colors for the hexagon
in the for loop is a counter, which starts at 0 and stops before colors =
['red', 'yellow', 'blue', 'orange', \
6. Using colors[i] gives us the ith item in the list.
'green', 'red']
shelly = turtle.Turtle()
turtle.bgcolor('black') # turn background black
# make 36 hexagons, each 10 degrees apart
Python Turtle Graphics
for n in range(36):
# make hexagon by repeating 6 times
for i in range(6):
shelly.color(colors[i]) # pick color at position i shelly.forward(100)
shelly.left(60)
# add a turn before the next hexagon
shelly.right(10)
Step 3: nested loop hexagon with background and rainbow colors 48
/:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 48
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 48
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:48
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.
This step demonstrates the turtle moving forward and returning by
going backward to its start position. Since there are 36 hexagons,
we’ll draw 36 small circles to match; each time the turtle returns to the
center, it turns 10 degrees: 36 x 10 = 360 degrees, to make a
complete circle around the pattern.
Add the following code to the end of the code in Step 3: Step 4:
nested loop hexagon with background, rainbow colors, and small
white circles
# get ready to draw 36 circles
shelly.penup()
shelly.color('white')
# repeat 36 times to match the 36 hexagons
for i in range(36):
shelly.forward(220)
shelly.pendown()
shelly.circle(5)
shelly.penup()
shelly.backward(220)
shelly.right(10)
# hide turtle to finish the drawing
shelly.hideturtle()
CREATE YOUR OWN ART MASTERPIECES ::/ 49
225269 - Creative Coding in Python_001-144.indd 49
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 49
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:48
Text
Page:49
NEXT STEPS
EXPERIMENT AND EXTEND
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()
50 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 50
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 50
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:50
Experiment 2:
Make a House with Starter Code
Start with the following code, which creates one filled gray Python
Turtle Graphics
square and one filled red triangle:
# 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()
CREATE YOUR OWN ART MASTERPIECES ::/ 51
225269 - Creative Coding in Python_001-144.indd 51
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 51
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:50
Text
Page:51
Experiment 4:
Overlapping Circles
Change the code at the end of Step 2 in this chapter’s project Python
Turtle Graphics
to create a different image. Use the following:
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
52 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 52
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 52
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:52
More to Explore
Can you make one or more of these images? Some are related to the
other challenges in this chapter.
CREATE YOUR OWN ART MASTERPIECES ::/ 53
225269 - Creative Coding in Python_001-144.indd 53
24/9/18 1:08 pm
225269 - Creative Coding in Python_001-144.indd 53
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:52
Text
Page:53
Run code
based on
user’s
choice.
Repeat
tasks until
you are
ready to
quit.
225269 - Creative Coding in Python_001-144.indd 54
225269 - Creative Coding in Python_001-144.indd 54
3 13/9/18 11:28 AM13/9/18 11:26 AMTitle: 225269 - Creative Coding
in Python Text
Title:
Page:54
Use your
creativity and
write your own
interactive
fiction.
Make a
custom quiz
game for
friends and
family.
CREATE
YOUR OWN
ADVENTURE
GAMES
225269 - Creative Coding in Python_001-144.indd 55
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 55
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title: 225269 - Creative Coding in Python
Page:54
Text
Title:
Page:55
BIG IDEA
COMPUTERS UNDERSTAND
TRUE AND FALSE
Python is
simple to
True.
learn.
24 is an
even
True.
number.
312 is
less than
123.
False.
Computers can decide if a statement is true or false. For example,
the statement “24 is an even number” is true, but the statement “25 is
an even number” is false.
Computers use this true and false value to determine which part of
the algorithm (which code) must be executed.
In the Introduction, we saw how decisions can be shown using a
diamond shaped box. In this example, based on whether BOOLEAN
VALUES
the statement “R is equal to 0” is true or false, the algorithm True and
false are known as Boolean values or Booleans, chooses two
different paths and gives two different answers.
after English mathematician George Boole. His invention of Boolean
algebra in the mid 1800s is the basis of modern digital computer
logic.
56 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 56
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 56
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:56
Set n to be the number
entered by the user.
Set R to be the reminder
when n is divided by 2.
True
R is equal to 0.
Print to screen that n is even.
False
Print to screen that n is odd.
STOP
CREATE YOUR OWN ADVENTURE GAMES ::/ 57
225269 - Creative Coding in Python_001-144.indd 57
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 57
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:56
Text
Page:57
Comparing Items in Python
We use two equal signs (see below) to compare two items. The result
is the value True if they are indeed the same or the value False if
they are not.
Try this in the Python shell:
>>> player_score = 0 # this puts 0 into the variable player_score
>>> player_score == 0 # this checks if value in player_score is 0
Because player_score is set to 0, when it is compared with 0, Python
shell returns True.
If the information to be tested is text (a string), the check is case
sensitive.
In the example below, variable name stores “Zoe” with an uppercase
“Z” and it is tested against “zoe” with a lowercase “z”. They are not
the same, the check fails, and Python returns 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.
>>> 5 > 2 # check if 5 is greater than 2
True
>>> 5 < 2 # check if 5 is less than 2
False
BOOLEAN
EXPRESSIONS
>>> 5 != 3 # check if 5 is not equal to 3
True
Any statement that evaluates to
True or False is called a Boolean
>>> choice = 'yes'
expression or a condition.
>>> choice != 'quit' # check if choice is not equal to quit Examples
include:
True
x<2
choice == 'yes'
player_score > 100
58 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 58
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 58
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:58
BIG IDEA
COMPUTERS CAN COMBINE
TRUE AND FALSE
Take an umbrella.
Often, we combine different conditions to create a new It is
condition to help us make our decision. For example, we need
raining.
to check on the condition “It is raining” AND the condition “I have an
umbrella” before we decide to take an umbrella with us when we go
out. We are using the word AND to combine the two conditions—
raining and having an umbrella.
AND
Computers combine Boolean expressions that can be true or false,
using the Boolean operators—AND, OR, NOT—to create new true
and false Boolean expressions.
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.
So, ”take umbrella” is true only if both statements are true.
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.
So, “take jacket” is true if any one of the statements or both
statements are true.
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.
So ”take jacket” is true if “it is warm outside” is false; it is the opposite.
CREATE YOUR OWN ADVENTURE GAMES ::/ 59
225269 - Creative Coding in Python_001-144.indd 59
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 59
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:58
Text
Page:59
Using Operators in Python
We can use the AND operator (and) to combine two Booleans.
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.
>>> lives > 0 and game_time > 0
# game proceeds only if there are lives and time left We can also
use the OR operator (or) to combine two Booleans.
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.
>>> lives == 0 or game_time == 0
# game stops if no lives left or there is no time left We use the
NOT operator (!) to get the opposite value.
>>> choice != 'quit' # user does not want to quit
>>> not(player_score == 0) # this true if player_score is not a 0
TRUE WITH A CAPITAL T
True and False are recognized in Python as Boolean values, and they
are case sensitive. Try the following in the Python shell:
>>> True and True
>>> true or true
The second expression gives an error because “true” is not a
Boolean; it is considered a variable that has not been assigned any
value yet.
60 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 60
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 60
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:60
BIG IDEA
CODE BASED ON
CONDITIONS
True . . . If block of c
We make decisions and execute different actions based on ode
something being true or false.
ode
For example, consider a decision you may make at breakfast time: If
there are eggs in the refrigerator and I have time False . . . Else block
of c
(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.
Similarly, computers execute code based on a condition, a Boolean
expression that evaluates to true or false. If the condition evaluates to
true, one set of code statements (the if block of code) is executed;
else, the other part (the else block of code) is executed. This kind of
statement is called a conditional or an if-else statement.
Using a flowchart, the breakfast example can be shown as follows:
Make
an
egg?
Make
True
Make fried eggs. Make toast.
instant
I have eggs in the refrigerator
Eat eggs and toast for breakfast.
oatmeal?
AND I have time.
False
Take a
granola
bar to
Pick up granola bar from
go?
kitchen shelf. Put granola bar
in bag to eat later.
CREATE YOUR OWN ADVENTURE GAMES ::/ 61
225269 - Creative Coding in Python_001-144.indd 61
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 61
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:60
Text
Page:61
Using Conditional Statements in Python To execute code based
on a condition, we use an if statement, Here is an example that asks
the user for the day of the week also known as a conditional
statement. If the condition is true, and depending on the day, sets an
alarm variable and prints a it executes the set of statements in the if
section; otherwise, message. In the example below, the user entered
the day as it executes the statements in the else section. The else
part is Monday, so it printed the message, “Get up and get ready for
optional.
work.”
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':
>>> raining = True
alarm = 'OFF'
>>> if raining:
print('It is a weekend - sleep in!')
print('It is wet outside')
else:
print('Wear rain boots')
alarm = 'ON'
print('Take an umbrella')
print('Get up and get ready for work')
Get up and get ready for work
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 as the block of code that
must be run.
if
else
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.
225269 - Creative Coding in Python_001-144.indd 62
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 62
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:62
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.
I have eggs in the
True
Make fried eggs. Make toast.
refrigerator AND
Eat eggs and toast for breakfast.
I have time.
False
True
Put instant oatmeal and water in
I have instant oatmeal
a bowl. Microwave. Eat oatmeal.
AND I have a little bit
of time.
False
Pick up granola bar from
kitchen shelf. Put granola bar in
bag to eat later.
This is any expression that is a Boolean and evaluates to either True
or False.
The : is important, and it separates the condition if <condition> :
from the block of code that will run when this
condition is true. Python expects the block to be
<code to be executed when condition is true> indented and IDLE will
automatically indent the next else :
line after you enter : .
<code to be executed when condition is false> The : is important
because it separates the block of code that will run when this
condition is false.
Python expects the block to be indented and IDLE will automatically
indent the next line after you enter : .
225269 - Creative Coding in Python_001-144.indd 63
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 63
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:62
Text
Page:63
Nested Conditionals
Here is a simple number guessing game that you can try by creating
a new file called guessNumber.py and entering the following code. In
this example, there is an if-else statement inside the else part of the
code; if the number entered by the user is not equal to the secret
number, then it checks to see if it is lower or higher to give the user
the appropriate message.
# Guess the number game
secret_number = 87
n = input('Guess the secret number between 1 and 100 ') n = int(n) #
convert user input into an integer if n == secret_number:
print('You got it!')
else:
# not equal to secret_number so check if lower or higher if n >
secret_number:
print('Your guess was too high')
else:
print('Your guess was too low')
print('Thanks for playing') # this is done at end in all cases Guess
the
number.
83?
64 /:: CREATIVE CODING WITH PYTHON
225269 - Creative Coding in Python_001-144.indd 64
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 64
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:64
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.
# day of the week program
day = input('Enter day of the week :')
if day == 'monday' or day == 'wednesday':
alarm = '7.30am'
carpool = True
coding_class = True
Monday X X
gym = False
Tuesday X
elif day == 'tuesday' or day == 'thursday':
Wednesday X
alarm = '7.30am'
Thursday X X
carpool = False
Friday X X X
coding_class = False
Saturday X
gym = True
Sunday X
elif day == 'friday':
alarm = '6.30am'
carpool = True
coding_class = False
gym = False
else:
alarm = 'OFF'
carpool = False
coding_class = False
gym = True
print(alarm, carpool, coding_class, gym)
BOOLEAN OPERATORS REQUIRE
BOOLEAN VALUES
A common mistake when using Boolean operators is not using them
with Boolean values.
day == 'monday' or 'wednesday' is incorrect because the first part,
day == 'monday' is Boolean, but 'wednesday' is a string, not a
Boolean. Each part must be a Boolean. The correct way to do this is:
day == 'monday' or day == 'wednesday'
CREATE YOUR OWN ADVENTURE GAMES ::/ 65
225269 - Creative Coding in Python_001-144.indd 65
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 65
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:64
Text
Page:65
BIG IDEA
COMPUTERS CAN LOOP
BASED ON A CONDITION
Too
high
Computers can loop (run a set of code repeatedly) as long as a
condition remains true. This is called a conditional loop.
Unlike the for loop in Chapter 2, which is used to run code a fixed
number of times, this kind of loop is used when the exact number of
times to run the code is not known. It runs until Too
some condition remains true.
low
For example, in the guessing game on page 64, we may want to keep
playing the game so long as the user has not guessed the number.
Instead of specifying a fixed number of tries (a 83?
fixed number of times to run the loop), we will let the code Guess the
run until they guess the number. We use these kind of loops
number?
when we do not know how many times it must be repeated.
In this example, we do not know how many turns it will take 27? the
user to guess the number.
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.
Using a Conditional Loop in Python
In Python, conditional loops can be created using the while
statement.
Here is the code for the flowchart. Enter it in a new file called
guessNumberVersion2.py.
This is any expression that is a Boolean and
evaluates to either True or False.
The : is important because it separates the while <condition> :
condition from the block of code that will run when this condition is
true. Python expects the block to
<code to be executed when condition is true> be indented and IDLE
will automatically indent the next line after you enter : .
66 /:: CREATIVE CODING WITH PYTHON
225269 - Creative Coding in Python_001-144.indd 66
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 66
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:66
Set secret_number
Here is a flowchart for this modified version of the game.
Set n = user’s guess
True
n equals secret_number?
Print “done”
STOP
False
True
n > secret_number?
Print “too high”
False
Print “too low”
Set n = user’s new guess
# Guess the number game version 2
SAMPLE RUN
secret_number = 87
Guess the secret number between
n = input('Guess the secret number between 1 and 100 ') 1 and 100
89
n = int(n) # convert user input into an integer Your guess was too
high
Make another guess between 1
while not (n == secret_number):
and 100 12
# not equal to secret_number so check if lower or higher Your
guess was too low
if n > secret_number:
Make another guess between 1
print('Your guess was too high')
and 100 29
else:
Your guess was too low
print('Your guess was too low')
Make another guess between 1
# ask user for another guess
and 100 99
n = input('Make another guess between 1 and 100 ') Your guess was
too high
n = int(n) # convert user input into an integer Make another guess
between 1
print('You got it !')
and 100 87
You got it !
CREATE YOUR OWN ADVENTURE GAMES ::/ 67
225269 - Creative Coding in Python_001-144.indd 67
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 67
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:66
Text
Page:67
Forcing User Input with While Loops
A while loop can be used to force a certain input from the user. For
example, if the only choices that should be entered are “yes” and
“no”, the while loop can run code to keep asking the user to enter
input again if their input is something else.
# while loop checks for specific input - a yes or no choice =
input('Enter yes or no :')
while not(choice == 'yes' or choice == 'no'):
choice = input('Please enter yes or no :')
# end of while loop, code entered here runs when input is valid
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
In the guessing game example, we set up the initial condition as the
first user guess. The condition we test is if the guess is equal to the
secret number. The code we run each time is printing too low or too
high, and finally, the change condition is allowing the user to enter a
new number, so that the condition to be checked will change.
What happens if the condition is not changed, if we do not give the
user another chance to enter a guess?
68 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 68
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 68
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:68
PROJECT
CREATING AN
ADVENTURE GAME
This is an example of the popular
category of text-based adventure games,
also known as interactive fiction. The
user makes choices and moves through
the story, collecting items or answering
questions. It is a good opportunity for
using conditionals (if statements) and
nested conditionals.
Storyline: The user is hiking in the moun-
tains and hears a sound. She gets lost and SAMPLE RUN OF THE
GAME
has to make decisions so that she can get
Welcome to the Santa Cruz Mountain Adventure Game
back safely and win the game.
*************************************************
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 -
choices, and characters. Creating a
map(m), flashlight(f), chocolate(c), rope(r), or stick(s) : more complex
adventure game based
What do you choose?: c
on this idea is a good way to practice
You hear a humming sound.
your Python coding skills.
Do you follow the sound? Enter y or n: n
Good idea. You are not taking risks.
Using a flowchart makes this project
You start walking back to the starting point.
easier to plan and code. You will add to
You realize you are LOST!
the project based on the flowchart at
The sound is behind you and is getting louder. You panic!
each step. Run the code after each step
Do you start running (r) or stop to make a call (c)?: c to make sure it
works.
The call does not go through.
Do you want to run (r) or try calling again (c)?: c The call does not go
through.
Do you want to run (r) or try calling again (c)?: r ERROR CHECKING
You are running fast. The sound gets really loud.
A woman on an electric scooter comes up behind you.
Note that there is no error checking
She asks, "Name my favorite computer programming language.":
PYTHON
in the first few steps. We assume
She says, "Yes, Python is my favorite programming language.
the user will enter the correct input
If you have some chocolate, I can help you."
at each step of the game. This
Luckily, you did choose correctly!
simplifies the code because we do
You give her the chocolate.
not have to check each input for
She helps you get home.
correctness. In Step 4, you can see
CONGRATULATIONS! You got out safely. You won the game.
suggestions on some ways to check
for errors.
CREATE YOUR OWN ADVENTURE GAMES ::/ 69
225269 - Creative Coding in Python_001-144.indd 69
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 69
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:68
Text
Page:69
Step 1:
Add an Introduction and Have the User
Make a Choice
Start a new file for this project called, for example,
AdventureGame.py. Add an introduction to the game using
print statements and get the user to pick an item to take on the
adventure by using an input.
Then, present the first choice and go different ways using an if
statement. See the flowchart below
for this step.
Here is the code for this step.
Print introduction
# 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! ') 70
/:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 70
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 70
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:70
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.
See the flowchart below for this while loop.
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! ') Add
the following code:
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)?: ') Here
is the code for this step.
print('You are running fast. The sound gets really loud')
# adventure game
print('Welcome to the Santa Cruz Mountain Adventure Game!')
print('*************************************************') print('You are
visiting Santa Cruz, California.')
Action? Enter run (r)
print('You go on an evening hike alone in the mountains.') or call (c).
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: ') No
Action = c?
Print-you start running.
if choice1 == 'y':
Sound gets louder.
print('You keep moving closer to the sound.')
print('The sound suddenly stops.')
Yes
print('You are now LOST! ... ')
print('You try to call on your phone, but there is no signal!') else:
Print-call failed message.
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! ')
CREATE YOUR OWN ADVENTURE GAMES ::/ 71
225269 - Creative Coding in Python_001-144.indd 71
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 71
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:70
Text
Page:71
Which
way?
Which
way?
Which
way?
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.
This is an example of nested if statements. We are checking a
condition inside the first if statement. Instead of just an if-else, we will
use the if-elif-else (multiple conditions). Here is the flowchart for that
part of the story.
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.
72 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 72
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 72
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:72
After the if part in Step 1, that is, right after this line of code: print('You
try to call on your phone, there is no signal!') Add the following 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.') STOP
You win.
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.--') CREATE YOUR OWN
ADVENTURE GAMES ::/ 73
225269 - Creative Coding in Python_001-144.indd 73
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 73
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:72
Text
Page:73
Sound gets louder,
STOP
woman appears.
You win.
What is my favorite
programming language?
Woman helps you.
Yes
Step 4:
Yes
Make the User Answer a Question
Python?
Chocolate
to Determine the Next Action
Add a puzzle or quiz question that the user must answer correctly No
No
to determine the next action. Add this after the user is running fast,
after the code in Step 2.
STOP
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') Add
this code:
print('A woman on an electric scooter comes up behind you.') answer
= input('She says, "Name my favorite computer programming
language.": ') if answer == 'python':
print('She says, "Yes, Python is my favorite programming language."')
print('"If you have some chocolate, I can help you."') if item == 'c':
print('Luckily you did choose correctly!')
print('You give her the chocolate.')
print('She helps you get home.')
print('CONGRATULATIONS! You got out safely. You won the game.')
else:
print('You should have chosen that chocolate!')
print('She rides away, leaving you alone and lost.') print('You lost the
game.')
else:
print('She did not like your answer.')
print('She rides away, leaving you lost!')
print('You lost the game.')
74 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 74
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 74
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:74
PYTHON?
STOP
pyt
You win.
ho
Step 5:
n?
Improve User Input and Add Error Checking
Python?
We can make some improvements to the game now that we have
something Woman helps you.
working.
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.”
Chocolate
One way to do this is to check for each possible user input. So we
can change this part:
if answer == 'python':
to:
if answer == 'python' or answer == 'Python' or answer == 'PYTHON':
CODING TIP
This will work but seems repetitive. Instead, you can convert the
user’s response to The best way to work on any coding
lowercase and just check that. Luckily, this is easy to do in Python.
You can use the project is to make incremental
lower method on any string to convert it to lowercase, as follows:
steps; do not write in too much
code at a time. Once a piece is
working, you can always go back
if answer.lower() == 'python':
and improve something or change it
to run better.
We can also add some basic error checking. Using what we learned
in the previous section, we can add a while loop and force the user to
retry if they do not type in MANIPULATING
the correct answer. When we ask the user to make the first choice
between y and n, we can check that they actually type one of them.
The Boolean condition (choice1
TEXT
== 'y' or choice1 == 'n') must be true if the input is valid. We will
retry if this In addition to lower() function,
condition is not true, so we use not (choice1 == 'y' or choice1 ==
'n') at there are several other powerful
the start of the while loop. The new code for this section is as follows:
ways to manipulate text (strings)
in Python. One way to find them
choice1 = input('Do you follow the sound? Enter y or n: ') is to type in
the string and a ‘.’ and
while not (choice1 == 'y' or choice1 == 'n'):
wait in the Python IDLE editor;
choice1 = input('That is an invalid input. Enter y or n: ') it autofills to
tell you what is
possible. Take a look at the What’s
Next section at the end of this
book for more information on how
to do this.
CREATE YOUR OWN ADVENTURE GAMES ::/ 75
225269 - Creative Coding in Python_001-144.indd 75
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 75
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:74
Text
Page:75
Step 7:
Add More to Make
the Game Better
Step 6:
There are many ways you can make this
game much better. Here are a few:
Add Pauses in the Story
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
and no.
time.sleep(3)
7 Add an energy variable that changes as
you move through various levels.
Try changing the code in Step 1 to:
8 Add more pauses, using the sleep
function, to make the game run better.
if choice1 == 'y':
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.
All you need is your creativity and some
more Python code!
76 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 76
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 76
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:76
NEXT STEPS
EXPERIMENT AND EXTEND
Experiment 1:
Password Checker
Create a password checking program that lets the user keep trying
until they get it correct. Use any password to test your program.
Pseudocode
Get password from user
While password is not correct
Print incorrect
Get password from user
Print Correct
Sample Run
Enter the password :python17
Sorry that is incorrect
Enter password again :lab28!
Sorry that is incorrect
Enter password again :secret987
Success: You are correct
CREATE YOUR OWN ADVENTURE GAMES ::/ 77
225269 - Creative Coding in Python_001-144.indd 77
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 77
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
T
225269 - Creative Coding in Python
itle:
Page:76
Text
Page:77
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.
So a 6 year old dog would be 40 in human years.
Cats:
■ 1st cat year = 15 human years
■ 2nd cat year = 24 human years
■ Add four years for every year after that.
So a 4 year old cat would be 32 in human years.
Using this information, write a program that asks the user if the
animal is a dog or cat, along with its current age, and prints out age of
the animal in human years.
Sample Run
Enter dog or cat: cat
Enter age of animal: 4
Human age of cat is 32
78 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 78
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 78
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:78
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.
Sample Run with Two Questions
What is the capital of Peru: Lima
You are correct
Which is the longest river: Nile
You are incorrect
The correct answer is Amazon
Your score is 1
CREATE YOUR OWN ADVENTURE GAMES ::/ 79
225269 - Creative Coding in Python_001-144.indd 79
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 79
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:78
Text
Page:79
Experiment 4:
Count by 2s, 3s, or
Multiples of Any Number
Print numbers starting from 0 in multiples of the number the user
selects. For example, if the user wants to count by 7s, then print 0, 7,
14, 21, 28, and so on until the user enters quit.
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:
Enter return to continue or q to quit:
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
80 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 80
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 80
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:80
Experiment 5:
Extend the Chatbot
Use conditional statements to make the chatbot from Chapter 1
better.
For example, reply with an appropriate response to how the user is
feeling, depending on whether the user is happy, sad, bored, or the
like.
Sample Run
How are you feeling today?: sad
Sorry to hear you are sad. Why are you feeling
this way? :
CREATE YOUR OWN ADVENTURE GAMES ::/ 81
225269 - Creative Coding in Python_001-144.indd 81
13/9/18 11:28 AM
225269 - Creative Coding in Python_001-144.indd 81
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:80
Text
Page:81
Build smart
strategies
for your
Generate
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.
225269 - Creative Coding in Python_001-144.indd 82
225269 - Creative Coding in Python_001-144.indd 82
13/9/18 11:26 AM
Text
4 13/9/18 12:08 PMTitle: T225269 - Creative Coding in Pythonitle:
Page:82
Build your own
functions to
reuse code in
powerful ways.
CREATE YOUR
OWN DICE
GAMES
Challenge
your friends
to your
custom word
games.
225269 - Creative Coding in Python_001-144.indd 83
13/9/18 12:08 PM
225269 - Creative Coding in Python_001-144.indd 83
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:82
Text
Page:83
BIG IDEA
CREATING
YOUR OWN FUNCTIONS
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 A
simple example is the code we wrote in Chapter 2 for auto-indent any
line after entering : .
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 computer how to
respond to the word square by making a for i in range(4):
square.
shelly.forward(100)
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 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 84
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 84
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:84
This is the name of the function.
This is where information is given to the function.
There can be 0 or more parameters. If there is more than 1
parameter, they are separated by commas.
def functionName ( parameters ) :
The : is important; it separates the block of code
<code to be executed when function is called> that must be indented
below it and is the code for the function. IDLE will auto-indent any line
after entering this : .
Try this by creating a new file called myfunctions1.py and the code
below:
# my functions
import turtle
shelly = turtle.Turtle()
# square function creates square of size 100
def square():
for i in range(4):
shelly.forward(100) # each side of square is 100
shelly.left(90)
square() # calling the function
shelly.forward(100) # move forward
square() # make another square by calling the function
shelly.forward(100) # move forward
square() # make another square by calling the function again 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
is more organized and easier to read, and we can reuse the code for
the square easily multiple times.
CREATE YOUR OWN DICE GAMES ::/ 85
225269 - Creative Coding in Python_001-144.indd 85
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 85
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:84
Text
Page:85
Functions with Parameters
In the square function on the last page, we had no parameters;
Python Turtle Graphics
it did not take any information. This always makes a square of size
100. We can change that by adding a size as a parameter so that it is
more flexible and can make squares of any size.
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.
Parameters make the square function more flexible and powerful
because the same code can be used in many ways.
# my functions with parameters
import turtle
shelly = turtle.Turtle()
# square function creates square of ANY size
def square(s):
for i in range(4):
shelly.forward(s) # each side of square is variable s shelly.left(90)
square(100) # calling the function for square of size 100
shelly.forward(100) # move forward
square(200) # calling the function for square of size 200
shelly.forward(100) # move forward
square(300) # calling the function for square of size 300
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)
86 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 86
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 86
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:86
Functions with Return Values
Sometimes, a function returns something that the rest of the code can
use.
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:
# functions that return values
# define a function that finds average of a list def average(myList):
total = sum(myList) # use the sum function in Python lists average
= total / len(myList) # len gives number of items return average
# use the function
scores = [7, 23, 56, 89]
averageScore = average(scores)
print('The average of the scores is', averageScore) 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.
suits = ['Clubs', 'Hearts', 'Diamonds', 'Spades']
cardno = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', \
'K', 'A']
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)
CREATE YOUR OWN DICE GAMES ::/ 87
225269 - Creative Coding in Python_001-144.indd 87
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 87
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:86
Text
Page:87
BIG IDEA
COMPUTERS CAN PICK ITEMS
AT RANDOM
When we create games, we often want to add an element of chance.
Instead of deciding on an item, we want the computer to pick
something at random.
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.
In the case of the adventure game in Chapter 3, we may want a
variation in which the computer picks which is the lucky item that is
needed in the last stage of the game. Instead of deciding on using
“chocolate” as the item needed at the final stage, let the computer
pick an item at random so that the game ends differently with each
run.
Think of this as a computer picking items from a bag at random.
Picking Items at Random in Python
In Python, we can select random items by using the random module.
So on top of your code, use:
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).
So, to pick a number between 1 and 100, use:
random.randint(1,100)
To select an item at random from a list called listname, 5
use random.choice(listname).
5 >>> fruit = ['apples', 'cherries', 'bananas', 'strawberries']
>>> random.choice(fruit)
88 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 88
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 88
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:88
BIG IDEA
LOOPING THROUGH
A LIST OR A STRING
Computers are very good at looping—repeating things again and
again either a fixed number of times, while a condition is true, or for
each item in a list or string.
For any list of items (for example, names, phone numbers, or scores),
we often want to create a loop in which the computer goes through
the list and executes a fixed amount of code for each item.
We can think of text as a list of characters, and we can loop through
the text and do something with each character. This is especially
useful in manipulating information inputted by the hello
hello
user or in a text-based project such as a word game.
Trisha
Kyle
hello
Nico
KYLE
NICO
TRISHA
NAMES
CREATE YOUR OWN DICE GAMES ::/ 89
225269 - Creative Coding in Python_001-144.indd 89
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 89
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
T
225269 - Creative Coding in Python
itle:
Page:88
Text
Page:89
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.
The : is important; it separates the block of code that will run for the
loop, and this must be indented.
for j in <nameoflist> :
IDLE will auto-indent this after the : is entered.
<code to be executed for each j item in list> Because the variable j
gets the value of each item in the list, it can be used here in the code.
Looping Through a List or String in Python
In Chapter 2, we saw how Python can loop through a fixed The
variable i is equal to each item in the list in turn. So i =
number of times. For example, to say hello ten times, alex, then i =
bob, and so on as it executes the code. Try the we can use:
code in the Python shell. It should give the following: for i in
range(10):
Welcome to the class alex
print('Hello')
Welcome to the class bob
Welcome to the class sue
The range (10) causes Python to create an internal list of Welcome
to the class dave
numbers from 0 to 9 that it uses to loop through.
Welcome to the class emily
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.
>>> names = ['alex', 'bob', 'sue', 'dave', 'emily']
>>> s = 'Python'
>>> for i in names:
>>> for i in s:
print('Welcome to the class', i)
print(i)
90 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 90
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 90
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:90
PROJECT
CREATING YOUR OWN
DICE GAME
Let us make a dice game in which the computer and the user take
turns rolling a fixed number of dice to see who can get the highest
total. Each gets one chance to roll again and can decide which of the
dice rolled must be held or rerolled.
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.
We will look at how the computer could use different strategies to
decide on what to hold and what to roll.
We can also change the objective of the game from highest total to
lowest total or the highest number of 6s rolled or something else.
Because the computer and the user make similar moves, we will use
functions where possible to reuse the code.
SAMPLE RUN OF THE DICE GAME
Enter number of dice:6
Ready to start? Hit any key to continue
User first roll: [4, 6, 5, 6, 2, 5]
ARTIFICIAL INTELLIGENCE
Enter - to hold or r to roll again :----r-
Rolling again ...
IN GAMES
User new Roll: [4, 6, 5, 6, 3, 5]
Many games use some amount of artificial intelligence Computers
turn
(AI), usually to turn the computer into an interesting Computer first
roll: [1, 6, 5, 5, 4, 6]
opponent to the human player. The amount of artificial Computer is
thinking ...
intelligence varies based on the complexity of the game.
Computer Choice: r---r-
It could be as simple as programming a computer to Rolling again ...
play a dice game like the one in this chapter or as com-Computer
new Roll: [5, 6, 5, 5, 6, 6]
plicated as creating a program to play a complex game Computer
total 33
such as chess with a human champion. Some games
User total 29
have AI that uses strategies that are created based on Computer
wins
data gathered from previous runs of the game—this is the machine-
learning part of AI.
CREATE YOUR OWN DICE GAMES ::/ 91
225269 - Creative Coding in Python_001-144.indd 91
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 91
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:90
Text
Page:91
Step 1:
Have the User Select the Number of Dice
Create a new file called Dicegame.py and add a comment on top.
Ask the user for the number of dice to be used in this game and store
it in a variable called number_dice. Before starting the game, ask the
user to hit a key when they are ready for the game.
# dice game
# step1 in main program area - start game
number_dice = input('Enter number of dice:')
number_dice = int(number_dice)
ready = input('Ready to start? Hit any key to continue') Run the above
program and make sure it works.
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.
92 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 92
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 92
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:92
Step 2:
Create a Function to Roll the Dice
The dice rolled will be represented by a list of numbers, where each
number is the value of the dice. For example, if there are 6 dice, a
dice roll DEFINE YOUR
of 3, 4, 5, 6, 6, 1 can be represented by the list [3,4,5,6,6,1]. For the
number FUNCTIONS BEFORE
of dice needed, we must use random.randint(1,6) to generate a
number between 1 and 6 and add it to the list. We can start with an
empty YOU USE THEM
list as a variable called dice (the empty list is indicated by [], which is
the Functions must be defined before they are
open [ followed by the closed ]) and then add to this list by appending
used. It is best to define these at the top of
random numbers using dice.append(random.randint(1,6)). We will
the file and clearly mark the main code area
do this inside a for loop as many times as the number of dice in the
game that uses these function with a comment
(using the previous variable number_dice).
below.
In order to use randomness in the game, we must of course import
the Also import of any modules must be done
random module so we can use the random function.
before anything else and is best done on top.
To create a list for the computer or the user, we will use a function
that So any program file will be of the type:
takes the number of dice as a parameter and then returns this dice
list.
This is the code to be added to the top of the file (it will be above the
code import …
in Step 1).
def function1():
...
import random
def function2():
def roll_dice(n):
...
dice = [] # start with empty list of dice
# main program code
# add random numbers between 1 to 6 to the list for i in range(n):
dice.append(random.randint(1,6))
return dice
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]
CREATE YOUR OWN DICE GAMES ::/ 93
225269 - Creative Coding in Python_001-144.indd 93
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 93
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:92
Text
Page:93
Step 3:
Decide the Winner
Before adding the rest of the game, let’s write the function that
decides on the winner. This function takes the lists of dice for the user
and the computer, gets the sum of the each, and prints out who wins
or if it is a tie.
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.
def find_winner(cdice_list, udice_list):
computer_total = sum(cdice_list)
user_total = sum(udice_list)
print('Computer total', computer_total)
print('User total',user_total )
if user_total > computer_total:
print('User wins')
elif user_total < computer_total:
print('Computer wins')
else:
print('It is a tie!')
Now, call this function just after the code in Step 2 in the main
program area using:
# final line in code - deciding who wins
find_winner(computer_rolls,user_rolls)
Run the program to see if it works.
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
94 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 94
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 94
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:94
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 We will
also use a while loop to do some error checking and which set of
choices is being used to modify the list. We must make sure the user
enters the correct number of holds and also add import time at the
top to add the pause in the game rolls and force them to reenter data
if necessary. This error here. Add this function toward the top of the
file after the checking is important so the rest of the game works.
other functions.
Here is the code to be added after the code for the user rolls, just
before the computer rolls.
def roll_again(choices, dice_list):
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!
CREATE YOUR OWN DICE GAMES ::/ 95
225269 - Creative Coding in Python_001-144.indd 95
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 95
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:94
Text
Page:95
Step 6:
Use a Strategy to Determine the Computer’s Choices Now that
the user’s choices have been made and the dice have been rerolled,
we must allow the computer to make its choice on what dice to hold
and what to roll again. We can use different strategies to do this. Here
are two possibilities: Strategy 1: Roll everything, so the choice string
is just a series of rs.
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
96 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 96
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 96
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:96
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)
How Can You Make This Game Better?
There are many ways to improve this game.
■ Allow two or three rerolls, to allow the user or computer to improve
the final score.
■ Run the entire game inside a loop, to allow three rounds of the
game to determine a final winner.
■ Change the winning objective—get the lowest score, the maximum
number of sixes, or something else.
■ Is < 5 the best strategy to decide on a reroll? Modify the code for
the strategy or add more strategies and/or give the user a choice of
difficulty level to determine which strategy will be used by the
computer.
■ Add some better formatting and/or ASCII art to make the text-based
game look better.
This dice game is yours. You can customize it and make it unique
using your creativity and some Python code.
CREATE YOUR OWN DICE GAMES ::/ 97
225269 - Creative Coding in Python_001-144.indd 97
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 97
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:96
Text
Page:97
NEXT STEPS
EXPERIMENT AND EXTEND
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
98 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 98
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 98
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:98
Python Turtle Graphics
Experiment 2:
Create Changing Landscapes
Use the following house function—which is based
off the experiment on page 51—with different
sizes and colors, to create several random houses
in a landscape that changes each time the program
is run.
Pseudocode
Import turtle module
Python Turtle Graphics
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 house(x, y, wallColor, roofColor):
shelly.penup() # Lift pen before moving to new location
shelly.goto(x,y) # move turtle to position
shelly.setheading(0) # set turtle to point to the right
shelly.pendown() # put pen down and get ready to draw
shelly.begin_fill()
shelly.color(wallColor) # set color and make square for i in range(4):
shelly.right(90)
shelly.forward(30)
shelly.end_fill()
shelly.backward(35) # go back and get ready for roof
shelly.begin_fill() # start fill of color for roof shelly.color(roofColor)
shelly.left(60)
shelly.forward(40)
shelly.right(120)
shelly.forward(40)
shelly.right(120)
shelly.forward(40)
shelly.end_fill() # end fill of color for roof CREATE YOUR OWN
DICE GAMES ::/ 99
225269 - Creative Coding in Python_001-144.indd 99
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 99
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:98
Text
Page:99
Experiment 3:
Experiment 4:
Generate Poems
Create a Card Game
Set up lists of words—adjectives, verbs, and the like—and Create a
card game in which the user and the computer pick generate a poem.
For an extra challenge, try and create a poem from a set of cards and
the higher card wins. Add your own of a particular type, such as a
haiku or a limerick, by choosing rules on scoring and how long the
game runs. Use code from words for the list accordingly. Let the user
decide if they want the Big Idea section on creating a deck of cards
as a list.
another poem or to quit, to allow them to get one or more Use
random.choice(list) to get a card at random from poems.
the list. To remove an item from the deck, use my_cards.
remove(card) where my_cards is the list returned from the Sample
Run
make_cards function.
Enter any key for another poem or enter q to quit Use the function
-------------------------------
find_card_order below to determine if one
card is higher. (Note that this function assumes you are using There
once was a girl called Serena
the code from the Big Idea section on creating a card deck.) who
wanted to be a ballerina.
This function returns same, lower, or higher depending on She played
on a flat
whether the first card is the same, lower, or higher than the and made
friends with a cat,
second card. If the cards are not identical, it finds the first part And
ended up lost in Pensylvina.
of the card name (which is the card number), then the order
-------------------------------
in the list of card numbers, and then returns higher or lower Enter any
key for another poem or enter q to quit based on this position.
-------------------------------
There once was a girl called Tymina
who wanted to be a ballerina.
def find_card_order(card1, card2):
She danced on a hat
if card1 == card2:
and made friends with a rat,
return 'same' # picked the same card
And ended up lost in Transelina.
cpos1 = card1[0: card1.find('-')]
-------------------------------
cpos2 = card2[0: card2.find('-')]
Enter any key for another poem or enter q to quit q order1 =
cardno.index(cpos1)
order2 = cardno.index(cpos2)
if order1 > order2:
return 'higher'
elif order1 < order2:
return 'lower'
else: # same cardno but not same suit
return 'same'
100 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 100
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 100
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:100
Experiment 5:
Create an Unscramble Word Game
Create an unscramble word game in which the computer gives the
user a scrambled word from a list and the user guesses the word.
You can add your own rules on scoring, if the user can quit at any
point or must play all the words, and if there are hints. Use the
following function to scramble the word: 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
ytponh????
225269 - Creative Coding in Python_001-144.indd 101
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 101
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:100
Text
Page:101
Use your
creativity to
create your own
special arcade
games.
Create apps
that have
windows,
buttons,
images, and
more.
225269 - Creative Coding in Python_001-144.indd 102
225269 - Creative Coding in Python_001-144.indd 102
13/9/18 11:26 AM
Text 5
13/9/18 11:29 AM
Title:
225269 - Creative Coding in Python
itle:
Page:102
Write code to
handle keyboard
and mouse
controls.
CREATE YOUR
OWN APPS AND
GAMES
Give a
graphical
interface to
all your coding
projects.
225269 - Creative Coding in Python_001-144.indd 103
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 103
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title: 225269 - Creative Coding in Python
Page:102
Text
Title:
Page:103
BIG IDEA
GRAPHICAL USER
INTERFACES (GUI)
PRESS HERE
Graphical User Interfaces, more popularly called GUI (pronounced
goo-ee), allow users to interact with the computer using graphical
elements such as icons instead of text-based commands that are
typed. Most games and EVENT-DRIVEN PROGRAMMING
applications (apps) on your computer or phone use GUI; you click on
icons, buttons, or menus.
GUI programs are different from the other programs The games in
Chapters 3 and 4 allowed only text-based input in that they have to
respond to external events—for from the user. In this chapter, we
learn how to use GUI in our example, a user clicking on a button,
pressing a key, or games and apps.
resizing a window. This type of programming is called event-driven
programming. GUI programs have a main event loop that listens
for events and then calls on code Creating GUI in Python
(functions) to handle these events; these type of func-Python has a
standard module for creating GUI called Tkinter.
tions are called event handlers.
Tkinter is cross-platform, which means that the Python code used to
build an application can be run on any platform (PC, TKINTER
IMPORT
Mac, Linux, etc). Because Tkinter is a module, any Python program
using it must import it. This must be added at the top The import code
here is different than what we used for of the code.
the turtle module in Chapter 2 or the random module in Chapter 4.
This way of importing allows us to use all the functions in the Tkinter
module without prefixing it with from tkinter import *
the word tkinter.
104 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 104
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 104
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:104
BIG IDEA
GUI EVENT LOOP
Because a program that uses GUI may change any part of the screen
and be able to react to any events, it must be constantly checking to
see if the screen must be updated and refreshed. It must also listen
to the events (keyboard controls or mouse clicks) and handle them by
calling the event handlers.
GUI Event Loops in Python
The Tkinter module has a GUI event loop called the main loop, and it
should be the last line of code in any GUI project. It loops
continuously, listening and handling events and updating the screen
until the user closes the window (or the program calls a window
destroy function). Assuming the name of the variable for the window
is window, this is the last line that must be added.
window.mainloop()
Window update or
GUI MAIN LOOP—
Response to
other actions may
monitors events
event may update
cause other events
and calls function
window or cause
handlers
other actions
Events are
Event
generated
handler
function
User interacts with
Functions known
computer using
as event handlers
mouse or keyboard
are called to run
CREATE YOUR OWN APPS AND GAMES ::/ 105
225269 - Creative Coding in Python_001-144.indd 105
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 105
13/9/18 11:26 AM
Title:
T
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:104
Text
Page:105
BIG IDEA
GUI STARTS WITH
A WINDOW
Any GUI must start with a window that contains everything in the
game or application. It holds the icons, graphic images, text, buttons,
menus, and so on for the application. The GUI program also should
call the main event loop to constantly listen for events.
Creating a Window in Python
To create a window using the Tkinter module, we can use a variable
called window to hold the information about the window and then
give it a title using the following code: window = Tk()
window.title('My First GUI')
The final step as mentioned before is to call the main event loop—this
must be the LAST line in the code.
window.mainloop()
SAME CODE, DIFFERENT
Create a new program in a file called GUITest.py to make your first
GUI window. Here is the code for this program: COMPUTERS
One of the big advantages
My First GUI
from tkinter import *
of the Tkinter module
is that the Python code
window = Tk()
can create a GUI for
window.title('My First GUI')
the computer it is being
run on. So if it’s on a
window.mainloop() # GUI main event loop
Windows computer, your
GUI window will look
You should see a window that looks like any other window on similar
to other Windows
your computer.
applications. If it’s on
a Mac, it will looks like
a Mac application (the
image shown here is from a Mac).
106 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 106
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 106
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:106
BIG IDEA
CLICKABLE
BUTTONS
Now that there is a window, we can add graphical items.
Graphical elements such as buttons, labels, menus, and scrollbars
are called widgets. In this chapter, we will create button, label, entry,
and canvas widgets.
For example, we may want to add a Click Me button that, when
clicked, prints “Hello, World” to a display area on the screen.
To do this, we need to create two widgets:
1 A Click Me button widget that, when clicked, causes the action.
2 A label widget used as a display text area on the screen where the
text is shown.
We must also connect the button to the code that will run when the
user clicks on it. This code will place information into the display area
on the window.
Making Clickable Buttons in Python
For the above example, we will have a Click Me button that, when
clicked, prints “Hello, World” to a display area on the screen.
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.
CREATE YOUR OWN APPS AND GAMES ::/ 107
225269 - Creative Coding in Python_001-144.indd 107
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 107
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:106
Text
Page:107
Now, we can add code to create the widgets and then place them on
the screen.
# adding a button widget
button1 = Button(window, text="Click Me", command = hello_function)
button1.pack() # this actually places the button on the window
# adding the display area - using the label widget display_area =
Label(window, text ="")
display_area.pack() # this actually places the text area on the
window
Here is the complete code. Enter it into a file called FirstGUI.py and
run it.
# my first GUI program
from tkinter import *
window = Tk()
window.title('My First GUI')
# function to be called when the button is clicked def
hello_function():
print('Hello, World') # prints Hello World to the Python Shell
# change the display Area widget to show this text
display_area.config(text = "Hello, World", fg="yellow", bg = \
"black")
# adding a button widget
button1 = Button(window, text="Click Me", command = hello_function)
button1.pack() # this actually places the button on the window
# adding the display area - using the label widget display_area =
Label(window, text ="")
display_area.pack() # this places text area on window
window.mainloop() # last line is the GUI main event loop 108 /::
CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 108
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 108
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:108
Name of the function in the
Name of the variable
code that will run when the user
that has the information
Text to be written
clicks on this button—it must
on the button settings
on the button
be defined before the button.
button1 = Button(window, text="Click Me:", command =
hello_function) The window in which this
button will be used—use
the variable window
created earlier.
My First GUI
Button has the text “Click Me.”
Click Me
When clicked, it will call the
function hello_function.
Display area where the code for
Hello, World
the button will place the text—
it is set to a black background
and yellow foreground or text.
CREATE YOUR OWN APPS AND GAMES ::/ 109
225269 - Creative Coding in Python_001-144.indd 109
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 109
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:108
Text
Page:109
BIG IDEA
ADDING SHAPES, TEXT, AND
IMAGE OBJECTS ON THE SCREEN
For most applications, we need much more than buttons. For
example, a game needs objects such as shapes, text, or images on
the screen. To hold these objects, we need to create a canvas object
that can take in other objects.
How to Display Objects on the Screen in Python
To create a canvas, we create a Canvas widget inside the window,
and we specify the width and height. Like we did for the button
widget, we create a variable for this widget and then use pack() to
display it on the screen.
# create a canvas to put objects on the screen
canvas = Canvas(window, width=400,height=400)
canvas.pack()
USING IMAGES
Add the above to the FirstGUI.py file before the final GUI main event
loop line, and run IN YOUR CODE:
it. You should get a blank open canvas area.
WHERE IS THAT
Add the following code just after this canvas creation code to create a
circle, a rectangle, text, and an image on this canvas. The comments
explain the various GREEN CHAR?
parameters, including x, y, and color, that must be specified to create
each object.
Before you do your test run, an
image named greenChar.gif must
# this creates a red circle at position 100,200, of size 30 by 30
be in the same folder as the
circle = canvas.create_oval(100,200,130,230, fill = 'red') Python file.
You can create a small
gif file using any drawing tool or
# creates a blue rectangle with top left at 50,50, of size 20 by 30
download the greenChar.gif file
blue_rect = canvas.create_rectangle(50,50,70,80, fill = 'blue') at the
website listed on page 138.
Make sure the file is not very large
# creates text 'Welcome' in black,font Helvetica 30 at position
200,200
and you are using the exact name;
screen_message = canvas.create_text(200,200, text= 'Welcome', \
the case matters.
fill='black', font = ('Helvetica', 30))
My First GUI
# create an image object using the gif file
Click Me
img = PhotoImage(file="greenChar.gif")
# use image object to create a canvas image at position 100,100
Hello, World
mychar = canvas.create_image(100,100,image = img)
Run the file. You should get a red circle, a blue rectangle, “Welcome”
text, and a green character image on the screen. See the note on the
left to find out where to get and place the green character image.
Welcome
225269 - Creative Coding in Python_001-144.indd 110
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 110
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:11
Page: 0
11
BIG IDEA
MOVING OBJECTS
BASED ON KEYBOARD CONTROLS
For most applications, we need much more than buttons. For
example, a game needs Now that we have objects, we want to
control them in Using Keyboard Controls in Python
objects such as shapes, text, or images on the screen. To hold these
objects, we need different ways. For example, we may want to move
an object We must create a function that will handle the keyboard to
create a canvas object that can take in other objects.
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 How to
Display Objects on the Screen in Python
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.
To create a canvas, we create a Canvas widget inside the window,
and we specify the called
Because each keyboard input is considered an event, these
move_circle that decides what key has been pressed width and
height. Like we did for the button widget, we create a variable and
then changes the x and y amounts in the circle to move it.
functions are called event handlers. The association of this for this
widget and then use pack() to display it on the screen.
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
# create a canvas to put objects on the screen
the event handler function and the keyboard.
negative amount.
canvas = Canvas(window, width=400,height=400)
Here is the code for this function. Add this after the canvas.pack()
hello_function code in the FirstGUI.py file.
Add the above to the FirstGUI.py file before the final GUI main event
loop line, and run it. You should get a blank open canvas area.
# move circle to left or right based on keys
def move_circle(event):
Add the following code just after this canvas creation code to create a
circle, a key = event.keysym
rectangle, text, and an image on this canvas. The comments explain
the various if key == "Right":
parameters, including x, y, and color, that must be specified to create
each object.
canvas.move(circle,10,0) # change x
elif key == "Left":
# this creates a red circle at position 100,200, of size 30 by 30
canvas.move(circle,-10,0) # change x
circle = canvas.create_oval(100,200,130,230, fill = 'red') Now, we
connect or bind this move_circle function to the
# creates a blue rectangle with top left at 50,50, of size 20 by 30
keys using a canvas bind function as follows.
blue_rect = canvas.create_rectangle(50,50,70,80, fill = 'blue')
# bind keyboard input to move_circle
# creates text 'Welcome' in black,font Helvetica 30 at position
200,200
canvas.bind_all('<Key>', move_circle)
screen_message = canvas.create_text(200,200, text= 'Welcome', \
fill='black', font = ('Helvetica', 30))
Add this canvas bind code just before the final GUI main loop.
# create an image object using the gif file
Run the FirstGui.py file and see if the circle moves with the img =
PhotoImage(file="greenChar.gif")
arrow keys.
# use image object to create a canvas image at position 100,100
mychar = canvas.create_image(100,100,image = img)
Run the file. You should get a red circle, a blue rectangle, “Welcome”
text, and a green character image on the screen. See the note on the
left to find out where to get and place the green character image.
CREATE YOUR OWN APPS AND GAMES ::/ 111
225269 - Creative Coding in Python_001-144.indd 111
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 111
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:11
Page: 0
Text
Page:111
BIG IDEA
MOVING OBJECTS
BASED ON MOUSE CLICKS
Sometimes, we want to move or change an object based on the
mouse click on the object. We must connect a function that handles
the mouse click in a way similar to the event handler for keyboard
controls on the last page.
For example, if we want the character to move to where the user
clicks on the screen, we must find the x and y position of the mouse
click and update the character to that position. We do this by creating
a function that reads the mouse position and updates the character’s
position, and we bind this function to the mouse click event.
Using Mouse Clicks in Python
Code to move character ”mychar” to a new mouse position is done
through a function called move_character as follows:
# function that handles mouse clicks on the character mychar
def move_character(event):
canvas.coords(mychar,event.x,event.y)
Code to bind the character to the mouse clicks is done using a
canvas binding as follows:
# bind left button mouse to moving the character
canvas.bind_all('<Button-1>', move_character) Inch to cm Converter
112 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 112
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 112
13/9/18 11:26 AM
Title:
T
225269 - Creative Coding in Python
Text
itle:
Page:11
Page: 2
11
BIG IDEA
GETTING DATA
FROM THE USER
In addition to the use of buttons, mouse, and keyboard input, a GUI
program may need to get information typed in by the user using an
entry widget. This entry data from the user can then be accessed and
processed in the program.
Getting User Data in Python
To get data from the user, an entry widget must be created as follows:
user_data = Entry(window,text='') # initial entry is blank
user_data.pack()
To access this data in the rest of the program, use user_data.get().
For example, here is a short program that takes a user entry of a
distance in inches, and if it is not empty, converts it to cm and
displays the distance when the user clicks on the Convert button.
# A unit converter app - from inch to cm
from tkinter import *
def convert():
if inch_data.get() != "":
cm_string = str(int(inch_data.get()) * 2.54)
cm_display.configure(text = cm_string)
window = Tk()
window.title('Inch to cm Converter')
Inch to cm Converter
inch_data = Entry(window, text="")
inch_data.pack()
100|
254.0
cm_display = Label(window, text="")
cm_display.pack()
Convert to cm
button = Button(window, text='Convert to cm', command = convert)
button.pack()
window.mainloop() # last line is the GUI main event loop CREATE
YOUR OWN APPS AND GAMES ::/ 113
225269 - Creative Coding in Python_001-144.indd 113
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 113
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:11
Page: 2
Text
Page:11
Page: 3
11
BIG IDEA
GUI CAN SCHEDULE
CODE TO RUN
In some projects—games, for example—we need some actions to
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.
Scheduling Code to Run with GUI in Python
Before the call to the mainloop, schedule any other actions using the
after function. For example:
window.after(100, move_candy)
This schedules the move_candy function to run after 100
milliseconds. In the function move_candy, schedule move_candy to
run again; this creates a loop and keeps it running during the
program. We will see more on how to use this idea in this chapter’s
project.
114 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 114
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 114
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:11
Page: 4
11
BIG IDEA
EXITING
A GUI PROGRAM
Because a GUI program uses a loop (mainloop) that runs
continuously, updating the screen and handling events, it can end if
the user clicks on the window Close button or the program calls a
window destroy function.
Exiting GUI in Python
We can add an Exit button that can be clicked to exit the program.
We will need a function and to connect it to a button as follows.
# function to be called when the button Exit is clicked def
exit_program():
window.destroy()
qbutton = Button(window, text="Exit", command = exit_program)
qbutton.pack() # this actually places the button on the window E
XIT
225269 - Creative Coding in Python_001-144.indd 115
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 115
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:11
Page: 4
Text
Page:11
Page: 5
11
PROJECT
CREATING YOUR OWN
ARCADE-STYLE GAME
Let’s make a classic arcade-style game with the GUI concepts in this
chapter. We will make The Candy Monster Game with the following
features:
■ The player controls a monster character using arrow keys.
■ Candy of different colors appear at random start positions on top
and falls to the bottom.
■ The player must catch the candy that falls and the score ARCADE-
STYLE GAMES
updates to show how many pieces have been caught. If a Arcade-
style games are a type of action game similar to red (or other bad
color) piece of candy is caught, the the classic coin-operated arcade
games. Most of them game ends.
have simple presentation and gameplay. They involve
■ As the score increases, the candy falls faster and the games very
little puzzle solving and rely on a player’s skill in gets more difficult.
moving accurately, making quick decisions, and hand-eye
coordination. Games usually get more difficult as Obviously, you can
change any aspect of the game—the the play advances.
character, the object that falls, the scoring method, and so on.
USING IMAGES IN YOUR GAME
Step 1:
Create the Initial Game Setup
WITH GIF FILES
Here is the pseudocode for this step.
The player character is created using a file of image format GIF (ends
in gif). This file should be placed in the Pseudocode
same folder as the Python file. The size of the file should Import
Tkinter and random modules
not be very large (in the examples provided, they are just Create
window, and canvas object
4KB). You can download the sample gif file for this game, Create
game title and instructions text object
greenChar.gif, at the website on page 138 or find another Set
variable score to 0
file that is copyright free for your use. You can also create Create
score_display widget to show score
your own character using any bitmap editor. Please note Set level to
1
the example in this chapter use gif files because they are Create
level_display widget to show level
the simplest to use in Tkinter. Make sure the file type is gif.
Create character by using an image file
In Tkinter, to use any image on the canvas or in buttons, Call the GUI
main event loop as the last line of code for example, you must first
create an object of type PhotoImage and then use it in the widgets.
Here is the Python code to do the above pseudocode; comments
explain each part. Enter the following code into a new file called
GUIGame.py.
116 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 116
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 116
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:11
Page: 6
11
The Candy Monster Game
The Candy Monster
# The Candy Monster game program
from tkinter import *
import random
Collect Candy but avoid the red ones
# 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()
# set up welcome screen with title and directions title =
canvas.create_text(200, 200, text= 'The Candy Monster', \ fill='white',
font = ('Helvetica', 30))
directions = canvas.create_text(200, 300, text= 'Collect candy \ but
avoid the red ones', fill='white', font = ('Helvetica', 20))
# set up score display using label widget
score = 0
score_display = Label(window, text="Score :" + str(score))
score_display.pack()
# set up level display using label widget
level = 1
level_display = Label(window, text="Level :" + str(level))
level_display.pack()
# create an image object using the gif file
player_image = PhotoImage(file="greenChar.gif")
# use image object to create a character at position 200, 360
mychar = canvas.create_image(200, 360, image = player_image)
window.mainloop() # last line is the GUI main event loop When you
run the code at this step, a basic game window with instructions,
similar to the one shown, should appear.
CREATE YOUR OWN APPS AND GAMES ::/ 117
225269 - Creative Coding in Python_001-144.indd 117
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 117
13/9/18 11:26 AM
Title:
T
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:11
Page: 6
Text
Page:11
Page: 7
11
Step 2:
Add Code to Make the Candy and Drop It
Here is the pseudocode for this step.
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.
118 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 118
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 118
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:11
Page: 8
11
# 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']
# function to make candy at random places
def make_candy():
# pick a random x position
xposition = random.randint(1, 400)
# pick a random color
candy_color = random.choice(candy_color_list)
# create a candy of size 30 at random position and color candy =
canvas.create_oval(xposition, 0, xposition+30, 30, fill = \ candy_color)
# add candy to list
candy_list.append(candy)
# if color of candy is red - add it to bad_candy_list if candy_color
== 'red' :
bad_candy_list.append(candy)
# schedule this function to make candy again
window.after(1000, make_candy)
# function moves candy downwards, and schedules call to
move_candy def move_candy():
# loop through list of candy and change y position for candy in
candy_list:
canvas.move(candy, 0, candy_speed)
# check if end of screen - restart at random position if
canvas.coords(candy)[1] > 400:
xposition = random.randint(1,400)
canvas.coords(candy, xposition, 0, xposition+30,30)
# schedule this function to move candy again
window.after(50, move_candy)
CREATE YOUR OWN APPS AND GAMES ::/ 119
225269 - Creative Coding in Python_001-144.indd 119
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 119
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:11
Page: 8
Text
Page:11
Page: 9
11
Step 3:
Add Code to Update the Score
and End the Game
Here is the pseudocode for this step.
Here is the code for this step. Add this to the end of the code from the
last step, again making sure it is before the last GUI Pseudocode
main event loop line. Because these functions have not been Define
function update_score_level()
scheduled, there is no change from Step 1; the score does not
Increase score, update display
update yet.
If score > 10
Set level to 2, update display
# function updates score, level and candy_speed Increase
candy_speed.
def update_score_level():
If score > 20
# use of global since variables are changed
Set level to 3, update display
global score, level, candy_speed
Increase candy_speed
score = score + 1
Define function end_game_over()
score_display.config(text="Score :" + \
Destroy the window,
str(score))
Define function end_title()
# determine if level needs to change
Destroy title, instructions objects
# update level and candy speed
if score > 5 and score <= 10:
candy_speed = candy_speed + 1
level = 2
level_display.config(text="Level :" + \
str(level))
LOCAL VS. GLOBAL VARIABLES
elif score > 10:
candy_speed = candy_speed + 1
Any variable that is created inside a function (inside level = 3
the def) is local to the function, which means that only
level_display.config(text="Level :" + \
the code within the function can access it. The variable str(level))
is not available after the function (outside the def) has run. Variables
that are created outside the function are
# function called to end game - destroys window called global
variables. They exist for the entire time def end_game_over():
the program does. All functions can access them, but
window.destroy()
cannot modify them unless they are declared global inside the
function. Because the variables score, level,
# this destroys the instructions on the screen
and candy_speed must be maintained through the def end_title():
game, they are created as global variables outside the
canvas.delete(title) # remove title
update_score_level function. The update_score_
canvas.delete(directions) # remove directions
level function will need to modify score, level, and candy_speed
variables, so they are declared as global inside the function. Global
variables should be avoided when possible since they can be
changed in different and sometimes unexpected places, making it
difficult to find problems in a program. We can avoid the use of global
variables by using more advanced programming techniques that are
beyond the scope of this book.
120 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 120
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 120
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:120
Step 4:
Add Code to Check If
Character and Candy Collide
We now need to add code to determine
Here is the code for this step; add this to the file once again before
the last GUI main when the character touches the candy
event line. Because these functions are not being called yet, there will
be no change and delete it from the list of candy. If it
detected at this stage.
is a bad candy, we must call an end to
the game.
# check distance between 2 objects - return true if they 'touch'
Here is the pseudocode for this step.
def collision(item1, item2, distance):
xdistance = abs(canvas.coords(item1)[0] - canvas.coords(item2)[0])
Pseudocode
ydistance = abs(canvas.coords(item1)[1] - canvas.coords(item2)[1])
Define function collision(item1,
overlap = xdistance < distance and ydistance < distance item2,
distance)
return overlap
Set x to horizontal difference
between items
# checks if character hit bad candy, schedule end_game_over
Set y to vertical difference
# if character hits candy, remove from screen, list, update score
between items
def check_hits():
Set overlap to x < distance and
# check if it hit a bad candy - need to end game for candy in
bad_candy_list:
y < distance
if collision(mychar, candy, 30):
Return overlap
game_over = canvas.create_text(200, 200, text= 'Game \ Define
function check_hits()
Over', fill='red', font = ('Helvetica', 30))
While there is item in
# end game but after user can see score
candy_list
window.after(2000, end_game_over)
If item is hit by character
# do not check any other candy, window to be destroyed If item
is in badcandy_list
return
# 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)
CREATE YOUR OWN APPS AND GAMES ::/ 121
225269 - Creative Coding in Python_001-144.indd 121
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 121
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:120
Text
Page:121
Step 5:
Add Code to Control the Character
with the Arrow Keys
We must now add code to control the player character with Here is
the pseudocode for this step.
the arrow keys. If we call a function each time the arrow key is
pressed, the control will not be smooth. Instead, we determine
Pseudocode which direction the character should move when the
arrow Set move_direction to 0
keys are first pressed, we keep track of this move direction in Define
function check_input(event)
a variable called move_direction, and then when the arrow If key
pressed is right
keys are released, we update the variable move_direction.
Set move_direction to right
Finally, we update the character position based on the move_
If key pressed is left
direction value, checking that it does not go off the edge of Set
move_direction to left
the screen.
Define function end_input(event)
Set move_direction to None
Define move_character()
If move_direction is right AND within screen edge
Increase character x
If move_direction is left AND within screen edge Decrease
character x
Schedule move_character after 16 ms
Set canvas binding key press to check_input
Set canvas binding key release to end_input
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).
122 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 122
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 122
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:122
move_direction = 0 # track which direction player is moving
# Function handles when user first presses arrow keys def
check_input(event):
global move_direction
key = event.keysym
if key == "Right":
move_direction = "Right"
elif key == "Left":
move_direction = "Left"
# Function handles when user stop pressing arrow keys def
end_input(event):
global move_direction
move_direction = "None"
# Function checks if not on edge and updates x coordinates
based on right/left def move_character():
if move_direction == "Right" and canvas.coords(mychar)[0] < 400:
canvas.move(mychar, 10,0)
if move_direction == "Left" and canvas.coords(mychar)[0] > 0 :
canvas.move(mychar, -10,0)
window.after(16, move_character) # Move character at 60 frames
per second
# bind the keys to the character
canvas.bind_all('<KeyPress>', check_input) # bind key press
canvas.bind_all('<KeyRelease>', end_input) # bind all keys to circle
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.
Here is the additional code for this step. Make sure it is added before
the final GUI main event loop line.
CREATE YOUR OWN APPS AND GAMES ::/ 123
225269 - Creative Coding in Python_001-144.indd 123
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 123
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:122
Text
Page:123
NEXT STEPS
EXPERIMENT AND EXTEND
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 Song
Lyrics Generator
their entries. Add an image on the button using code as follows
Pseudocode
Something red, e.g., roses:
(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).
Something blue, e.g. violets:
make_password function
Get random word from word list
button_image = PhotoImage(file="musicNotes.gif") Something you
love, e.g. puppies:
Add to random item from separator list
Set up GUI window
button = Button(window, text = 'Create \
Verb, e.g., singing:
Set up button with make_password callback
Song',image = button_image, compound = TOP, \
command = create_song)
Code Hint
button.pack()
Here is some sample code to combine strings chosen at random from
lists.
To set a color on the window, you can use:
commonWords=['cat', 'dog', 'jump', 'train', \
window.configure(bg="MediumPurple1")
robins are red
'toast', 'water', 'phone']
mittens are blue
specialChars = ['!', '$', '%']
I like kittens
You can also set the same color in the labels using: But not as much
as I love dancing with you!
password = random.choice(commonWords) + random. \
choice(specialChars) + random.choice(commonWords) \ red_label =
Label(window,text='Enter something red \
+ str(random.randint(0,100)) + random. \
, e.g. roses: ',bg="MediumPurple1", fg= 'black',) choice(specialChars)
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!
124 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 124
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 124
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:124
Experiment 3:
Make a Voting App
Create an app in which the user clicks
on the button of their choice to vote, and
Song Lyrics Generator
the vote count updates. For example, a
voting app could find out if the person
Something red, e.g., roses:
is a dog lover or a cat lover. The code is
robins
similar to the score update in the game
Something blue, e.g. violets:
project in this chapter.
mittens
Something you love, e.g. puppies:
kittens
Verb, e.g., singing:
Voting App
dancing
Create Song Lyrics
robins are red
Cat person?
mittens are blue
I like kittens
But not as much as I love dancing with you!
Dog person?
Cat lovers = 2
Dog lovers = 3
225269 - Creative Coding in Python_001-144.indd 125
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 125
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:124
Text
Page:125
The Spider Survival Game
Experiment 4:
Create an Arcade-style Survival Game
Make changes and extensions to the Candy Monster game to create
a Spider Survival game in which the player must avoid the objects
(spiders) instead of catching them. The goal is to survive for as long
as possible, and the score field at the The Spider Survival Game
bottom indicates how many seconds they have survived. As before,
the game gets more difficult by increasing the speed of How long can
you avoid the spiders?
the objects over time.
Here are some changes that you may need:
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)
Use a spider graphic instead of the canvas objects that were used to
make the candy. Place this code outside the make_spiders function
(which is a version of the make_candy The Spider Survival Game
function).
spider_image = PhotoImage(file="spider.gif") And inside the
make_spiders function, use the following: 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"
126 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 126
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 126
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:126
Experiment 5:
Two-player Games and More
Change the move_character function to use all directions and Once
you understand the code to make one of these games, check edges:
extend the games and/or add other extensions. For example:
● Turn the Spider Survival game into a Road Crossing game, in def
move_character():
which you update the score only if player can move across if
move_direction == "Right" and canvas. \ the screen, avoiding spiders
and/or other objects, and reach coords(mychar)[0] < 400:
a home icon safely.
canvas.move(mychar, 10,0)
● Create a Treasure Hunt game in which the player has to if
move_direction == "Left" and canvas. \ move around collecting
treasure and avoiding enemies.
coords(mychar)[0] > 0 :
When the player reaches a portal icon, the background and
canvas.move(mychar, -10,0)
objects change to create a new room or level.
if move_direction == "Up" and canvas. \
● Customize the images and/or add background image to the
coords(mychar)[1] > 0 :
window by using a canvas image object centered on the
canvas.move(mychar, 0,-10)
canvas.
if move_direction == "Down" and canvas. \
● Turn any of these games into a two-player game. For
coords(mychar)[1] < 400:
example, in the Spider Survival game, create another player
canvas.move(mychar, 0,10)
using a different image that is controlled by WASD keys.
window.after(16, move_character)
Display scores for both players at the bottom.
● Add a laser or missile launch feature for when you press the
Change the movement so the spiders appear on the left and Space
key. You can create a new canvas object that starts at move to the
right. Note the spiders do not come back once the player and add it to
a new laser list and then schedule they reach the edge.
a function that moves items in the laser list and checks if it hits other
items in the game.
# function moves spiders from left to right
Invite your friends and family to showcase your coding skills def
move_spider():
and test your apps and games. Get feedback on how to
# loop through list and change x position
improve your projects further.
for spider in spider_list:
canvas.move(spider, spider_speed, 0)
window.after(50, move_spider)
Change the way the score updates, so it updates every second and
not when there are hits.
CREATE YOUR OWN APPS AND GAMES ::/ 127
225269 - Creative Coding in Python_001-144.indd 127
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 127
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
T
225269 - Creative Coding in Python
itle:
Page:126
Text
Page:127
WHAT’S NEXT?
Now that you have learned to code several projects in Python, what’s
next? Here are some ways to use your powerful new skill and expand
your knowledge of coding in Python.
Use Python with the micro:bit for Physical
Computing: Program LEDs, Motors,
Speakers, and More
The micro:bit is a small and inexpensive computer (powered by a
microcontroller) that can be programmed using MicroPython—a
special version of Python for microcontrollers.
You can use MicroPython online on microbit.org or download an
editor like Mu (codewith.mu). Using Python code, you can control
LEDs (light emitting diodes), motors, play music on speakers, and
much more.
Here is a simple example of Python code that turns on an LED
light, displays a check mark on the display when button A is B
pressed, and then turns the light off and displays an X when button B
is pressed. In addition, if the micro:bit is shaken, it Pressing
Pressing
displays a random number from 1 to 6 (acts like a digital dice).
this Button
this Button
You could use a micro:bit project like this to build your own A turns
ON
B turns OFF
the LED and
the LED and custom game board, for example.
displays a
displays
check
GND
an X
from microbit import *
import random
May need
pin1.write_digital(0) # light is off
to add a
display.show(Image.NO)
resistor here,
while True: # repeat forever
LED
depending
on the type
if accelerometer.was_gesture("shake"):
of LED
roll = random.randint(1,6)
display.show(str(roll)) # show random number
elif button_a.is_pressed():
+ve (long leg)
-ve (short leg)
display.show(Image.YES)
connected to
connected to
pin 1
GND
pin1.write_digital(1) # turn light on
elif button_b.is_pressed():
display.show(Image.NO)
pin1.write_digital(0) # turn light off
128 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 128
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 128
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:128
What can
I code
next?
Use Python on the Raspberry Pi
The Raspberry Pi is a small and inexpensive general-purpose
computer that comes with Python 3 installed. In addition to running all
the Python projects in this book on the Raspberry Pi, you can use it
for physical computing by connecting the row of GPIO (general-
purpose input/output) pins to LEDs, motors, speakers, and more. Or,
you can extend the Raspberry Pi using an add-on board like the
Sense Hat.
Here is a simple example of using Python to control an LED
and a button connected to the Raspberry Pi.
from gpiozero import LED, Button
led = LED(17)
button = Button(2)
while True:
if button.is_pressed:
led.on()
else:
led.off()
PHYSICAL COMPUTING AND
THE MAKER MOVEMENT
The micro:bit and the Raspberry Pi are popular in the maker
movement, a trend where anyone can use their creativity and building
skills to create objects from different materials. Using code, a maker
can make
fun and/or useful items that come alive with spinning motors, blinking
lights, and more.
::/ 129
225269 - Creative Coding in Python_001-144.indd 129
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 129
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:128
Text
Page: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 ap
a dictionary called scores to keep track of scores of different players.
pw
lic e
The key is the name of the player and the value is the score. This is
much a b
easier than using multiple variables or a list.
ion
files
scores = {'Mia': 56, 'Nico': 44, 'Joe': 97, 'Ana' : 100}
print(scores['Ana']) # this prints 100, value for key Ana Exception
Handling
We did some basic error checking in the projects in this book—for
dictionaries
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 when the program runs are called exceptions. To make
a robust program, g
we want to exit the program gracefully with an error message in all
cases.
dlin
In order to do that, we will have to check for several possibilities: for n
exception
example, is the file to be opened available, is the number entered
valid, h
and so on. Python provides an easy way to do exception handling
with the try/except statement. Here is a very simple example where
we recover from any error due to an invalid number entry or a divide
by 0.
try:
machine
candy = input('Enter amount of candy ')
physical
learning
persons = input(‘Enter number of people ')
computing
print('Candy per person is', int(candy) // int(persons)) except:
print('Error. Unable to calculate candy amount')
130 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 130
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 130
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:130
Files
Your project may need to save and read information to a computer file
to be used next time it is run (for example the high score of the
player). Python has many ways to create, read, and modify different
kinds of files. Here is a very simple example that opens a file
containing high scores and prints out the information.
app w
fhandle = open('highscores.txt', 'r') # opens file for reading ic e
ab
scores = fhandle.read() # gets all content from file tio
print(scores)
ns
fhandle.close()
advanced
games
Extend Your Python Powers by Using Other Standard Python
Modules
There are several modules in the Python Standard Library and are
part of the Python a
alysi
download. We have already used the following in this book: s
■ Chapter 2: Turtle module, to do turtle graphics
■ Chapter 3: Time module, to create a pause in the adventure game
■ Chapter 4: Random module, to get a random number for a roll for
the dice
■ Chapter 5: Tkinter module, to create GUI games and apps 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:
■ Math gives access to math functions like pi or square root.
■ Statistics allows use of functions like mean, median, and variance.
■ Datetime makes operations on time and date easy.
machine
■ CSV handles files in Comma Separated Values format, which is
commonly used in learning
spreadsheets and databases.
■ Webbrowser allows you to display Web documents to users.
WHAT’S NEXT? ::/ 131
225269 - Creative Coding in Python_001-144.indd 131
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 131
13/9/18 11:26 AM
Title:
T
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:130
Text
Page:131
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.
Code Completion with Autocomplete
With the autocomplete feature in IDLE, you do not need to
>>> s = 'hello'
remember the exact name and usage of the functions, and you can
discover new functions as you code. This assisted
>>> s.
intelligent code completion makes coding much easier. To use
capitalize
casefold
autocomplete in IDLE, enter the name of the variable and the center
‘.’ and wait for IDLE to prompt with all the possible functions.
count
See the screenshot showing all possible functions to be used encode
on the string ‘s’. Once you select the function and enter the endswith
first ‘(‘, IDLE prompts with the list of parameters needed for
expandtabs
the function.
find
format
In addition to using autocomplete, you can also use the Python
format_map
dir function to find all possible functions. For example, if you have a
string s, type in dir(s) in the Python Shell to list all the ways you can
manipulate the string.
IDLE is an example of an IDE (Integrated Development Environment)
that is free with the Python download. You can use other IDEs and
editors like PyCharm from JetBrains or Microsoft’s Visual Studio
Code that offer more powerful tools for debugging and intelligent
code completion.
132 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 132
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 132
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:132
>>> s = 'hello'
>>> dir(s)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__',
'__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__',
'__getnewargs__',
'__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__',
'__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__',
'__reduce__',
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__',
'__sizeof__',
'__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count',
'encode',
'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index',
'isalnum',
'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric',
'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip',
'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition',
'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase',
'title', 'translate', 'upper', 'zfill']
>>> s.capitalize()
'Hello'
>>>
Go Even Further by Using Powerful Third-Party Python
Packages Since Python is a popular and open source language,
there is an active community of users and contributors who have
created software for a variety of applications. They make their
software available for free as packages (collections of modules) for
other Python developers. You can check what is available at the
Python Package Index at pypi.org. Here is a small list of some
popular third-party Python packages that you can look at next.
■ PyGame (Pygame.org) allows you to build 2-D games in Python.
■ Use Python code to build and control Minecraft Pi, a special
edition of Minecraft made for Raspberry Pi.
■ Requests (docs.python-requests.org/en/master) and
BeautifulSoup (crummy.com/software/
BeautifulSoup) packages help you access content on the Internet in
your projects.
■ Kivy (kivy.org) allows you to create multi-touch Python apps across
multiple platforms.
■ Matplotlib (matplotlib.org) is a popular package for data analysis.
■ Scikit-learn (scikit-learn.org) offers easy to use tools for machine
learning in Python.
WHAT’S NEXT? ::/ 133
225269 - Creative Coding in Python_001-144.indd 133
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 133
13/9/18 11:26 AM
Title:
T
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:132
Text
Page:133
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 on
Help, then click on Python Docs, and you will be able stories on
Python.org.
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 Expand Your
Coding Skills by Learning
example, the Biopython Project provides Python tools for Object-
Oriented Programming
computational molecular biology.
■ 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.
The only way to learn to code is to spend a lot of time coding.
Work through all the small code examples under the Big Idea
sections to understand the fundamental ideas in programming,
build your own version of the chapter projects, and then
strengthen your understanding by trying out all the Experiment
and Extend projects. Building your own projects using your
creativity and Python code is not only a good way to learn to
code, but is also a lot of fun.
134 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 134
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 134
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:134
HAPPY
CODING!
225269 - Creative Coding in Python_001-144.indd 135
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 135
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
T
225269 - Creative Coding in Python
itle:
Page:134
Text
Page:135
GLOSSARY
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
just using text.
> 5 is false
Debugger: A tool that helps in testing
and finding bugs in a program
Global variables: Variables that can be
Bugs: Mistakes in the code that cause
accessed by all parts of the program
the program to run differently than
Debugging: Finding and removing a bug
expected
or mistake in the code
Imports: A way to give access to the
functions and definitions in a module
Canvas: Part of the application window
Event-driven programming: Where
in Python
used to display shapes, images, etc.
the program or code runs based on an
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
136 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 136
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 136
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:136
Loops: A repeating a set of instructions Shell: An interactive
part of Python IDLE
where you can enter Python code for
Module: A file in Python that has
experimenting; also a place where text
functions and definitions—for example,
is entered to a program, or output of a
turtle module has functions to use the
program is displayed
Python turtle
Strings: Any text is known as a string
Nested conditional: A conditional
and is entered with a single or double
statement inside another conditional
quote. ‘Hello’ and “Susan” are strings.
sentence
Syntax error: A mistake in the usage
Nested loop: A loop inside another loop
of the programming language—for
Object-oriented programming: A
example, a wrong spelling
way of coding where the program is
Value: Content of the variable
organized as objects with data and
functions that can manipulate the object
Variables: Item that stores
information—it has a name and a value
Parameters: Information given to a
and corresponds to location in memory.
function—for example, the print function
takes the string to be printed as a
Widgets: Graphical elements like
parameter
buttons, labels, menus that are part of a
GUI program
Physical computing: Programming
objects in the world like LEDs, motors,
Window: Part of the GUI program, the
speakers, and more
window is a separate viewing area on
the computer screen corresponding to
Program: A set of instructions to do
an application.
a task in a language the computer
understands
Pseudocode: Algorithm written in an
informal natural language like English
Random: Something that has an
element of chance, changes each time,
or is not fixed
Runtime error: A mistake that appears
when the program is run
::/ 137
225269 - Creative Coding in Python_001-144.indd 137
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 137
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:136
Text
Page:137
RESOURCES
Python
Download Python for free, get help with Python problems and
questions, and learn more about programming.
www.python.org
Creative Coding in Python
Your source for all things related to this book.
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
Computers for Creativity
More information on programing (in Python and other
languages) and its uses, plus project ideas and resources for
teachers. The author’s website.
www.computersforcreativity.com
138 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 138
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 138
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:138
ACKNOWLEDGMENTS
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.
I am grateful to my years of teaching experience at the Los Altos
School District and the innovative administrators, Jeff, Alyssa,
Sandra, and Karen, who supported me in the best job ever—
bringing computer science to every student in the district.
I would like to acknowledge the teacher community—the STEM
team at LASD, the hundreds of teachers who took my coding
workshops at KCI Foothill college, and the amazing #csk8 and
CSTA (Computer Science Teachers Association) groups.
Your enthusiastic reception of my lessons made me believe that
I should share my teaching methods through a book.
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.
::/ 139
225269 - Creative Coding in Python_001-144.indd 139
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 139
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:138
Text
Page:139
ABOUT THE AUTHOR
Sheena Vaidyanathan teaches a Python-based computer science
class to 11–13
year olds and is the computer science integration specialist in
the Los Altos School District, in Los Altos, California, where she
has also designed computer science curricula, conducted
professional development for the K–8 STEM program, and
taught pre-algebra, digital design, and visual art. She is also the
program director for the computer science professional
development programs at Krause Center for Innovation, Foothill
College, where she teaches teachers to code in Python, Scratch,
and other languages. Over the years, hundreds of students and
teachers have learned to code in her classes. She shares her
many years of experience teaching coding by writing articles,
presenting at conferences, and providing best practices and
student work on her personal website,
computersforcreativity.com.
Prior to teaching, Vaidyanathan worked in Silicon Valley for
more than 10 years as a computer scientist and technology
entrepreneur. She lives in Los Altos, California.
140 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 140
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 140
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:140
INDEX
3-D animation, 134
importance of, 8
incremental steps, 75
BeautifulSoup package, 133
indentation, 62
begin_fill function, 41
abstract art, 98
text color, 10
binding, 111
adventure game project
colon (:), 62, 63
Blender tool, 134
direction choices, 72–73
color
Boolean expressions, 58, 59–60
error checking, 75
colored squares, 50
Boolean values, 56, 65
improvement ideas, 76
geometric art project, 48
Boole, George, 56
introduction code, 70
list storage of, 44–45
bugs. See errors.
introduction to, 69
text color, 10
buttons
loops, 71
turtle graphics, 41
clickable GUI buttons, 107–109
pauses in, 76
comments, 22
Convert, 113
user choices, 70, 72–73
comparisons, 58
Exit, 115
user input improvements, 75
conditions
images in, 116, 124
user question, 74
colon (:) and, 62
algorithms
combined conditions, 59
flowcharts, 13
conditional (if-else) statements, 61, 62
pseudocode, 12
calculations, 23–25
conditional loops, 66–68
and operator, 59, 60
canvas objects, 110
definition of, 58
animation, 134
card game, 100
elif statements, 65
arcade-style game project
changing landscapes, 99
nested conditionals, 63–64
candy code, 118–119
chatbot project
Convert button, 113
candy collision, 121
extending, 81
counting by 2s, 3s, or multiple numbers,
80
ending, 120
feelings comments, 30
CSV module, 131
frames-per-second (FPS), 122
file creation, 27
gif files, 116
goodbye code, 30
initial game setup, 116–117
improving, 31
keyboard controls, 122–123
introduction code, 28
datetime module, 131
score updates, 120
introduction to, 26
debugger tool, 132
starting, 123
math functions, 28
debugging, 11, 132
arcade-style survival game, 126–127
response templates, 29
def keyword, 84
artificial intelligence (AI), 91, 134
circle of circles, 52
dice game project
autocomplete feature, 132
choices function, 96–97
deciding the winner, 94
code
dice selection, 92
definition of, 8
hold or roll again, 95
font for, 9
improvement options, 97
force-stopping, 43
introduction to, 91
::/ 141
225269 - Creative Coding in Python_001-144.indd 141
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 141
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:140
Text
Page: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
False value, 56–58, 59–60
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
move_character, 112, 122, 127
H
overlapping circles, 52
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
142 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 142
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 142
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:142
text loops, 89–90
nested loops, 42–43, 47
lower( ) function, 75
not operator, 59
IDEs (integrated development
NumPy package, 134
environments), 9, 132
IDLE (Integrated DeveLopment
Environment)
machine learning
O
autocomplete feature, 132
games and, 91
object-oriented programming, 134
definition of, 9
scikit-learn library, 133, 1134
operators
shell window and, 10
TensorFlow library, 134
and, 59, 60
if-else (conditional) statements, 61, 62
Mad Libs, 32
Booleans, combining with, 60
imports
makeSpiders function, 126
Boolean values and, 65
modules, 93
math operations
not, 59
Tkinter module, 104
chatbot project, 28
or, 59
turtle graphics, 38
Math module, 131
overlapping circles, 52
indentation, 62
paint calculator, 35
input function, 19
Python Shell and, 23–24
installation, 9
restaurant bill calculator, 34
packages, 133
integers
user entries as integers, 25
paint calculator, 35
calculating, 24
Matplotlib package, 133, 134
Papert, Seymour, 38
converting, 25
micro:bit, 128
password checker, 77
print function and, 21
MicroPython, 128
password generator, 124
user data and, 25
Minecraft Pi, 133
poem generator, 100
int function, 25
modules
print function
interpreter, 9
CSV, 131
end characters, 21
datetime, 131
function of, 11, 21
importing, 93
loops and, 40
keyboard inputs, 111
math, 131
projects
Kivy package, 133
random, 88
adventure game, 69–76
statistics, 131
arcade-style game, 116–123
time, 76
chatbot, 26–31
turtle graphics, 38, 46
lists
dice game, 91–97
webbrowser, 131
color storage in, 44–45
geometric art, 46–49
mouse, GUI object movement with, 112
data storage in, 44–45
unit converter, 34
move_character function, 112, 122, 127
local variables, 120
pseudocode
move_circle function, 111
LOGO programming language, 38
definition of, 12
move_coins function, 114
loops
font for, 9
action scheduling, 114
PyCharm, 132
adventure game project, 71
PyGame, 133
conditional loops, 66–68
names
Python
for loop, 40–41
functions, 84, 92
creation of, 8
GUI events, 104, 105
gif files, 110
installing, 9
nested loops, 42–43
underscore ( _ ) and, 92
interpreter, 9
variables, 19
name origin, 8
INDEX ::/ 143
225269 - Creative Coding in Python_001-144.indd 143
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 143
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
itle:
Title:
225269 - Creative Coding in Python
itle:
Page:142
Text
Page:143
popularity of, 8
shell window, 10
versions, 9
text
values
Python Docs, 134
color, 10
Booleans, 56
Python Package Index, 133
comments, 22
False, 56–58
loops, 89–90
True, 56–58
manipulation options, 75
variables
strings, 17, 75
data storage in, 16, 17
quiz game, 79
time module, 76
naming, 17, 18
Tkinter module
quotation marks in, 17
R
cross-platform use of, 104, 106
spelling and, 17
random module, 88, 93, 101
imports, 104
text strings, 17, 19
Raspberry Pi, 129
main loop, 105
user data, 19
Requests package, 133
widgets, 107
value of, 16
reroll function, 95
window creation, 106
viewing stored data, 17
restaurant bill calculator, 34
True value, 56–58, 59–60
voting app, 125
Rossum, Guido van, 8
try/except statement, 130
runtime errors, 11
turtle graphics
color function, 41
webbrowser module, 131
functions, 38, 39
widgets
importing, 38
scheduled GUI actions, 114
Canvas, 110
location coordinates, 39
scientific research, 134
definition of, 107
loops, 40–41
Scikit-learn package, 133
entry widget, 113
nested loops, 42–43
shell window, 10
word game, 101
shape of, changing, 39
sleep function, 76
two-player games, 127
Solomon, Cynthia, 38
song lyrics generators, 33, 124
square function, 84–85
Stack Overflow website, 134
underscore ( _ ), 92
statistics module, 131
unit converter, 34
strings
unscramble word game, 101
concatenation, 25
converting to integer, 25
definition of, 17
looping, 90
lower method, 75
manipulation options, 75
sum function, 94
syntax errors, 11
144 /:: CREATIVE CODING IN PYTHON
225269 - Creative Coding in Python_001-144.indd 144
13/9/18 11:29 AM
225269 - Creative Coding in Python_001-144.indd 144
13/9/18 11:26 AM
Title:
225269 - Creative Coding in Python
Text
itle:
Page:144
Document Outline
Cover
Half Title
Title
Copyright
Dedication
Contents
INTRODUCTION
What Is Coding?
Why Learn to Code?
Why Python?
Installing Python
The First Line of Code
Python Functions
Computers Are Picky: Understanding Errors
Problem Solving: Planning Your Code by Writing
Algorithms
Pseudocode
Flowcharts
1 CREATE YOUR OWN CHATBOTS
Big Ideas
Storing Data with Variables
Getting Data from the User
Outputting Data on a Screen
Adding Comments to Your Code
Doing Math on the Computer
Project
Creating Your Own Chatbot
Next Steps
Experiment and Extend
2 CREATE YOUR OWN ART MASTERPIECES
Big Ideas
Turtle Graphics
Loops
Storing Data in Lists
Project
Creating Geometric Art
Next Steps
Experiment and Extend
3 CREATE YOUR OWN ADVENTURE GAMES
Big Ideas
Computers Understand True and False
Computers Can Combine True and False
Code Based on Conditions
Computers Can Loop Based On a Condition
Project
Creating an Adventure Game
Next Steps
Experiment and Extend
4 CREATE YOUR OWN DICE GAMES
Big Ideas
Creating Your Own Functions
Computers Can Pick Items at Random
Looping Through a List or a String
Project
Creating Your Own Dice Game
Next Steps
Experiment and Extend
5 CREATE YOUR OWN APPS AND GAMES
Big Ideas
Graphical User Interfaces (GUI)
GUI Event Loop
GUI Starts with a Window
Clickable Buttons
Adding Shapes, Text, and Image Objects on the
Screen
Moving Objects Based on Keyboard Controls
Moving Objects Based on Mouse Clicks
Getting Data from the User
GUI Can Schedule Code to Run
Exiting a GUI Program
Project
Creating Your Own Arcade-Style Game
Next Steps
Experiment and Extend
What’s Next?
Glossary
A
B
C
D
E
F
G
I
L
M
N
O
P
R
S
V
W
Resources
Acknowledgments
About the Author
Index
A
B
C
D
E
F
G
H
I
K
L
M
N
O
P
Q
R
S
T
U
V
W