Pythonfree PDF
Pythonfree PDF
Python 3x Programming
Start Here:
Python Programming
Made Fun and Easier
by
Jody Scott Ginther
Free Version
ii
THIS FREE SAMPLE OF THE COURSE MAY BE FREELY SHARED AND DISTRIBUTED
Published by
Alien Cat Studios
Quantum-Sight
(Educational Division)
1712 W Stevens #D
Bozeman, MT 59715
Copyright 2013 by Jody Scott Ginther. All rights reserved.
iii
Python 3x Programming
iv
DEDICATION
To my two sons, who helped me understand the deeper meaning of:
CONTENTS
Acknowledgments
Int roducing This Course
i
1
2
5
6
8
12
14
15
17
18
19
22
Introducing Strings
String Placeholders and Escapes
26
Review
Lesson 2: Quiz
New Vocabulary
20
23
25
26
30
31
33
Conditional Statements
Loop for a While Statements
35
40
New Vocabulary
34
37
44
45
Python 3x Programming
46
Tuples
Review
Lesson 4: Quiz
56
50
57
New Vocabulary
58
Lesson 5: Functions
Whats a Function?
Making Your Own Functions
The following lessons are included in the full version of this course:
59
64
60
63
66
Positional Parameters
Keyword Arguments
66
67
68
69
70
71
Review
Lesson 5: Quiz
74
75
New Vocabulary
Lesson 6: Basic Modules, Tkinter, and Dictionaries
OOP and Module Basics
Enough Words! Lets Get Graphic!
76
83
78
87
New Vocabulary
88
89
90
More on Methods
More Functions
95
Built-In Functions
More Keywords and Expressions
96
92
96
103
viii
104
Review
105
Lesson 7: Quiz
New Vocabulary
Lesson 8: Common Data Structures
More About Lists
106
112
Sequences
Whats a Set? (Intro to Common Sets)
Frozen Sets
115
114
Review
Lesson 8: Quiz
116
119
120
New Vocabulary
121
123
124
Review
Lesson 9: Quiz
128
129
131
131
131
137
139
Understanding Tkinter
Speaking Tkinter
139
140
140
141
143
Review
Lesson 11: Quiz
145
146
New Vocabulary
Lesson 12: Debugging Basics
147
148
ix
Python 3x Programming
Logic or Semantic Errors
Execution or Runtime Errors
149
Hunting Bugs
The Fight or Rewrite Approach
150
151
150
151
151
152
Pythons Debugger
Tips
152
154
Review
Lesson 12: Quiz
155
156
New Vocabulary
Lesson 13: Designing Your Software
Software Development
Software Versioning
Planning Stage
157
Development Cycle
Maintenance and Support Cycle
161
159
160
161
161
162
163
164
168
169
170
Whats PyGame?
Environmental Planning
171
172
175
171
174
175
176
Animation
Review
177
181
182
183
183
Keyboard Control
Mouse Control
186
189
187
192
193
194
195
196
Sprite Making
Making Asteroids
Review
199
196
197
200
202
203
205
205
206
Back to Class(es)
Sprite Class
210
206
210
Asteroid Class
Laser Class
Review
213
216
217
219
222
220
230
xi
Python 3x Programming
Lesson 19: Programming With Style
Python Style
PyScripter Style
232
PyGame Style
234
233
235
237
Choosing a License
Looking for Approval?
240
245
237
238
244
Mini Challenge
The Superman Challenge
246
246
247
249
250
256
New Vocabulary
Final Beginners Test
259
255
257
258
260
263
265
269
268
xii
273
274
xiii
ACKNOWLEDGMENTS
It is not possible to acknowledge by name everyone who has influenced me in writing this course. So, I will
have to offer a generic thank you and acknowledge those unknown people who influence me along the
way. I would like to acknowledge the people at Python.org for their unwavering support for Python
programmers. I would also like to acknowledge those throughout the Python community who may have had
a part in providing or influencing some of the code used in this course.
The next page is intentionally left blank just to bother people.
You will always wonder.
Python 3x Programming
Introduction
You
The unexpected popularity of my mini-book on Python programming combined with constant requests to
write a more in depth course; inspired me to write this one. The first book, Start Here: Python
Programming Made Simple for the Beginner was a free introduction to Python programming. I had no
idea that over 10,000 copies of this short e-book would spread worldwide in the first two months from
one unknown website. This opened my eyes to the need for programming books and courses that teach
Python in an interesting or at least different way.
This book includes an updated, and re-written course that includes all the contents of the first book. So, it
is unnecessary to read that book first. You can begin here. Content changes and improvements have been
made to each chapter and we go deeper into the world of Python in this course. I use the term course
rather than book because I have added some self-study exams, exercises, and quizzes. The intent is to
use this as a programming course for classrooms; and a resource for those who prefer independent-study.
When you finish this book, you will be able to do some programming in Python, make simple games,
package them, and be well down the road to being a great programmer.
Why isnt this course free like the first mini-book? My wife likes to eat, so I guess I should feed her once
in awhile. Unfortunately my time for free projects is limited.
The author, (thats me if you havent guessed already), believes the theory that visual learning, humor,
(emotional learning), interactive or conversational communication, and action, (experiential learning), are
some of the best ways for most people to quickly learn something. I attempt to be as brief as possible to
transform the reader into a competent programmer as fast as possible. This means I did skip things about
history, comparisons to other programming languages you probably dont know anyway, and anything
else that may slow you down, (other than humor and visual elements to help you remember things and
Sincerely Mine,
Jody S. Ginther
Python 3x Programming
Who cares? I just want to get into programming quickly! Then skip this part. The author,
(Jody S. Ginther), chose to include only a few useless details about himself that you probably dont care
about anyway, (yeah its a man with a girls name, kind of like Jackie Chan). If you must know a little
about him; he has taught internationally at major universities for over 17 years, (Jody not Jackie Chan).
He has a wide range of interests and has taught computers, programming, math, business, science,
languages, and martial arts. He has and continually researches effective learning methods to speed up the
learning process. His hobbies include; programming, learning new things, directing, writing, art, playing
drums, guitar, piano, singing, making movies, cartoons, and acting. Anyway, enough meaningless drivel
about that guy, the focus in this course is not on useless information about that one, but is all about:
turning
you
into a
Python 3x Programming
Even if you read my previous short e-book; Start Here: Python Programming Made Simple you should
still begin at Lesson 1 in this course. One reason is because it is always good to reinforce and review even
if you already read most of this information. But most importantly, new information and expanded
explanations have been added that may be important to you.
If you are an experienced programmer jump around at will to the parts you dont know; need to review;
use this as a reference; or just read everything anyway for its entertainment value.
If you are new to programming this is the course to begin with. Although the lessons in this course have
been made simple to understand; keep in mind that intermediate and advanced programming is not so
simple when you are new to it. But, just as any skills or talents, anything you practice enough will
become easier and more simple as you become a master. A master is someone who has done some skill
so many times; it looks easy and has become easy for them to perform and teach.
Dont just read the book unless you plan to read a lesson one time through and go back to do it the second
time through. Just as speaking any language can only truly be learned by speaking it; learning a
programming language can only be mastered by doing it. Each code example is intended for you to do,
not just to read. You will be surprised that things you thought looked too simple to bother typing, need to
be practiced. The elimination of a space or a mild typo will destroy your program. You must practice as
much as possible until you are a code perfectionist. This will save you countless hours of debugging or
fixing your code and will radically lower your level of stress.
In this course, self-testing proficiency exams and quizzes are provided to help you understand how well
you know the information that has been covered to that point. Depending on your style of learning, you
could approach these lessons in different ways :
1. The best way for most people is to do each lesson, type, (dont copy and paste),
all code as you follow along. Why? To re-enforce what you learn by doing it, and
because the most common errors in programming come from typing and
copying mistakes. If you dont completely understand the lesson, repeat it until
you do before going on.
2. If you are the kind of person who gets bored easily and need an overview before
you will remember things; use this approach: Read the lessons, do copy and
paste code where you can, and fly through the book to get an overview. Return
to the beginning and do the lessons slowly and type all the code for practice and
mastery. Repeat the lessons until you master them.
Programming is learned best by doing it until you got it. Some people find that having an
overview of the entire course and coming back to practice is a better approach. If you have a teacher or
3
Python 3x Programming
instructor for this course, then you should trust their experience and judgment. They will have specific
objectives and a specific time frame planned for you. In this case you have the following choices:
1. Listen to your instructor.
2. Fail the class.
3. Learn it your own way and gamble with your grades.
The exercises provided should be repeated and altered at will until you reach a point of confidence and
understanding. Dont just copy the code in the book, play with it.
Keep in mind that one of the primary purposes of this course is to give you some confidence in doing
some simple programming while giving you an overview of Python.
You can dive into the deeper depths of every topic within this course as you feel ready to do so. To reach
more advanced levels of programming see python.orgs website; visit Python communities; advanced
books; Python 3x or newer code exchanges; online resources, resources in Index C of this course,
Pythons documentation, python.org and www.toonzcat.com .
Other Uses for this course:
Of course, there are other uses for a book or course if you have a creative mind. My wife thinks books are
where you put the hot frying pan so it doesnt burn the table. I once had an interesting experience when I
taught my first class in China; that opened my eyes to other creative uses for a book:
Setting: One of the most famous Universities in China. Sometime after the Qing Dynasty.
Daytime.
I had just eaten some, not so safe local food, giving me a new definition to the term fast
food. I desperately searched for a bathroom on my way to class. Surprise one
happened when I opened the door of the stall. I expected to see a friendly toilet; in its
place was a porcelain lined hole in the floor. But this was a desperate situation; I had no
time to contemplate neither the reasoning behind someone stealing the toilet nor the
philosophy behind lining the hole in the floor with porcelain. With some relief everything
quickly came out OK. Then came surprise number two. I looked around for toilet paper.
It was at that memorable moment in my life when I discovered a difference in our two
cultures. In China, you are expected to bring your own toilet paper. Caught with my
pants down, I looked at the time and saw I was about to be late for my first class. I
frantically looked around the cubical for alternatives.
I entered the classroom as the bell was ringing, just in time! I went to the podium,
cleared my voice, and declared; For this lesson we will go directly to chapter 2;
chapter one has been chosen to serve a higher purpose.
Python 3x Programming
Even the importance of a simple insect can radically increase as our minds become
desperate to fly around real, imagined, and internal realities as a welcome escape from
focusing on one topic too long.
Python 3x Programming
The higher the emotions are when you receive the new information,
the easier it will be to remember. I call this emotional learning.
think of funny, interesting or emotional things while learning.
background while studying can help. The music must be gentle, quiet,
and not distracting. I find solo piano or guitar works best.
Alpha brain wave states; a relaxed state of mind can help you learn
faster. When you first wake up or are about to sleep, your brain can
retain information better. Generally, this is because your brain is in
an alpha state. We have all experienced hearing some song in the
morning and even if we hate the song, it is stuck in our head all day.
We even get disgusted when we catch ourselves humming it. The first
things you do in the morning and the last things you do before sleeping
can more easily be retained.
I wont go into the research and verification of these learning methods. You will just have to believe me
or go do some research yourself. This course is about programming so we wont spend much time on the
research end of faster learning. Just try these methods and you will see a difference in your ability to
retain new information. Believe it or not.
I also find it is useful to read and record information into an mp3 file to use for passive learning. You can
listen to the new vocabulary and concepts while driving, walking, exercising, etc.
Python 3x Programming
Programming is the art and science of making the computer do what you want it to do by creating
programs. Computers are stupid and dont understand English. So, we have to use computer languages to
translate what we say into Computerish. Actually, the language computers speak is referred to as a binary
language. Binary language is a language based on two words; on and off represented by the numbers
0 and 1. Humans have trouble communicating in binary.
If I said,
011 001 101
Huh?
you would say,
I can understand binary...now
whos the stupid one?
Python 3x Programming
Human Language
Binary Language
The language of
Machine Language
0s and 1s
1100101000110
0011100111000101
Interpreter or
Compiler
Interpreters and compilers both translate high level language code into low level binary code so the
machine can understand it. However, they do the same job in different ways. Why two different
approaches? Using a compiled language will generally result in faster running code. While using an
interpreted language will generally result in less time for the developer to write and debug the code.
C om piler:
10
Compiled Languages:
C om piler
E ntire Object
C ode for Execution
High Level
Source Code
Machine
Understands
Entire code
translated......
LIST OF ERROR
MESSAGES
Int erpreter
>>>
Intermediate
source code
High Level
Source Code
line by line...
Dont be impatient,
wait your turn!
Machine
Understands
Li ne by Line Execution
An interpreter reads
the high level
language code line by
line and executes it in
sequence. When it hits
an error it stops
running and does not
save the interpreted
code to an exe.
STOP
>>>
ERROR
MESSAGE
11
Python 3x Programming
Python is an interpreted language. It does not need to be compiled before running it.
So what does this mean for you? It means you save a step and some time. You dont have to send your
code through a compiler before you can run it and test it. Python even allows you to run small amounts of
code in an interactive or instant manner as you write it.
Python simplifies some tasks in programming and is more readable to humans than many programming
languages. Since code can be packages into moveable modules it can also save time by allowing you to
reuse clones of code modules rather than rewriting them from scratch.
So, what is Python used for? Python is use for anything from games and data base programs to web
applications. It is used from the New York Stock Exchange to NASA.
Python is considered a valuable tool and is used by many programmers throughout the world. Best of all,
Python is easier to learn than most programming languages and is open source! So, lets get started!
Note: To read the history of Pythons development, refer to doc umentation at Python. org.
Getting and installing Python
P yt hon i s free. Download it from python.org. I used Python 3.2 for most of this course and played a
little with 3.3. As you read this, a newer version may be available. I suggest choosing the latest stable
version for your operating system. When using additional stuff like PyGame make sure it is compatible
with the version of Python you are using. I primarily used Python 3.2 because it was thoroughly tested
and compatible with the other software I used in these lessons. There were major changes made from
Python 3 on, so backwards compatibility is limited. This course is not intended to be used with earlier
versions of Python. Follow any special installation instructions you may need and check for the latest
versions at:
http://www.python.org/download/
12
IDLE acts as your interpreter and translates what you say into a language that the computer can
understand. If you really want to know, IDLE stands for Ineractive DeveLopment Environment. Why
did they choose the L in the middle of the word, development? I have no idea and its not important for
the purposes of this book, so lets move on and get over it.
There are two windows to work from in IDLE. There is the Edit Window and the Shell Window. The
Python Shell window will say, Python Shell at the top of the window, while the Edit window will say,
Untitled and have a run command listed on the top menu bar. If Python starts in the Shell Window
and you want to use the Edit Window, just choose File<New Window and it will open an Edit Window.
If you want to use the Shell Window from the Edit Window go to the Run menu at the top of the
window and choose Python Shell.
The Python Shell is an interactive interpreter. This means that when you press the enter key, it checks
your source code and may give you some feedback. If you see (>>>), this is the first command prompt. It
is letting you know the interpreter is patiently waiting for you to type something. If you see (), this is
the secondary prompt waiting for you to type something more.
The Python Shell looks like this:
There are other editors that you can use for programming but to keep things simple in this book we will
use IDLE for nearly everything. Besides, its already packaged with Python. Remember that if you chose
to use another text editor; you should stick to specific or simple text editors. Editors like notepad rather
than one that will mess up your code by adding textual elements or applying unwanted formatting, (like
Microsofts Word program). We will discuss other useful editors later in the course.
13
Python 3x Programming
Why are there two windows in IDLE and how do I use them? Python allows you to work in script mode or
in interactive mode. Whats the difference?
Script Mode is great for writing programs you can save and run later. It is generally used for the final
product. You are running Script mode when you are in the Edit window.
Interactive mode is for testing and trying small ideas quickly. You are running in interactive mode
when you are in the Shell window. Most people use both of these together. Script mode for working on
their main program and interactive mode for trying new ideas; in the same way you would use a piece of
scratch paper.
A third function of IDLE is that it is also a debugger. You can find the debugger button at the top of the
Shell window. Whats a debugger? Its a program to help you find bugs. No not the one crawling up your
leg or living in your hair; but the bugs, or problems, that are in the code we are working on. Why are
computer problems called bugs? Computer history tells us that one of the first major computer crashes
was caused by an actual bug getting toasted on the circuit board of a computer; hence they named
problems in programming computers as bugs. We will go deeper into that story later.
Did you notice that IDLE changes the colors of your text? Whats the meaning? Lets look at a list of
some of the most common syntax colors and their meanings in IDLE.
orange
green
red
blue
black
You neednt memorize these at this point, but knowing the meaning of the colors can help you see clearly
where you typed something wrong.
14
If you were trying to type a string and its not green, you probably forgot the quotation marks or did
something else the computer didnt like. Dont worry, I will tell you what a string is later. The colors can
also be changed according to your personal preferences and may vary in different editors.
>>>code
While we are looking at the windows, how is your text arranged? The text is arranged in lines, groups,
and blocks. A block is just a group of code that goes together. Like a city block, it can be divided into
smaller groups like houses on the block, cars on the block, people, dogs, lions, cockroaches; etc. on that
block. This concept is important to tell the computer how to read and follow your code. To a computer,
arranging your code with the proper grouping of lines and blocks is like a map that says; first do this,
second do that, or repeat this part. It can also give directions like a map within your program by saying;
2 spaces
4 spaces
8 spaces
The number of times we indent helps the computer know how we are grouping the information.
(Hang in there, a few more ideas and you will make your first game).
15
Python 3x Programming
Block 2
Block
3
16
Each block of code can reside and work within another block of code.
Block 1
Block 2
Block
Quiz 1:
Answer the following questions on a separate piece of paper or in a document if you prefer. Check your
answers on the next page.
1.1 Define the following terms:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
Algorithms
Block
High Level Language
IDLE
Interactive Mode
Programming
Python Shell
Programs
Script Mode
Source Code
1.2 Questions:
1. Whats the difference between an interpreter and a compiler?
2. Which one does Python use?
3. Why is indentation important?
17
Python 3x Programming
Vocabulary
Algorithms are sets of instructions that tell the computer what to do.
Block is just a group of code that goes together.
High level language is a computer language that is closer to human language and easier for us
to use than low level or machine languages.
IDLE is software, (an editor), that helps you to communicate with the computer.
Interactive mode is for testing and trying small ideas quickly.
Low level languages are used when the programmer wants more direct control over the
machine he is using.
Programming is the art and science of making the computer do what you want it to do by
creating programs.
Programs are algorithms and source code packaged together to achieve your objective(s).
Python Shell is an interactive interpreter.
Script Mode is great for writing programs you can save and run later. It is generally used for the
final product.
Source Code includes all the algorithms or instructions written in a particular programming
language
Quiz 1 Answers:
1.1 Refer to the vocabulary terms chart above.
1.2
1. Compilers translate all the high level code into object code before
running the program. An interpreter reads the high level language
code line by line and executes it in sequence.
2. Python is an interpreted language, therefore it uses an interpreter and
has no need for a compiler.
3. Indentation tells the computer how to group the code into blocks that will be run in a particular
order.
18
Python 3x Programming
If you type the # key in front of some text, the computer ignores the text. This is useful for adding
comments in your programs that will not be misunderstood as instructions by the computer; or if you just
feel like being ignored. Ah, our first error message. Get used to these because they are the programmers
constant companion. In time, you will see them less and understand they do have a purpose other than
raising your blood pressure.
We will be explaining more about this code shortly; for now I just wanted you to type something and get
the feel of the shell.
Variables X
Have you ever asked; When am I going to use this kind of math? Now that you are a programmer you
should remember some simple math concepts to make your life easier. Dont worry, Ill be brief. You
dont have to remember complex math at this point, but higher levels of math will definitely increase your
programming skills. For now all you need to know is the world of math has animals called operators
and variables. In programming we use these same mathematical concepts and math-like logic when
designing algorithms.
Variables are like little like boxes or containers to put different things in. In math your teacher may have
told you that 1 + x = some other number. The 1 is an integer, (a complete number as opposed to part of a
number like ), and the x is a variable. In programming, you get to name your variable anything you
want. You can create an imaginary box with anything you want to put in it, and define/label that
imaginary box, (or variable), by any name you choose.
20
This means a variable in programming can refer to or contain integers, strings, and some other data
creatures you will be meeting as we continue on this path into the world of Python. Lets try it. Lets
imagine a box of chocolate. We want to tell the computer that the box labeled chocolate has happiness
and joy inside of it. To do this we use the = sign to define what our variable means for the computer to
understand us.
In the Python shell window type:
Chocolate = happiness and joy
Hit the enter key.
Now, lets type the word without quotes;
Chocolate
Hit enter.
Your computer should reply, happiness and joy
You just defined a variable and then called it. This is very useful in programming. You will constantly be
teaching the computer how to think as you write programs and will define things for it.
Variables are chunks of data stored in the computers memory. There are generally three types of data
stored in variables. Variables can be in the form of integers or in a string as mentioned previously.
Another type of data, called a float, refers to the non-whole numbers like decimals. Remember to use the
= sign to assign a variable. If you want the computer to think the variable x means 5 is in the variable box
named x, then you type:
x=5
Now the computer holds a 5 in memory and when you type or call an x, it tells you 5 when you hit the
enter key. What if you want to name a variable now, but you want to assign a value or put something in it
later? One way is to assign the no value, or None. You could do it this way:
x=None
You can then overwrite or replace the value None later. There are times when you write code but
dont know what value will be placed in a variable. All you have to do to delete and replace the word
None with the value, (or to overwrite it); is type it with the new value you want to assign to it, (in this
case 23):
x=23 #(overwrites the old x value)
21
Python 3x Programming
and
c o ntinue e x cept
g lobal
l a mbda
as
def
if
N one
a s sert
b r eak e lif
F a lse
del
f i nally
for
in
i mport
not
p a ss
w h ile
r a isew i th
n o nlocal r e turn y i eld
T r ue
If you should accidentally, (or just out of rebellion), use these words something like this will happen:
c l ass e lse
f rom
is
or
try
SyntaxError: invalid syntax... is Pythons ways of saying, Hey, you dont know what you
are talking about and neither do I! Speak Python! Dont take it personal, as a programmer you will get
used to these insults. You will find your computer has an attitude. Dont begin a variable name with a
number. The name 34th_apple would not be accepted by Python. Underscores are allowed. There are
also other illegal characters you cant use because they are used for other things in Python. Like the dollar
sign, ($).
Python is case sensitive, so remember when you used capital letters. It also pays
attention to blank spaces.
Other than these minor rules, you can name a variable anything you want. To sound more like cool geeks,
we dont always call them names, we sometimes call them identifiers. Remember that identifiers are
just the names we give to our containers.
22
Operators
Operators do something, like add, multiply, divide, subtract, or compare.
Notice that we already used the = sign to assign an identifier. So, we cant use the equal sign as an
operator. Instead we must use == to mean the; equals symbol in normal mathematics. What other useful
things can be done with operators? In the Python shell type:
words words words words words
Hit enter and type:
words *10
Hit enter.
Which is easier? If I knew this in primary school I could have really saved countless hours and gone
home at the same time as the other kids. I could have just written:
I will not run on the desks nor refer to my teacher as something I saw floating in the toilet. * 1000
Of course, at that time my teachers preferred to see my handwriting rather than a print-out. Operators are
life saving tools for the programmer. A good programmer in Python will rarely type the same code more
than once. As you guessed by now, the asterisk * symbol is used to express multiplication and to repeat
things. You could use it to repeat a string or tuple for a specific number of times. Remember to add a
space at the end of words before the closing quotation marks or your 10 words will look like one
long one.
+
/
*
for addition
for subtraction
for division
for multiplication
You can also use operators with strings of data. Try it. Make two strings with any words you want
between quotation marks and add them together. Like this:
23
Python 3x Programming
We also have comparison operators foryou guessed it; for comparing things!
Here are some of those:
> for greater than
< for less than
<= less than or equal to
>= greater than or equal to
= = equal to
! = not equal to
Remember that we already used the = symbol to define or tell the computer the meaning of our variables.
So we dont confuse our little computer, we must use double equal signs = = to express the traditional
meaning of equals to.
Now try some of these until you get bored. Any math expression will do. But wait! Use only integers; no
decimals at this point.
Due to the way a computer deals with floating point numbers, (numbers with a decimal point); you wont
always get the same results as a calculator. Use a . in all floating point numbers to solve this problem,
(1.0, 0.234).
For now, remember that Python is not your math teacher; although they may look similar. In math, 7.0 is
still an integer because numbers like 0, 5, 177, are integers. But computers are not so clever, so in Python
the number 7 is an integer but since 7.0 includes a decimal point; its called a floating point number.
Logical Operators
The words and, or, and not are logical operators. Logical operators are for comparing and
establishing relationships. A simple condition is a comparison that only uses two values:
9<19
A compound condition is a comparison using more than two values:
x < 10 and x>5
These logical operators generally mean the same thing in programming as they do in English.
24
But, what exactly is an expression in Python? Shorty you will also run into the word, statement. You
know what they are in English but in programming they have special meanings. An expression is any
combination of values, (numbers), that can evaluated into another single value, (number). This is just a
fancy way of saying; In 3 + 2 =5 is an expression. A statement can be instructions that evaluate into a
single value or a expressed fact, (just as in English). If you wrote a line in your game like: If the
spaceship hits an asteroid, they both explode. This would be a statement.
Now that you are a programmer, your whole life will be about the pursuit of truth,
(or not). You will be converting every problem and task into true, false, and logical
sequences.
Lets play with some of this new knowledge. Open IDLE and type the following, but feel free to play
with your own ideas after you try these:
8>3
Hit enter.
Ah, the computer agrees, it says, True.
3>8
Hit enter.
Hey! The computer just said, False.
I told you the computer has an attitude! Finding Boolean values of True or False is vital to the
programmer.
To see if and expression is true or false you can compare the values in the expression using ==:
7==7
>>> True
7==4
>>> False
25
Python 3x Programming
Introducing Strings
If you noticed I typed the words hey look a programmer in quotation marks. Later I used; single
quotation marks and got the same exciting result. When we hit enter, the computer just repeated what we
typed back to us. It printed the characters as output on the screen. A sequence of characters, words, or
sentences like this one is called a string. When we use single or double quote symbols to tell the
computer what is in our string, we call these quotation symbols delimiters. We tell the computer that we
are entering or ending a string by using single or double quotation marks. The computer dont care
which kind you use as long as you are consistent in pairing them. We can now say we have declared or
delimited the string, (a fancy way of saying we put it in quotation marks). You did what to that string?
Yes, you delimited it and there is nothing to be ashamed of. In IDLE strings are green and the output is
blue. The error message is red.
You can also add strings together using a math operator. We will talk more about that in a moment.
Putting the string cool with cat produced coolcat. If I want a space between them when they are
added together, I should add one in my string; cool +cat or cool+ cat would generate cool
cat, because in the first one I added a space after cool and in the second one I added a space before
cat.
What happened when I typed, wow? The computer said;
Blah blah blahis not defined.
This is the computers way of saying; huh? I dont understand. Python attempts to give you an idea of
what went wrong. When I typed the word, I did not include it inside quotation marks to tell the computer
that I was entering a string. So, the computer went, Huh? Not defined means that you did not tell the
computer the meaning of wow. You did not delimit it nor did you define it for the computer by putting
it into quotation marks.
26
We can reuse our string and add more values. We can also add multiple placeholders in the
same string as follows:
Sometimes you may want to use punctuation marks that Python sees as having another meaning.
As you have seen, programmers assign other meanings to traditional characters.
True and totally useless story: I once asked two students to tell their meaning of the word; love. One
student rolled up her eyes, cooed and softly whispered, Wonderful.
The next student stood up, violently swung a fist in the air and yelled; Pain! Death! Misery!
The same word; but two people had two very different meanings.
Just as two different people can see different meanings in the same word; Python must also be
told which meaning we want to use if we have more than one.
Now to escape! There are escape characters in Python to tell the computer to ignore the Python
code meaning of the character and see it as normal punctuation.
The escape character tells Python to stop or continue to read the code through the eyes of
Python. In this case we will use a pair of backslash, (\x\), escape characters to stop and then to
continue Python thinking.
27
Python 3x Programming
Without the escape characters we would only see the word without the quotation marks in our output.
A single backslash \ can be placed at the end of a line of code as a continuation character.
This tells the computer to treat the continued line as a single line:
>>>stuff = This is a very very very long string that I typed here \
to make my point.
>>>print (stuff)
This is a very very very long string that I typed here to make my point.
>>>stuff = This is a very very very long string that I typed here \n\
to make my point, but in this case I want two lines.
>>>print (stuff)
This is a very very very long string that I typed here
to make my point, but in this case I wanted two lines.
28
If you ever find yourself in a situation where you need to use a lot of backslashes, (probably wont happen
until you get deeper into programming), you may have to tell Python to store all your backslashes as they
appear. Otherwise the backslash will have a different meaning to Python and it will eliminate some of
them as in the examples above.
You may need to do this if you want to output a DOS path in Windows. Messing with the backslashes in
C:\program files\put it here\folder\ would not be a good thing. For this we use an r to indicate our
string is a raw string literal. Yeh, I know, just a weird way to say, read and store it literally/as it is
written. Whats a string literal? A string literal is just fancy way to say; text or values between
quotation marks for Python to ignore. Notice in the following example how \n\ is ignored and printed as
you see it in the text.
>>>stuff = This is a very very very long string that I typed here \n
to make my point, but in this case I want two lines.
>>>print (stuff)
This is a very very very long string that I typed here
to make my point, but in this case I want two lines.
29
Python 3x Programming
Review:
Quiz 2:
Answer the following questions on a separate piece of paper or in a document if you prefer. Check your
answers on the next page.
2.1 Define the following terms and check your answers on the next page:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
Boolean
Comparison operators
Compound condition
Delimiters
Float
Floating point numbers
Identifiers
Integer
Logical operators
Operators
Simple condition
String (not the one your cat plays with)
Variables
30
Vocabulary
Boolean data type is referring to two possible values; True or False.
Comparison operators are for comparing things, (<, >, ==, !=, etc.).
Compound condition is a comparison using more than two values, (x < 10 and x>5)
Conditional expressions (also called Boolean expressions), are based on the condition that
something is either true or false.
Delimiters defining quotation marks to tell the computer we are entering a string.
Escape character tells Python to stop or continue to read the code through the eyes of Python
Float non-whole numbers like decimals..
Floating point numbers numbers with a decimal point
Identifiers are names
Integer a complete number as opposed to part of a number like
Logical operators the words and, or, and not
Operators do something, like add, multiply, divide, subtract, or compare.
Placeholder (%s) a symbol in our code that indicates a blank value
Simple condition is a comparison that only uses two values, (9<10)
String a sequence of characters, words, or sentences in quotation marks.
Variables are like little like boxes or containers to put different things in.
31
Python 3x Programming
32
Save your program and give it a name, but add .py after the name you choose. Then close Python.
Reopen IDLE and go to file, then recent files, and choose your program name.
Go to the run button at the top of the edit window and choose Run module.
When it asks you, How many eggs can you eat? type a number or a word. I typed 1000 green ones.
33
Python 3x Programming
It should respond and look something like this:
If your program didnt work, go back and make sure everything is typed exactly as I typed it, and make
sure you typed in the right windows. Before we go on to your first mini game I will explain more about
the program you just made.
amount=input ()
The above like was to do two things. We made up the name of a variable and called it amount. We also
used the input() command to tell the computer that the computer user would put some data into amount
variable/box.
print (Wow you can really eat, +amount)
This line was to tell the computer to print these words on the computer screen but to add our variable. Our
variable was called amount and now contains in memory whatever you typed for the input.
Change the lines above and make up your own mini programs to practice and see what happens.
When you are ready, go on to the next part and make your first mini game.
34
Conditional Statements
As a programmer you will often find yourself needing to use conditionals, (statements based on a
condition). If you eat 2000 candy bars: you will get sick. This kind of conditional statement is called an
if statement.
We will use the if and the elif statements to make your first simple game. Lets name your game; Fred;
The Middle Aged Alien Chicken.
To start programming I will make a note of the name of my game at the top of the window as a reminder,
using the # key.
Enter the following code and then we can play and explain it:
Make sure you are in the right window and that you type everything exactly as you see above. Then click
on run and run module to try it. Enter a number and it will give you a reply. Enter another number and
...ahh!! it just repeats what you entered! You close the game and run it again to try again. So, at this
point, you can only make one guess before the game replies and stops working. Dont worry; we will fix
that in a moment when you learn about loops. For now, I will explain the code we have so far:
#Fred The Middle Aged Chicken
Again the # sign makes this information to ignore for the computer, but a reminder or information for us
humans and aliens who know how to read.
print (How old is Fred the alien chicken? )
This tells the computer to print the string of characters inside the ( ) to the screen.
number=17
This tells the computer that the variable we called number will mean 17.
35
Python 3x Programming
36
print (No way, that is too old to be a middle aged alien chicken )
Again, we indented and told the computer to print a string of characters.
Remember pages ago when we talked about blocks? You were younger then, but maybe you remember.
Well, we need to review that stuff and expand on the meaning to be able to teach you about loops. Only then
will you know how to fix our games problem of stopping after one guess.
Most of this code was already explained, so we will just look at the changes and the new things. You
didnt need to type any of the red comments for your code to work. These were just there to help you. The
spaces are also ignored by the computer and are placed in code to make it easier for humans to read. The
indentations are important changes. We will discuss those in a moment. Now, if you try the game, you
can continue guessing until you guess correctly. The game will only end when you guess the correct
answer. Play around with the game and the code before moving on.
37
Python 3x Programming
The code:
run=17
Here we named another variable called run, and told the computer that it also means 17.
while run:
The while statement is known as a looping statement. It tells the computer to repeat the next block of code
as long as it continues to be true. Notice the empty line after the line of code with the while statement. In
this example, I used a blank lines before and after the block of code that the while statement applies to.
This entire block will continue to repeat forever until the run variable becomes false. So, the meaning of
this would be to repeat the next block of code while the run variable is true; then, (:), do this... Here
we can add if or elif statements to tell the computer when our run variable is true or when our run variable
becomes false. If the run variable becomes false, our while run loop is no longer true and will stop
looping/repeating.
if guess==number:
This means that if the guess, (input), really equals, (==), the number, (17), then, (:)...
39
Python 3x Programming
What will the following code do ? (Dont try it yet, just think about it.)
x = 0
while x < 12:
print(x)
*Remember that to type all of this in and run it you need to open a new window in IDLE. Dont try to use
the Shell window because you will not be testing and running it line by line.
If you didnt listen and actually ran this, you found that it will loop eternally and you have to kill it by
closing the window. The better way to kill an eternal loop is to hold down the control key and hit the
c key at the same time. Now that you know a better way to kill it, you can give it a try.
Why? Well, in the print function we told Python to print x, which is = to 0; and we told the loop to
continue while x or 0 is less than 12. Zero will always be less than twelve so the loop will repeat forever
until the user interferes to kill it.
Ok, now you know. Try this one:
x = 0
while x < 12:
print(x)
x = x + 3
Before running it, what do you think will happen?
(Dont move on to the next page until you have a theory.)
40
TIME:
print(0)
prints 0
0 = 0 + 3
is 3 so...
... now make x = 3 for the second run through the loop:
This loop will repeat and run again until x is no longer
less than twelve.
SECOND TIME:
41
Python 3x Programming
Running through the loop the
x = 3
while 3 < 12:
SECOND TIME:
print(3)
prints 3
3 = 3 + 3
is 6 so...
... now make x = 6 for the second run through the loop:
THIRD TIME:
print(6)
prints 6
6 = 6 + 3
is 9 so...
... now make x = 9 for the second run through the loop:
FOURTH TIME:
print(9)
prints 9
9 = 9 + 3
is 12 so...
... now make x = 12 fo r the second run through the loop:
Wow! If we looped that much we would be dizzy. Fortunately, the computer can handle it and all that looping just
results in a simple output for us humans:
0
3
6
9
There are different ways to exit a while loop. One way is to just add the word break and the loop will
end at that point. Another common way to end a loop is to define when it is true and when it is false.
while done = = false:
for...(here I would enter my code block)
if...(this will repeat in the loop until it becomes true)
done = true (when done is true, we exit the loop, and are done with it)
Are you ready for a quiz? If not; go back and loop until you go it; if you think so; go on to the next page.
43
Python 3x Programming
Review
Quiz 3:
Answer the following questions on a separate piece of paper or in a document if you prefer. Check your
answers at the end of this lesson.
3.1 Define the following:
1. If statement
2. Loop
3. While statement
3.2 Answer the following questions:
1. Give two examples of conditional statements.
2. Correct the following portion of code (without referring to the text):
number = 17
run = 17
while run:
guess = int(input(Enter a number:)
if guess = number:
print Yes.
run = False
elif guess < number
CHALLENGE:
Write a while loop that does a countdown from ten to one and then prints, Go!
Check the end of this lesson to see one possible solution. *Hint: The break statement can be used to
break out of a loop.
44
Vocabulary
If Statement a conditional statement/ a statement based on a condition.
Loop when the computer goes back and repeats something in a cycle until something breaks it
out of that cycle.
While statement tells the computer to continue looping while some condition is continuing to
happen; usually while it is still true.
3.2 Answers:
1. if and elif, (you could also include else).
2. Obsessive attention to details and syntax must be developed as early as possible to
be a great programmer. It is better to spend time developing these skills than in
debugging messed up code after you write it. Prevention is better than repair but
both skills need to be developed.
Code:
Errors:
number = 17
run = 17
while run:
guess = int(input(Enter a number:) indent, quotation marks, parenthesis ))
if guess = number:
indent
print Yes.
indent, quotation marks around Yes
run = False
elif guess < number
indent, missing colon : after number
Challenge (one possible answer, (you figure out the correct indentation)):
x = 10
p r int(x)
if x < 1:
45
p rint("Go!")
b reak
x = x-1
Python 3x Programming
Lists
A list is a sequence of elements. A list is referred to as an array in some programming languages. You
could make a list of the family members in your home:
Family = [Dad, Mom, Brother, Sister, Me, Cat, Cockroaches]
Each element in the list has a position of reference. In other words, they are numbered for indexing or
referring to them later. The elements within the brackets are often called the index. But, instead of
calling the first element in the list; 1, programmers begin with 0. So, now you wont be confused if
you see a programmer counting how many cups of coffee he had tonight by beginning with; 0, 1, 2, 3...
Lists can store numbers, strings, both, and they can store other lists.
They may look like this:
Numbers:
Strings:
Both:
Other Lists:
theAlist=[ 2, 4, 6, 8 ]
theBlist=[words, abc, fuglet]
theClist=[abc, 4, words, 7]
AllLists=[theAlist, theBlist, theClist]
We can edit lists. But, the word edit is too common for a programmer to use, so lets use the word
mutable.
Later you will learn about tuples. Tuples are immutable. Huh? Mutable means we can edit it. Immutable
means we cant edit it. So the secret meaning is that lists can be edited; but strings and tuples cant be
edited, (directly).
46
www.Toonzcat.com
2013
Maybe you would like to edit your list of family members. Remember
our list:
Family =
Index position:
[ Dad,
0
Mom,
1
Cockroaches]
7
Lets say you bought a mouse and he ate the family cockroaches. It was a sad event but life goes on and
now you must edit your list of family members. You need to replace Cockroaches with psycho
mouse.
To replace an item in a list you need to understand what is in a particular index position. Index position
references begin before an item and at the comma after the item in the list. Since Cockraoches is in the
6th position of our Family list, (remember you count from 0), we do this:
Family[6]= Psycho Mouse
Give it a try. First, define what is in your list by typing:
Family = [Dad, Mom, Brother, Sister, Me, Cat, Cockroaches]
Then, type:
Family[6]= Psycho Mouse
Test it by typing:
print(Family)
47
Python 3x Programming
What happens if I want to add something to my list? Adding something to a list is referred to as
appending the list.
Lets say that our Cat and Psycho Mouse got married and had a baby. We will call it, Cathouse. Now
we have a new member of our family and we must append the list.
We add this line before our print statement:
Family.append(Catouse)
Run it:
How do I remove an item? Im glad you asked. Lets say that Psycho Mouse gets angry and eats the Cat.
To remove Cat from the Family list we use del for delete and give the index position:
del Family[5]
48
Just to complicate our lives, our sister marries a guy and now another family has become part of our
family. Fortunately, adding two lists together is easier than combining two families. First we define what
is in the second list. Lets add this list second family list under our Family list:
Family2=[a guy, dog, father, mother]
Then to add the two lists change the print statement to:
print(Family+Family2)
49
Python 3x Programming
Slices
Remember how we used an index to cut one part of a list out to exchange it or delete it?
Wouldnt it be great if you could choose any part of the list or a string; one character; half of an index; all
of the list; or any part you want to copy or work with? You can! A slice is cutting a list into smaller
parts. A slice is a subset of a list or a string. Just as you can choose what piece of pie you want to cut and
how big you want to cut it; you can cut a slice from a list or a string starting and ending where you want
it.
Lets cut up a string pie. Dont worry; you dont need to eat it. The strings always get caught between
your teeth anyway, (but they are good fiber). Remember that we use a 0 for our first index position. But,
when talking about slices of pie or strings you have to use two reference points. You need an index or
reference point for the first cut and one for the final cut of the slice. So, our index points are on eac h side
of the characters in our string.
If we want to slice out the s we have to tell the computer the beginning and ending index for the slice,
[0:1].
50
Try this:
Run it:
Im not sure what a rin tastes like but we successfully sliced a piece of our string from index position 2
to 5!
6 7
10
i e
You try a few to practice. First choose the letters you want to cut out of the string. Then choose the
beginning and ending cut for your slice of the string. Practice until you are confident in choosing the
index positions and getting the slice you want.
There is another way to refer to index positions in a slice if you want to use it. You can think backwards!
There are practical uses for this in more advanced programming.
For now, I will only introduce you to it and you can play with it. In this index system, index positions use
negative numbers.
0 1 2 3 4 5 6 7 8 9 10
s t r i n g
p i e
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1
51
Python 3x Programming
Try it:
Run it:
A tring p probably tastes better than a rin, but Im only guessing. When you program you will find
that making a copy of part or all of what you have typed before will save you a lot of time. Slicing strings
is a useful talent.
Practice 4.1 Do this:
Look at what we have done so far, and take a guess about what you think will happen before doing the
following:
1. What do you think happens if you create a string and you print [ :3] of that string?
2. What happens if you create a string and you print [3:] of that string?
Come on! Take a guess. Try it before looking at the answer at the end of the lesson.. Learning by doing it
and thinking about it makes things easier to remember.
Here are a couple more slicing operations you can play with:
>>> string1='pronounce'
>>> string2= 'deepfat'
>>> newstring = string1 + string2
>>> print(newstring)
pronouncedeepfat
52
In the previous example you can see how easy it is to create a new string variable that contains the
combined data of other variables.
>>> newstring = string1[:3] + string2[4:]
>>> print(newstring)
profat
If you put a
space here [4: ],
rather than [4:],
it will not work.
In the above example you can see how easy it is to create a new string that is a combination of parts of
other strings. These same slice operations work for lists. What is the difference when slicing lists or
strings? With strings each character and empty space is indexed as separate data. Lists are compound data
types where each chunk of data is indexed according to the location of the commas you used to designate
each item of data. In other words, with strings you would count index positions before and after each
character or empty space; with lists you would count index positions before the first item as 0 and at each
comma after each item in the list.
String index positions:
s
0
t
1
r
2
i
3
n
4
g
5
53
Python 3x Programming
You can also append, (add something to the end), a list:
>>> mylist = ['up', 'downerk', 377, '40']
>>> mylist.append('kitten')
>>> print(mylist)
['up', 'downerk', 377, '40', 'kitten']
You can:
Replace items in a list:
Remove items:
>>> mylist[0:2] = []
>>> print(mylist)
['pencil', '100', 'hat', 'horse']
Insert items:
54
>>> len(mylist)
28
Let's clear the list:
>>> mylist[:] = []
>>> print(mylist)
[]
You can now understand why lists will be one of your most valuable tools for manipulation of data. Play
and practice with these until you are confident.
55
Python 3x Programming
Tuples
Lets talk tuples! A tuple is like a list but cant be edited or changed, (immutable), in its original form. If
we really want to be able to modify tuple, we must convert it to a list by using the list(tuplename) first.
We generally use parenthesis, ( ), rather than brackets, [ ], to tell Python we are defining a tuple. If it is
very obvious to Python that it is a tuple, parenthesis can be skipped.
This is a string:
Family3 = creatures
This is a tuple:
Family3 = (a guy, dog, cat)
This is a list:
Family3 = [a guy, dog, cat]
Review
Quiz 4:
Answer the following questions on a separate piece of paper or in a document if you prefer. Check your
answers on the next page.
4.1 Define the following terms:
1.
2.
3.
4.
5.
6.
7.
Immutable
List
Mutable
Nested
Slice
Tuple
constants
4.2 Questions:
1.
2.
3.
4.
5.
4.3 Activity:
1. Practice making lists, appending them, and removing items until you are confident with indexing
references.
2. Make some tuples and convert them so you can edit them.
57
Python 3x Programming
Vocabulary
Immutable means we cant edit it.
List a sequence of elements
Constants are read only data
Mutable means we can edit it.
Nested, (placed), inside
Slice a subset of a list
Tuple like a list but cant be edited or changed in its original form.
4.2 Answers:
1.
2.
3.
4.
5.
4.3 Activity
Answers will vary. Refer back to the lesson examples if you dont fully understand.
Practice 4.1 Answers:
1. [:3] produces everything in your list up to index position 3.
2. [3:] produces everything in your list after index position 3.
Remember to type the syntax correctly.
>>> mystring = 'astring'
>>> print (mystring [3:])
ring
>>> print (mystring [:3])
ast
58
Whats a Function
Making Your Own Functions
Arguments And Parameters
Docstrings and Suites
global and Local scope
Whats a function?
Again; a function is a re-usable mini program inside of your program. One of the greatest things about
functions is that you never have to repeatedly type code, if you need to repeat it, let a function do it. You
have already been using functions throughout this book. The print () function call for the print
function is the one you have used most.
Calling a function:
Is A. Function_home?
Am I turning you on?
59
Python 3x Programming
60
I hope you enjoyed this free mini-book. The full course can be
found by following the link at www.Toonzcat.com,
www.Quantum-Sight.com, or www.QuantumSight.mobi
61