Non-Programmers Tutorial For Python 3 - 2 Print Version
Non-Programmers Tutorial For Python 3 - 2 Print Version
Non-Programmers Tutorial For Python 3 - 2 Print Version
3/Print version
All example Python source code in this tutorial is granted 0.2 First things rst
to the public domain. Therefore you may modify it and
relicense it under any license you please. Since you are
So, you've never programmed before. As we go through
expected to learn programming, the Creative Commons
this tutorial, I will attempt to teach you how to program.
Attribution-ShareAlike license would require you to keep
There really is only one way to learn to program. You
all programs that are derived from the source code in
must read code and write code (as computer programs are
this tutorial under that license. Since the Python source
often called). I'm going to show you lots of code. You
code is granted to the public domain, that requirement is
should type in code that I show you to see what happens.
waived.
Play around with it and make changes. The worst that can
This tutorial is more or less a conversion of Non- happen is that it won't work. When I type in code it will
Programmers Tutorial for Python 2.6. Older versions be formatted like this:
and some versions in Korean, Spanish, Italian and Greek
##Python is easy to learn print(Hello, World!")
are available from http://jjc.freeshell.org/easytut/
The Non-Programmers Tutorial For Python 3 is a tutorial
Thats so it is easy to distinguish from the other text. If
designed to be an introduction to the Python program-
you're reading this on the Web, you'll notice the code is
ming language. This guide is for someone with no pro-
in color -- thats just to make it stand out, and to make the
gramming experience.
dierent parts of the code stand out from each other. The
If you have programmed in other languages I recommend code you enter will probably not be colored, or the colors
using Python Tutorial for Programmers written by Guido may be dierent, but it won't aect the code as long as
van Rossum. you enter it the same way as its printed here.
If you have any questions or comments please use the dis- If the computer prints something out it will be formatted
cussion pages or see Authors page for author contact in- like this:
formation. I welcome questions and comments about this
Hello, World!
tutorial. I will try to answer any questions you have as best
I can. (Note that printed text goes to your screen, and does not
involve paper. Before computers had screens, the output
Thanks go to James A. Brown for writing most of the
of computer programs would be printed on paper.)
Windows install info. Thanks also to Elizabeth Cogliati
for complaining enough :) about the original tutorial (that Note that this is a Python 3 tutorial, which means that
is almost unusable for a non-programmer), for proofread- most of the examples will not work in Python 2.7 and
ing, and for many ideas and comments on it. Thanks before. As well, some of the extra libraries (third-party
to Joe Oppegaard for writing almost all the exercises. libraries) have not yet been converted. You may want
Thanks to everyone I have missed. to consider learning from the Non-Programmers Tuto-
rial for Python 2.6. However, the dierences between
versions are not particularly large, so if you learn one,
you should be able to read programs written for the other
0.1 Other resources without much diculty.
There will often be a mixture of the text you type (which
Python Home Page is shown in bold) and the text the program prints to the
screen, which would look like this:
Halt! Who Goes there? Josh You may pass, Josh
Python 3 Documentation
(Some of the tutorial has not been converted to this for-
mat. Since this is a wiki, you can convert it when you nd
A Byte of Python by Swaroop C H it.)
I will also introduce you to the terminology of program-
Porting to Python 3: An in-depth guide ming - for example, that programming is often referred to
1
2
as coding or hacking. This will not only help you under- Change to the directory and tell the computer to
stand what programmers are talking about, but also help compile and install the program
the learning process.
Now, on to more important things. In order to program $ cd Python-3.4/ $ ./congure --
in Python you need the Python 3 software. If you don't prex=$HOME/python3_install ... lots of output.
already have the Python software go to www.python.org/ Watch for error messages here ... $ make ... even more
download and get the proper version for your platform. output. Hopefully no error messages ... $ make install
Download it, read the instructions and get it installed.
Add Python 3 to your path. You can test it
rst by specifying the full path. You should add
0.3 Installing Python $HOME/python3_install/bin to your PATH bash
variable.
For Python programming you need a working Python in-
stallation and a text editor. Python comes with its own $ ~/python3_install/bin/python3 Python 3.4.3 (... size
editor, IDLE, which is quite nice and totally sucient for and date information ...) [GCC 4.5.2] on linux2 Type
the beginning. As you get more into programming, you help, copyright, credits or license for more infor-
will probably switch to some other editor like emacs, vi mation. >>>
or another.
The above commands will install Python 3 to your home
The Python download page is http://www.python.org/ directory, which is probably what you want, but if you
download. The most recent version is Python 3.5.1 (as of skip the --prex=$HOME/python3_install, it will install
February 2016); Python 2.7 and older versions will not it to /usr/local. If you want to use the IDLE graphical
work with this tutorial. There are various dierent in- code editor, you need to make sure that the tk and tcl
stallation les for dierent computer platforms available libraries, together with their development les, are in-
on the download site. Here are some specic instructions stalled on the system. You will get a warning during the
for the most common operating systems: make phase if these are not available.
itor in Windows. How you get to this editor is slightly with new Python statements, go into interactive mode and
dierent on dierent versions of Windows. try them out.
On Windows 8: Press the Windows key and type Control
Panel to locate the Windows Control Panel. Once you've 0.5 Creating and Running Programs
opened the Control Panel, select View by: Large Icons,
then click on System. In the window that pops up, click the Go into IDLE if you are not already. In the menu at the
Advanced System Settings link, then click the Environment top, select File then New File. In the new window that
Variables... button. appears, type the following:
On Windows 7 or Vista: Click the Start button in the print(Hello, World!")
lower-left corner of the screen, move your mouse over
Computer, right-click, and select Properties from the pop-
up menu. Click the Advanced System Settings link, then Now save the program: select File from the menu, then
click the Environment Variables... button. Save. Save it as hello.py (you can save it in any folder
you want). Now that it is saved it can be run.
On Windows XP: Right-click the My Computer icon on
your desktop and select Properties. Select the Advanced Next run the program by going to Run then Run Module
tab, then click the Environment Variables... button. (or if you have an older version of IDLE use Edit then Run
script). This will output Hello, World! on the *Python
Once you've brought up the environment variable editor, Shell* window.
you'll do the same thing regardless of which version of
Windows you're running. Under System Variables in the For a more in-depth introduction to IDLE, a longer tu-
bottom half of the editor, nd a variable called PATH. If torial with screenshots can be found at http://hkn.eecs.
there is is one, select it and click Edit.... Assuming your berkeley.edu/~{}dyoo/python/idle_intro/index.html.
Python root is C:\Python34, add these two folders to your
path (and make sure you get the semicolons right; there 0.5.1 Program le names
should be a semicolon between each folder in the list):
C:\Python34 C:\Python34\Scripts It is very useful to stick to some rules regarding the le
names of Python programs. Otherwise some things might
Note: If you want to double-click and start your Python
go wrong unexpectedly. These don't matter as much for
programs from a Windows folder and not have the console
programs, but you can have weird problems if you don't
window disappear, you can add the following code to the
follow them for module names (modules will be discussed
bottom of each script:
later).
#stops console from exiting end_prog = "" while
end_prog != q": end_prog = input(type q to quit) 1. Always save the program with the extension .py. Do
not put another dot anywhere else in the le name.
2. Only use standard characters for le names: letters,
0.4 Interactive Mode numbers, dash (-) and underscore (_).
3. White space (" ") should not be used at all (use un-
Go into IDLE (also called the Python GUI). You should
derscores instead).
see a window that has some text like this:
Python 3.0 (r30:67503, Dec 29 2008, 4. Do not use anything other than a letter (particularly
21:31:07) [GCC 4.3.2 20081105 (Red Hat no numbers!) at the beginning of a le name.
4.3.2-7)] on linux2 Type copyright, cred- 5. Do not use non-English characters (such as , ,
its or license()" for more information. , , , , ) in your le namesor, even better, do
****************************************************************
not use them at all when programming.
Personal rewall software may warn about the con-
nection IDLE makes to its subprocess using this
computers internal loopback interface. This con- 0.6 Using Python from the command line
nection is not visible on any external interface and
no data is sent to or received from the Internet. If you don't want to use Python from the command line,
you don't have to, just use IDLE. To get into interac-
****************************************************************
IDLE 3.0 >>> tive mode just type python3 without any arguments. To
The >>> is Pythons way of telling you that you are in run a program, create it with a text editor (Emacs has
interactive mode. In interactive mode what you type is a good Python mode) and then run it with python3 pro-
immediately run. Try typing 1+1 in. Python will respond gram_name.
with 2. Interactive mode allows you to test out and see Additionally, to use Python within Vim, you may want to
what Python will do. If you ever feel you need to play visit the Python wiki page about VIM.
4
0.6.1 Running Python Programs in *nix Python wiki has a list of local user groups, you can
join the group mailing list and ask questions. You
If you are using Unix (such as Linux, Mac OS X, or BSD), can also participate in the user group meetings.
if you make the program executable with chmod, and
have as the rst line: LearnPython subreddit is another location where be-
ginner level questions can be asked.
#!/usr/bin/env python3
Now is probably a good time to give you a bit of an expla- Notice that there are two ways to do division, one that
nation of what is happening - and a little bit of program- returns the repeating decimal, and the other that can get
ming terminology. the remainder and the whole number. The order of oper-
ations is the same as in math:
What we were doing above was using a function called
print. The functions name - print - is followed by paren- parentheses ()
theses containing zero or more arguments. So in this ex-
ample exponents **
print(Hello, World!") multiplication *, division /, integer division //, and
remainder %
there is one argument, which is Hello, World!". Note addition + and subtraction -
that this argument is a group of characters enclosed in
double quotes (""). This is commonly referred to as a
So use parentheses to structure your formulas when
string of characters, or string, for short. Another example
needed.
of a string is Jack and Jill went up a hill. The combina-
tion of a function and parentheses with the arguments is
a function call. 0.11 Talking to humans (and other intelli-
A function and its arguments are one type of statement gent beings)
that python has, so
Often in programming you are doing something compli-
print(Hello, World!")
cated and may not in the future remember what you did.
When this happens the program should probably be com-
is an example of a statement. Basically, you can think of mented. A comment is a note to you and other program-
a statement as a single line in a program. mers explaining what is happening. For example:
Thats probably more than enough terminology for now. # Not quite PI, but a credible simulation print(22 / 7)
Which outputs
0.10 Expressions
3.14285714286
Here is another program: Notice that the comment starts with a hash: #. Com-
ments are used to communicate with others who read the
print(2 + 2 is, 2 + 2) print(3 * 4 is, 3 * 4) print(100
program and your future self to make clear what is com-
- 1 is, 100 - 1) print("(33 + 2) / 5 + 11.5 is, (33 + 2) / plicated.
5 + 11.5)
Note that any text can follow a comment, and that when
the program is run, the text after the # through to the end
And here is the output when the program is run: of that line is ignored. The # does not have to be at the
2 + 2 is 4 3 * 4 is 12 100 - 1 is 99 (33 + 2) / 5 + 11.5 is beginning of a new line:
18.5 # Output PI on the screen print(22 / 7) # Well, just a
As you can see, Python can turn your thousand-dollar good approximation
computer into a ve-dollar calculator.
6
surrounded by " or '. The other type of variables are num- Notice that number was created with oat(input()) while
bers. Remember that variables are used to store a value, text was created with input(). input() returns a string
they do not use quotation marks (" and '). If you want to while the function oat returns a number from a string.
use an actual value, you must use quotation marks. int returns an integer, that is a number with no decimal
value1 == Pim value2 == Pim point. When you want the user to type in a decimal use
oat(input()), if you want the user to type in an integer use
int(input()), but if you want the user to type in a string use
Both look the same, but in the rst one Python checks input().
if the value stored in the variable value1 is the same as
the value stored in the variable Pim. In the second one, The second half of the program uses the type() function
Python checks if the string (the actual letters P,i, and m) which tells what kind a variable is. Numbers are of type
are the same as in value2 (continue this tutorial for more int or oat, which are short for integer and oating point
explanation about strings and about the ==). (mostly used for decimal numbers), respectively. Text
strings are of type str, short for string. Integers and oats
can be worked on by mathematical functions, strings can-
not. Notice how when python multiplies a number by
0.15 Assignment an integer the expected thing happens. However when a
string is multiplied by an integer the result is that mul-
Okay, so we have these boxes called variables and also tiple copies of the string are produced (i.e., text * 2 =
data that can go into the variable. The computer will see HelloHello).
a line like rst_name = Bill and it reads it as Put the Operations with strings do dierent things than opera-
string Bill into the box (or variable) rst_name. Later on tions with numbers. As well, some operations only work
it sees the statement c = a + b and it reads it as put the with numbers (both integers and oating point numbers)
sum of a + b or 123.4 + 432 which equals 555.4 into c. and will give an error if a string is used. Here are some
The right hand side of the statement (a + b) is evaluated interactive mode examples to show that some more.
and the result is stored in the variable on the left hand
>>> print(This + " " + is + " joined.) This is joined.
side (c). This is called assignment, and you should not
>>> print(Ha, " * 5) Ha, Ha, Ha, Ha, Ha, >>> print(Ha,
confuse the assignment equal sign (=) with equality in
" * 5 + ha!") Ha, Ha, Ha, Ha, Ha, ha! >>> print(3 - 1)
a mathematical sense here (thats what == will be used for
2 >>> print(3 - 1) Traceback (most recent call last):
later).
File "<stdin>", line 1, in <module> TypeError: unsup-
Here is another example of variable usage: ported operand type(s) for -: 'str' and 'str' >>>
a = 1 print(a) a = a + 1 print(a) a = a * 2 print(a) Here is the list of some string operations:
3 Area: 12.0 Perimeter: 14.0 Calculate information = a + 1 |<--[ The while statement BLOCK ] # print (a) |
about a rectangle Length: 2.53 Width: 5.2 Area: 13.156 # --
Perimeter: 15.46
Temperature.py And here is the extremely exciting output:
# This program converts Fahrenheit to Celsius fahr_temp 1 2 3 4 5 6 7 8 9 10
= oat(input(Fahrenheit temperature: ")) print(Celsius (And you thought it couldn't get any worse after turning
temperature:", (fahr_temp - 32.0) * 5.0 / 9.0) your computer into a ve-dollar calculator?)
So what does the program do? First it sees the line a = 0
Sample runs: and sets a to zero. Then it sees while a < 10: and so the
Fahrenheit temperature: 32 Celsius temperature: 0.0 computer checks to see if a < 10. The rst time the com-
Fahrenheit temperature: 40 Celsius temperature: puter sees this statement, a is zero, so it is less than 10.
40.0 Fahrenheit temperature: 212 Celsius temperature: In other words, as long as a is less than ten, the computer
100.0 Fahrenheit temperature: 98.6 Celsius temperature: will run the tabbed in statements. This eventually makes
37.0 a equal to ten (by adding one to a again and again) and the
while a < 10 is not true any longer. Reaching that point,
the program will stop running the indented lines.
0.17 Exercises Always remember to put a colon ":" at the end of the while
statement line!
Write a program that gets 2 string variables and 2 number
variables from the user, concatenates (joins them together Here is another example of the use of while:
with no spaces) and displays the strings, then multiplies a = 1 s = 0 print('Enter Numbers to add to the sum.')
the two numbers on a new line. print('Enter 0 to quit.') while a != 0: print('Current Sum:',
Solution s) a = oat(input('Number? ')) s = s + a print('Total Sum
=', s)
Enter Numbers to add to the sum. Enter 0 to quit. Cur-
Write a program that gets 2 string variables and 2 number rent Sum: 0 Number? 200 Current Sum: 200.0 Num-
variables from the user, concatenates (joins them together ber? 15.25 Current Sum: 184.75 Number? 151.85
with no spaces) and displays the strings, then multiplies Current Sum: 32.9 Number? 10.00 Current Sum: 42.9
the two numbers on a new line. Number? 0 Total Sum = 42.9
string1 = input('String 1: ') string2 = input('String Notice how print('Total Sum =', s) is only run at the end.
2: ') oat1 = oat(input('Number 1: ')) oat2 = The while statement only aects the lines that are in-
oat(input('Number 2: ')) print(string1 + string2) dented with whitespace. The != means does not equal
print(oat1 * oat2) so while a != 0: means as long as a is not zero run the
tabbed statements that follow.
Note that a is a oating point number, and not all oating
0.18 While loops point numbers can be accurately represented, so using !=
on them can sometimes not work. Try typing in 1.1 in
Presenting our rst control structure. Ordinarily the com- interactive mode.
puter starts with the rst line and then goes down from
there. Control structures change the order that statements 0.18.1 Innite loops or Never Ending Loop
are executed or decide if a certain statement will be run.
Heres the source for a program that uses the while con- Now that we have while loops, it is possible to have pro-
trol structure: grams that run forever. An easy way to do this is to write
a = 0 # FIRST, set the initial value of the variable a to a program like this:
0(zero). while a < 10: # While the value of the variable while 1 == 1: print(Help, I'm stuck in a loop.)
a is less than 10 do the following: a = a + 1 # Increase
the value of the variable a by 1, as in: a = a + 1! print(a)
# Print to screen what the present value of the variable a The "==" operator is used to test equality of the expres-
is. # REPEAT! until the value of the variable a is equal sions on the two sides of the operator, just as "<" was used
to 9!? See note. # NOTE: # The value of the variable for less than before (you will get a complete list of all
a will increase by 1 # with each repeat, or loop of the comparison operators in the next chapter).
'while statement BLOCK'. # e.g. a = 1 then a = 2 then a This program will output Help, I'm stuck in a loop. un-
= 3 etc. until a = 9 then... # the code will nish adding 1 til the heat death of the universe or you stop it, because
to a (now a = 10), printing the # result, and then exiting 1 will forever be equal to 1. The way to stop it is to hit
the 'while statement BLOCK'. # -- # While a < 10: | # a the Control (or Ctrl) button and C (the letter) at the same
0.20 Exercises 9
Fibonacci-method1.py Write a program that asks the user for a Login Name and
password. Then when they type lock, they need to type
# This program calculates the Fibonacci sequence a = 0 b
in their name and password to unlock the program.
= 1 count = 0 max_count = 20 while count < max_count:
count = count + 1 print(a, end=" ") # Notice the magic Solution
end=" " in the print function arguments # that keeps it
from creating a new line. old_a = a # we need to keep Write a program that asks the user for a Login Name and
track of a since we change it. a = b b = old_a + b print() password. Then when they type lock, they need to type
# gets a new (empty) line. in their name and password to unlock the program.
name = input(What is your UserName: ") password =
Output: input(What is your Password: ") print(To lock your
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 computer type lock.) command = None input1 = None
2584 4181 input2 = None while command != lock": command =
input(What is your command: ") while input1 != name:
Note that the output is on a single line because of the extra
input1 = input(What is your username: ") while input2
argument end=" " in the print arguments.
!= password: input2 = input(What is your password: ")
Fibonacci-method2.py print(Welcome back to your system!")
# Simplied and faster method to calculate the Fibonacci
sequence a = 0 b = 1 count = 0 max_count = 10 while If you would like the program to run continuously, just
count < max_count: count = count + 1 print(a, b, end=" add a while 1 == 1: loop around the whole thing. You
") # Notice the magic end=" " a = a + b b = a + b print() will have to indent the rest of the program when you add
# gets a new (empty) line. this at the top of the code, but don't worry, you don't have
to do it manually for each line! Just highlight everything
Output: you want to indent and click on Indent under Format
in the top bar of the python window.
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
2584 4181 Another way of doing this could be:
5 The average was: 4.0 This program will take several grams you have probably found that sometimes the pro-
numbers then average them How many numbers would gram does something you didn't want it to do. This is
you like to average: 3 Number 1 Enter a number: 1 Num- fairly common. Debugging is the process of guring out
ber 2 Enter a number: 4 Number 3 Enter a number: 3 The what the computer is doing and then getting it to do what
average was: 2.66666666667 you want it to do. This can be tricky. I once spent nearly
a week tracking down and xing a bug that was caused by
someone putting an x where a y should have been.
0.23 Exercises
This chapter will be more abstract than previous chapters.
Write a program that asks the user their name, if they
enter your name say That is a nice name, if they en-
ter John Cleese or Michael Palin, tell them how you 0.25 What should the program do?
feel about them ;), otherwise tell them You have a nice
name. The rst thing to do (this sounds obvious) is to gure out
what the program should be doing if it is running cor-
Solution rectly. Come up with some test cases and see what hap-
name = input('Your name: ') if name == 'Bryn': pens. For example, lets say I have a program to compute
print('That is a nice name.') elif name == 'John Cleese': the perimeter of a rectangle (the sum of the length of all
print('... some funny text.') elif name == 'Michael Palin': the edges). I have the following test cases:
print('... some funny text.') else: print('You have a nice
name.') I now run my program on all of the test cases and see if
the program does what I expect it to do. If it doesn't then
I need to nd out what the computer is doing.
Modify the higher or lower program from this section to
keep track of how many times the user has entered the More commonly some of the test cases will work and
wrong number. If it is more than 3 times, print That some will not. If that is the case you should try and gure
must have been complicated. at the end, otherwise print out what the working ones have in common. For example
Good job!" here is the output for a perimeter program (you get to see
the code in a minute):
Solution
number = 7 guess = 1 count = 0 print(Guess the num- Height: 3 Width: 4 perimeter = 15 Height: 2 Width: 3
ber!") while guess != number: guess = int(input(Is it... perimeter = 11 Height: 4 Width: 4 perimeter = 16 Height:
")) count = count + 1 if guess == number: print(Hooray! 2 Width: 2 perimeter = 8 Height: 5 Width: 1 perimeter
You guessed it right!") elif guess < number: print(Its = 8
bigger...) elif guess > number: print(Its not so big.) Notice that it didn't work for the rst two inputs, it worked
if count > 3: print(That must have been complicated.) for the next two and it didn't work on the last one. Try
else: print(Good job!") and gure out what is in common with the working ones.
Once you have some idea what the problem is nding the
Write a program that asks for two numbers. If the sum cause is easier. With your own programs you should try
of the numbers is greater than 100, print That is a big more test cases if you need them.
number.
Solution
0.26 What does the program do?
number1 = oat(input('1st number: ')) number2 =
oat(input('2nd number: ')) if number1 + number2 >
The next thing to do is to look at the source code. One
100: print('That is a big number.')
of the most important things to do while programming is
reading source code. The primary way to do this is code
walkthroughs.
0.24 What is debugging? A code walkthrough starts at the rst line, and works its
way down until the program is done. while loops and if
As soon as we started programming, we found statements mean that some lines may never be run and
to our surprise that it wasn't as easy to get pro- some lines are run many times. At each line you gure
grams right as we had thought. Debugging had out what Python has done.
to be discovered. I can remember the exact in-
stant when I realized that a large part of my Lets start with the simple perimeter program. Don't type
life from then on was going to be spent in nd- it in, you are going to read it, not run it. The source code
ing mistakes in my own programs. Maurice is:
Wilkes discovers debugging, 1949 height = int(input(Height: ")) width = int(input(Width:
")) print(perimeter =", width + height + width + width)
By now if you have been messing around with the pro-
12
Question: What is the rst line Python runs? What does it do? Well, while statements in general
Answer: The rst line is always run rst. In this look at their expression, and if it is true they do the
case it is: height = int(input(Height: ")) next indented block of code, otherwise they skip the
next indented block of code.
What does that line do? Prints Height: , waits for the
user to type a string in, and then converts the string So what does it do right now? If number > 1 is true
to an integer variable height. then the next two lines will be run.
What is the next line that runs? In general, it is the So is number > 1? The last value put into number was
next line down which is: width = int(input(Width: 5 and 5 > 1 so yes.
"))
So what is the next line? Since the while was true the
What does that line do? Prints Width: , waits for the next line is: print(".,end=" ")
user to type a number in, and puts what the user
What does that line do? Prints one dot and since the
types in the variable width.
extra argument end=" " exists the next printed text
What is the next line that runs? When the next line is will not be on a dierent screen line.
not indented more or less than the current line, it is What is the next line? number = number - 1 since that
the line right afterwards, so it is: print(perimeter is following line and there are no indent changes.
= ", width + height + width + width) (It may also
run a function in the current line, but thats a future What does it do? It calculates number - 1, which is the
chapter.) current value of number (or 5) subtracts 1 from it,
and makes that the new value of number. So basi-
What does that line do? First it prints perimeter = , cally it changes numbers value from 5 to 4.
then it prints the sum of the values contained within
the variables, width and height, from width + height What is the next line? Well, the indent level decreases
+ width + width. so we have to look at what type of control structure
Does width + height + width + width calculate the it is. It is a while loop, so we have to go back to the
perimeter properly? while clause which is while number > 1:
Lets see, perimeter of a rectangle is the bottom What does it do? It looks at the value of number, which
(width) plus the left side (height) plus the top is 4, and compares it to 1 and since 4 > 1 the while
(width) plus the right side (huh?). The last item loop continues.
should be the right sides length, or the height.
What is the next line? Since the while loop was true,
Do you understand why some of the times the perime-
the next line is: print(".,end=" ")
ter was calculated correctly"?
It was calculated correctly when the width and the What does it do? It prints a second dot on the line, end-
height were equal. ing by a space.
The next program we will do a code walkthrough for is a What is the next line? No indent change so it is: num-
program that is supposed to print out 5 dots on the screen. ber = number - 1
However, this is what the program is outputting:
And what does it do? It takes the current value of num-
.... ber (4), subtracts 1 from it, which gives it 3 and then
And here is the program: nally makes 3 the new value of number.
number = 5 while number > 1: print(".,end=" ") number What is the next line? Since there is an indent change
= number - 1 print() caused by the end of the while loop, the next line is:
while number > 1:
This program will be more complex to walkthrough since What does it do? It compares the current value of num-
it now has indented portions (or control structures). Let ber (3) to 1. 3 > 1 so the while loop continues.
us begin.
What is the next line? Since the while loop condition
was true the next line is: print(".,end=" ")
What is the rst line to be run? The rst line of the
le: number = 5 And it does what? A third dot is printed on the line.
What does it do? Puts the number 5 in the variable What is the next line? It is: number = number - 1
number.
What does it do? It takes the current value of number
What is the next line? The next line is: while number (3) subtracts from it 1 and makes the 2 the new value
> 1: of number.
0.28 Creating Functions 13
What is the next line? Back up to the start of the while else: print(The absolute values of, a, and, b, are
loop: while number > 1: dierent.)
What does it do? It compares the current value of num-
ber (2) to 1. Since 2 > 1 the while loop continues. with the output being:
The absolute values of 23 and 23 are equal.
What is the next line? Since the while loop is continu-
ing: print(".,end=" ") The program seems a little repetitive. Programmers hate
to repeat things -- thats what computers are for, after
What does it do? It discovers the meaning of life, the all! (Note also that nding the absolute value changed
universe and everything. I'm joking. (I had to make the value of the variable, which is why it is printing out
sure you were awake.) The line prints a fourth dot 23, and not 23 in the output.) Fortunately Python al-
on the screen. lows you to create functions to remove duplication. Here
What is the next line? Its: number = number - 1 is the rewritten example:
a = 23 b = 23 def absolute_value(n): if n < 0: n =
What does it do? Takes the current value of number (2)
-n return n if absolute_value(a) == absolute_value(b):
subtracts 1 and makes 1 the new value of number.
print(The absolute values of, a, and, b, are equal.)
What is the next line? Back up to the while loop: while else: print(The absolute values of, a, and, b, are
number > 1: dierent.)
0.29 Variables in functions variables of the same name are gone. Then the statement
print(a_var = ", a_var) prints the value 10 rather than
the value 15 since the local variable that hid the global
When eliminating repeated code, you often have vari- variable is gone.
ables in the repeated code. In Python, these are dealt
Another thing to notice is the NameError that happens at
with in a special way. So far all variables we have seen are
the end. This appears since the variable d_var no longer
global variables. Functions have a special type of variable
exists since a_func nished. All the local variables are
called local variables. These variables only exist while the
deleted when the function exits. If you want to get some-
function is running. When a local variable has the same
thing from a function, then you will have to use return
name as another variable (such as a global variable), the
something.
local variable hides the other. Sound confusing? Well,
these next examples (which are a bit contrived) should One last thing to notice is that the value of e_var remains
help clear things up. unchanged inside a_func since it is not a parameter and
it never appears on the left of an equals sign inside of
a = 4 def print_func(): a = 17 print(in print_func a =",
the function a_func. When a global variable is accessed
a) print_func() print(a = ", a)
inside a function it is the global variable from the outside.
Functions allow local variables that exist only inside the
When run, we will receive an output of:
function and can hide other variables that are outside the
in print_func a = 17 a = 4 function.
Variable assignments inside a function do not override
global variables, they exist only inside the function. Even
though a was assigned a new value inside the function, 0.30 Examples
this newly assigned value was only relevant to print_func,
when the function nishes running, and the as values is temperature2.py
printed again, we see the originally assigned values. #! /usr/bin/python #-*-coding: utf-8 -*- # con-
Here is another more complex example. verts temperature to Fahrenheit or Celsius def
print_options(): print(Options:") print(" 'p' print
a_var = 10 b_var = 15 e_var = 25 def a_func(a_var): options) print(" 'c' convert from Celsius) print("
print(in a_func a_var =", a_var) b_var = 100 + 'f' convert from Fahrenheit) print(" 'q' quit the
a_var d_var = 2 * a_var print(in a_func b_var =", program) def celsius_to_fahrenheit(c_temp):
b_var) print(in a_func d_var =", d_var) print(in
return 9.0 / 5.0 * c_temp + 32 def fahren-
a_func e_var =", e_var) return b_var + 10 c_var heit_to_celsius(f_temp): return (f_temp - 32.0) *
= a_func(b_var) print(a_var =", a_var) print(b_var
5.0 / 9.0 choice = p while choice != q": if choice
=", b_var) print(c_var =", c_var) print(d_var =", d_var) == c": c_temp = oat(input(Celsius temperature:
")) print(Fahrenheit:", celsius_to_fahrenheit(c_temp))
output: choice = input(option: ") elif choice == f": f_temp =
in a_func a_var = 15 in a_func b_var = 115 in a_func oat(input(Fahrenheit temperature: ")) print(Celsius:",
d_var = 30 in a_func e_var = 25 a_var = 10 b_var = 15 fahrenheit_to_celsius(f_temp)) choice = input(option:
c_var = 125 d_var = Traceback (most recent call last): ") else: choice = p #Alternatively choice != q": so that
File C:\def2.py, line 19, in <module> print(d_var = ", print #when anything unexpected inputed print_options()
d_var) NameError: name 'd_var' is not dened choice = input(option: ")
print() print('To nd the area of a rectangle,') print('enter Question: What is the rst thing the program does?
the width and height below.') print() w = posi- Answer: The rst thing done is the function mult is
tive_input('Width: ') h = positive_input('Height: ') dened with the lines:
print('Width =', w, ' Height =', h, ' so Area =', area(w,
h)) def mult(a, b): if b == 0: return 0 rest = mult(a, b - 1)
value = a + rest return value
Sample Run:
Your Name: Josh Hello! Welcome, Josh To nd the area This creates a function that takes two parameters and
of a rectangle, enter the width and height below. Width: returns a value when it is done. Later this function
4 Must be a positive number Width: 4 Height: 3 Width can be run.
= 4 Height = 3 so Area = 12
What happens next? The next line after the function,
result = mult(3, 2) is run.
0.31 Exercises What does this line do? This line will assign the return
value of mult(3, 2) to the variable result.
Rewrite the area2.py program from the Examples above
to have a separate function for the area of a square, the And what does mult(3, 2) return? We need to do a
area of a rectangle, and the area of a circle (3.14 * ra- walkthrough of the mult function to nd out.
dius**2). This program should include a menu interface.
What happens next? The variable a gets the value 3 as-
Solution signed to it and the variable b gets the value 2 as-
def square(L): return L * L def rectangle(width , height): signed to it.
return width * height def circle(radius): return 3.14159
* radius ** 2 def options(): print() print(Options:") And then? The line if b == 0: is run. Since b has the
print(s = calculate the area of a square.) print(c = value 2 this is false so the line return 0 is skipped.
calculate the area of a circle.) print(r = calculate the And what then? The line rest = mult(a, b - 1) is run.
area of a rectangle.) print(q = quit) print() print(This This line sets the local variable rest to the value of
program will calculate the area of a square, circle or mult(a, b - 1). The value of a is 3 and the value of b
rectangle.) choice = x options() while choice != q": is 2 so the function call is mult(3,1)
choice = input(Please enter your choice: ") if choice
== s": L = oat(input(Length of square side: ")) So what is the value of mult(3, 1) ? We will need to
print(The area of this square is, square(L)) options() run the function mult with the parameters 3 and 1.
elif choice == c": radius = oat(input(Radius of the
circle: ")) print(The area of the circle is, circle(radius)) So what happens next? The local variables in the new
options() elif choice == r": width = oat(input(Width run of the function are set so that a has the value 3
of the rectangle: ")) height = oat(input(Height of and b has the value 1. Since these are local values
the rectangle: ")) print(The area of the rectangle is, these do not aect the previous values of a and b.
rectangle(width, height)) options() elif choice == q": And then? Since b has the value 1 the if statement is
print(" ",end="") else: print(Unrecognized option.) false, so the next line becomes rest = mult(a, b - 1).
options()
What does this line do? This line will assign the value
of mult(3, 0) to rest.
Some people nd this section useful, and some nd it con-
fusing. If you nd it confusing you can skip it. Now we So what is that value? We will have to run the function
will do a walk through for the following program: one more time to nd that out. This time a has the
def mult(a, b): if b == 0: return 0 rest = mult(a, b - 1) value 3 and b has the value 0.
value = a + rest return value result = mult(3, 2) print(3 So what happens next? The rst line in the function to
* 2 = ", result) run is if b == 0:. b has the value 0 so the next line
to run is return 0
Basically this program creates a positive integer multipli- And what does the line return 0 do? This line returns
cation function (that is far slower than the built in mul- the value 0 out of the function.
tiplication function) and then demonstrates this function
with a use of the function. This program demonstrates the So? So now we know that mult(3, 0) has the value 0.
use of recursion, that is a form of iteration (repetition) in Now we know what the line rest = mult(a, b - 1) did
which there is a function that repeatedly calls itself until since we have run the function mult with the param-
an exit condition is satised. It uses repeated additions to eters 3 and 0. We have nished running mult(3, 0)
give the same result as mutiplication: e.g. 3 + 3 (addition) and are now back to running mult(3, 1). The vari-
gives the same result as 3 * 2 (multiplication). able rest gets assigned the value 0.
16
What line is run next? The line value = a + rest is run Any problem that can be solved with recursion could be
next. In this run of the function, a = 3 and rest = 0 re-implemented with loops. Using the latter usually re-
so now value = 3. sults in better performance. However equivalent imple-
mentations using loops are usually harder to get done cor-
What happens next? The line return value is run. This rectly.
returns 3 from the function. This also exits from the
Probably the most intuitive denition of recursion is:
run of the function mult(3, 1). After return is called,
we go back to running mult(3, 2).
Recursion If you still don't get it, see recursion.
Where were we in mult(3, 2)? We had the variables a
= 3 and b = 2 and were examining the line rest = Try walking through the factorial example if the multi-
mult(a, b - 1). plication example did not make sense.
The [ and ] start and end the list with commas (,) separat-
tice that you can just print a whole list. Next the append
ing the list items. The list is used in months[which_one function is used to add a new item to the end of the list.
- 1]. A list consists of items that are numbered starting len returns how many items are in a list. The valid indexes
at 0. In other words if you wanted January you would (as in numbers that can be used inside of the []) of a list
use months[0]. Give a list a number and it will return therange from 0 to len - 1. The index function tells where
value that is stored at that location. the rst location of an item is located in a list. Notice
The statement if 1 <= which_one <= 12: will only be how demolist.index(42) returns 1, and when demolist[1]
true if which_one is between one and twelve inclusive (in is run it returns 42. To get help on all the functions a list
provides for you, type help(list) in the interactive Python
other words it is what you would expect if you have seen
that in algebra). interpreter.
Lists can be thought of as a series of boxes. Each box The line # Next we will loop through the list is a just
has a dierent value. For example, the boxes created by a reminder to the programmer (also called a comment).
demolist = ['life', 42, 'the universe', 6, 'and', 9] would look Python ignores everything that is written after a # on the
like this: current line. Next the lines:
Each box is referenced by its number so the statement for c in range(len(demolist)): print('demolist[', c, '] =',
demolist[0] would get 'life', demolist[1] would get 42 and demolist[c])
so on up to demolist[5] getting 9.
create a variable c, which starts at 0 and is incremented
until it reaches the last index of the list. Meanwhile the
print statement prints out each element of the list.
0.34 More features of lists
A much better way to do the above is:
The next example is just to show a lot of other stu lists for c, x in enumerate(demolist): print(demolist[", c, "]
can do (for once I don't expect you to type it in, but you =", x)
should probably play around with lists in interactive mode
until you are comfortable with them.). Here goes:
The del command can be used to remove a given element
demolist = ["life, 42, the universe, 6, in a list. The next few lines use the in operator to test if
and, 9] print(demolist = ",demolist) de- an element is in or is not in a list. The sort function sorts
molist.append(everything) print(after 'ev- the list. This is useful if you need a list in order from
erything' was appended demolist is now:") smallest number to largest or alphabetical. Note that this
print(demolist) print(len(demolist) =", len(demolist)) rearranges the list. In summary, for a list, the following
print(demolist.index(42) =", demolist.index(42)) operations occur:
print(demolist[1] =", demolist[1]) # Next we will
loop through the list for c in range(len(demolist)): This next example uses these features in a more useful
print(demolist[", c, "] =", demolist[c]) del demolist[2] way:
print(After 'the universe' was removed demolist is menu_item = 0 namelist = [] while menu_item !=
now:") print(demolist) if life in demolist: print("'life' 9: print("--------------------") print(1. Print the list)
was found in demolist) else: print("'life' was not found print(2. Add a name to the list) print(3. Remove a
in demolist) if amoeba in demolist: print("'amoeba' name from the list) print(4. Change an item in the
was found in demolist) if amoeba not in demolist: list) print(9. Quit) menu_item = int(input(Pick an
print("'amoeba' was not found in demolist) another_list item from the menu: ")) if menu_item == 1: current
= [42,7,0,123] another_list.sort() print(The sorted = 0 if len(namelist) > 0: while current < len(namelist):
another_list is, another_list) print(current, "., namelist[current]) current = current + 1
else: print(List is empty) elif menu_item == 2: name =
The output is: input(Type in a name to add: ") namelist.append(name)
elif menu_item == 3: del_name = input(What name
demolist = ['life', 42, 'the universe', 6, 'and', 9] after 'ev- would you like to remove: ") if del_name in namelist:
erything' was appended demolist is now: ['life', 42, 'the # namelist.remove(del_name) would work just as
universe', 6, 'and', 9, 'everything'] len(demolist) = 7 de- ne item_number = namelist.index(del_name) del
molist.index(42) = 1 demolist[1] = 42 demolist[ 0 ] = life namelist[item_number] # The code above only re-
demolist[ 1 ] = 42 demolist[ 2 ] = the universe demolist[ moves the rst occurrence of # the name. The code
3 ] = 6 demolist[ 4 ] = and demolist[ 5 ] = 9 demolist[ 6 ] below from Gerald removes all. # while del_name in
= everything After 'the universe' was removed demolist is namelist: # item_number = namelist.index(del_name)
now: ['life', 42, 6, 'and', 9, 'everything'] 'life' was found in # del namelist[item_number] else: print(del_name,
demolist 'amoeba' was not found in demolist The sorted was not found) elif menu_item == 4: old_name
another_list is [0, 7, 42, 123] = input(What name would you like to change:
This example uses a whole bunch of new functions. No- ") if old_name in namelist: item_number =
18
answers, and an option to quit. Also, add a new ques- range function uses two arguments like this range(start,
tion to ask, What noise does a truly advanced machine nish). start is the rst number that is produced. nish is
make?" with the answer of ping. one larger than the last number. Note that this program
Solution could have been done in a shorter way:
for count in range(1, 11): print(count)
Expand the test.py program so it has menu giving the op-
tion of taking the test, viewing the list of questions and The range function returns an iterable. This can be con-
answers, and an option to quit. Also, add a new ques- verted into a list with the list function. which will then be
tion to ask, What noise does a truly advanced machine the dominant number. Here are some examples to show
make?" with the answer of ping. what happens with the range command:
## This program runs a test of knowledge questions >>> range(1, 10) range(1, 10) >>> list(range(1, 10)) [1,
= [["What color is the daytime sky on a clear day? ", 2, 3, 4, 5, 6, 7, 8, 9] >>> list(range(32, 20)) [32,
blue"], ["What is the answer to life, the universe and 31, 30, 29, 28, 27, 26, 25, 24, 23, 22,
everything? ", 42"], ["What is a three letter word 21] >>> list(range(5,21)) [5, 6, 7, 8, 9, 10, 11, 12, 13,
for mouse trap? ", cat"], ["What noise does a truly 14, 15, 16, 17, 18, 19, 20] >>> list(range(5)) [0, 1, 2, 3,
advanced machine make?", ping"]] # This will test a 4] >>> list(range(21, 5)) []
single question # it takes a single question in # it returns The next line for count in onetoten: uses the for control
True if the user typed the correct answer, otherwise False
structure. A for control structure looks like for variable
def check_question(question_and_answer): # extract the in list:. list is gone through starting with the rst element
question and the answer from the list question = ques-
of the list and going to the last. As for goes through each
tion_and_answer[0] answer = question_and_answer[1] element in a list it puts each into variable. That allows
# give the question to the user given_answer = in- variable to be used in each successive time the for loop is
put(question) # compare the users answer to the testers run through. Here is another example (you don't have to
answer if answer == given_answer: print(Correct) type this) to demonstrate:
return True else: print(Incorrect, correct was:", answer)
return False # This will run through all the questions def demolist = ['life', 42, 'the universe', 6, 'and', 7, 'every-
run_test(questions): if len(questions) == 0: print(No thing'] for item in demolist: print(The current item
questions were given.) # the return exits the function is:",item)
return index = 0 right = 0 while index < len(questions): #
Check the question if check_question(questions[index]): The output is:
right = right + 1 # go to the next question index =
index + 1 # notice the order of the computation, rst The current item is: life The current item is: 42 The cur-
multiply, then divide print(You got, right * 100 / rent item is: the universe The current item is: 6 The cur-
len(questions), "% right out of, len(questions)) #show- rent item is: and The current item is: 7 The current item
ing a list of questions and answers def showquestions(): is: everything
q = 0 while q < len(questions): a = 0 print(Q:" , Notice how the for loop goes through and sets item to
questions[q][a]) a = 1 print(A:" , questions[q][a]) each element in the list. So, what is for good for? The
q = q + 1 # now lets dene the menu function def rst use is to go through all the elements of a list and do
menu(): print("-----------------") print(Menu:") print(1 something with each of them. Heres a quick way to add
- Take the test) print(2 - View a list of questions and up all the elements:
answers) print(3 - View the menu) print(5 - Quit)
list = [2, 4, 6, 8] sum = 0 for num in list: sum = sum +
print("-----------------") choice = 3 while choice !=
num print(The sum is:", sum)
5": if choice == 1": run_test(questions) elif choice ==
2": showquestions() elif choice == 3": menu() print()
choice = input(Choose your option from the menu with the output simply being:
above: ") The sum is: 20
Or you could write a program to nd out if there are any
And here is the new typing exercise for this chapter: duplicates in a list like this program does:
onetoten = range(1, 11) for count in onetoten: list = [4, 5, 7, 8, 9, 1, 0, 7, 10] list.sort() prev = None for
print(count) item in list: if prev == item: print(Duplicate of, prev,
found) prev = item
and the ever-present output:
1 2 3 4 5 6 7 8 9 10 and for good measure:
The output looks awfully familiar but the program code Duplicate of 7 found
looks dierent. The rst line uses the range function. The
20
a = 1 b = 1 for c in range(1, 10): print(a, end=" ") n = a Notice that if the rst expression is true Python doesn't
+ba=bb=n check the second expression since it knows the whole ex-
pression is true. This works since or is true if at least one
half of the expression is true. The rst part is true so the
with the surprising output: second part could be either false or true, but the whole
1 1 2 3 5 8 13 21 34 expression is still true.
Everything that can be done with for loops can also be The next two lines, print(8, not (a == 7 and b == 6)) and
done with while loops but for loops give an easy way to print(9, not a == 7 and b == 6), show that parentheses
go through all the elements in a list or to do something a can be used to group expressions and force one part to
certain number of times. be evaluated rst. Notice that the parentheses changed
the expression from false to true. This occurred since the
Here is a little example of boolean expressions (you don't
parentheses forced the not to apply to the whole expres-
have to type it in):
0.37 A note on Boolean Operators 21
sion instead of just the a == 7 portion. >>> 'a' == ('a' and 'b') False >>> 'b' == ('a' and 'b')
Here is an example of using a boolean expression: True
At this point, the and and or operators seem to be broken.
list = ["Life, The Universe, Everything, Jack,
Jill, Life, Jill"] # make a copy of the list. See the It doesn't make sense that, for the rst two expressions, 'a'
is equivalent to 'a' or 'b' while 'b' is not. Furthermore, it
More on Lists chapter to explain what [:] means. copy
= list[:] # sort the copy copy.sort() prev = copy[0] del doesn't make any sense that 'b' is equivalent to 'a' and 'b'.
After examining what the interpreter does with boolean
copy[0] count = 0 # go through the list searching for a
match while count < len(copy) and copy[count] != prev: operators, these results do in fact exactly what you are
prev = copy[count] count = count + 1 # If a match was asking of them, its just not the same as what you think
not found then count can't be < len # since the while loop you are asking.
continues while count is < len # and no match is found if When the Python interpreter looks at an or expression,
count < len(copy): print(First Match:", prev) it takes the rst statement and checks to see if it is true.
If the rst statement is true, then Python returns that ob-
And here is the output: jects value without checking the second statement. This
is because for an or expression, the whole thing is true
First Match: Jill if one of the values is true; the program does not need
This program works by continuing to check for match to bother with the second statement. On the other hand,
while count < len(copy) and copy[count] is not equal to if the rst value is evaluated as false Python checks the
prev. When either count is greater than the last index of second half and returns that value. That second half de-
copy or a match has been found the and is no longer true termines the truth value of the whole expression since the
so the loop exits. The if simply checks to make sure that rst half was false. This laziness on the part of the in-
the while exited because a match was found. terpreter is called short circuiting and is a common way
of evaluating boolean expressions in many programming
The other trick of and is used in this example. If you languages.
look at the table for and notice that the third entry is false
and false. If count >= len(copy) (in other words count Similarly, for an and expression, Python uses a short cir-
< len(copy) is false) then copy[count] is never looked at. cuit technique to speed truth value evaluation. If the rst
This is because Python knows that if the rst is false then statement is false then the whole thing must be false, so
they can't both be true. This is known as a short cir- it returns that value. Otherwise if the rst value is true it
cuit and is useful if the second half of the and will cause checks the second and returns that value.
an error if something is wrong. I used the rst expres-One thing to note at this point is that the boolean ex-
sion (count < len(copy)) to check and see if count was a
pression returns a value indicating True or False, but that
valid index for copy. (If you don't believe me remove the
Python considers a number of dierent things to have a
matches Jill and Life, check that it still works and then
truth value assigned to them. To check the truth value of
reverse the order of count < len(copy) and copy[count] !=
any given object x, you can use the fuction bool(x) to see
prev to copy[count] != prev and count < len(copy).) its truth value. Below is a table with examples of the truth
Boolean expressions can be used when you need to check values of various objects:
two or more dierent things at once. Now it is possible to understand the perplexing results we
were getting when we tested those boolean expressions
before. Lets take a look at what the interpreter sees as
0.37 A note on Boolean Operators it goes through that code:
First case:
A common mistake for people new to programming is
a misunderstanding of the way that boolean operators >>> 'a' == ('a' or 'b') # Look at parentheses rst, so
works, which stems from the way the python interpreter evaluate expression "('a' or 'b')" # 'a' is a nonempty string,
reads these expressions. For example, after initially so the rst value is True # Return that rst value: 'a' >>>
learning about and " and or statements, one might as- 'a' == 'a' # the string 'a' is equivalent to the string 'a', so
sume that the expression x == ('a' or 'b') would check to expression is True True
see if the variable x was equivalent to one of the strings Second case:
'a' or 'b'. This is not so. To see what I'm talking about,
>>> 'b' == ('a' or 'b') # Look at parentheses rst, so
start an interactive session with the interpreter and enter
evaluate expression "('a' or 'b')" # 'a' is a nonempty string,
the following expressions:
so the rst value is True # Return that rst value: 'a' >>>
>>> 'a' == ('a' or 'b') >>> 'b' == ('a' or 'b') >>> 'a' == ('a' 'b' == 'a' # the string 'b' is not equivalent to the string
and 'b') >>> 'b' == ('a' and 'b') 'a', so expression is False False
And this will be the unintuitive result: Third case:
>>> 'a' == ('a' or 'b') True >>> 'b' == ('a' or 'b') False
22
>>> 'a' == ('a' and 'b') # Look at parentheses rst, guilherme guess = input(What is my name? ") while
so evaluate expression "('a' and 'b')" # 'a' is a nonempty count < 3 and guess.lower() != name: # .lower allows
string, so the rst value is True, examine second value # things like Guilherme to still match print(You are
'b' is a nonempty string, so second value is True # Return wrong!") guess = input(What is my name? ") count
that second value as result of whole expression: 'b' >>> = count + 1 if guess.lower() != name: print(You are
'a' == 'b' # the string 'a' is not equivalent to the string wrong!") # this message isn't printed in the third chance,
'b', so expression is False False so we print it now print(You ran out of chances.) else:
Fourth case: print(Yes! My name is, name + "!")
The remove student entry just deletes a student similar to With some output being:
the telephone book example. The record grades choice The time is: Sun Aug 20 13:40:04 2000 The time is: Sun
is a little more complex. The grades are retrieved in Aug 20 13:40:05 2000 The time is: Sun Aug 20 13:40:06
the line grades = students[name] gets a reference to the 2000 The time is: Sun Aug 20 13:40:07 2000 Traceback
grades of the student name. A grade is then recorded (innermost last): File clock.py, line 5, in ? the_time =
in the line grades[which] = grade. You may notice that ctime(time()) KeyboardInterrupt
grades is never put back into the students dictionary (as
in no students[name] = grades). The reason for the miss- The output is innite of course so I cancelled it (or the
ing statement is that grades is actually another name output at least continues until Ctrl+C is pressed). The
for students[name] and so changing grades changes stu- program just does an innite loop (True is always true, so
dent[name]. while True: goes forever) and each time checks to see if
the time has changed and prints it if it has. Notice how
Dictionaries provide a easy way to link keys to values. multiple names after the import statement are used in the
This can be used to easily keep track of data that is at- line from time import time, ctime.
tached to various keys.
The Python Library contains many useful functions.
Heres this chapters typing exercise (name it cal.py (im- These functions give your programs more abilities and
port actually looks for a le named calendar.py and reads many of them can simplify programming in Python.
it in. If the le is named calendar.py and it sees a import
calendar it tries to read in itself which works poorly at
best.)):
0.40 Exercises
import calendar year = int(input(Type in the year
number: ")) calendar.prcal(year) Rewrite the high_low.py program from section Decisions
to use an random integer between 0 and 99 instead of the
And here is part of the output I got: hard-coded 78. Use the Python documentation to nd an
appropriate module and function to do this.
Type in the year number: 2001 2001 January February
March Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Solution
Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 1 2 3 4 1 2 3 4 8 9
10 11 12 13 14 5 6 7 8 9 10 11 5 6 7 8 9 10 11 15 16 17 Rewrite the high_low.py program from section Decisions
18 19 20 21 12 13 14 15 16 17 18 12 13 14 15 16 17 18 to use an random integer between 0 and 99 instead of the
22 23 24 25 26 27 28 19 20 21 22 23 24 25 19 20 21 22 hard-coded 78. Use the Python documentation to nd an
23 24 25 29 30 31 26 27 28 26 27 28 29 30 31 appropriate module and function to do this.
(I skipped some of the output, but I think you get the from random import randint number = randint(0, 99)
idea.) So what does the program do? The rst line import guess = 1 while guess != number: guess = int(input
calendar uses a new command import. The command im- (Guess a number: ")) if guess > number: print(Too
port loads a module (in this case the calendar module). To high) elif guess < number: print(Too low) print(Just
see the commands available in the standard modules ei- right)
ther look in the library reference for python (if you down-
loaded it) or go to http://docs.python.org/3/library/. If
you look at the documentation for the calendar module, We have already seen lists and how they can be used. Now
it lists a function called prcal that prints a calendar for a that you have some more background I will go into more
year. The line calendar.prcal(year) uses this function. In detail about lists. First we will look at more ways to get at
summary to use a module import it and then use mod- the elements in a list and then we will talk about copying
ule_name.function for functions in the module. Another them.
way to write the program is: Here are some examples of using indexing to access a
from calendar import prcal year = int(input(Type in the single element of a list:
year number: ")) prcal(year) >>> some_numbers = ['zero', 'one', 'two', 'three',
'four', 've'] >>> some_numbers[0] 'zero' >>>
This version imports a specic function from a module. some_numbers[4] 'four' >>> some_numbers[5] 've'
Here is another program that uses the Python Library All those examples should look familiar to you. If
(name it something like clock.py) (press Ctrl and the 'c' you want the rst item in the list just look at index
key at the same time to terminate the program): 0. The second item is index 1 and so on through
from time import time, ctime prev_time = "" while True: the list. However what if you want the last item in
the_time = ctime(time()) if prev_time != the_time: the list? One way could be to use the len() function
print(The time is:", ctime(time())) prev_time = the_time like some_numbers[len(some_numbers) - 1]. This way
works since the len() function always returns the last in-
dex plus one. The second from the last would then be
0.40 Exercises 25
First of all notice that a is a list of lists. Then notice that unicode value. Python has a function called ord() (short
when b[0][1] = 10 is run both a and b are changed, but for ordinal) that returns a character as a number. There
c is not. This happens because the inner arrays are still is also a corresponding function called chr() that converts
references when the slice operator is used. However with a number into a character. With this in mind the pro-
deepcopy c was fully copied. gram should start to be clear. The rst detail is the line:
So, should I worry about references every time I use a if 'a' <= character <= 'z': which checks to see if a letter
function or =? The good news is that you only have is lower case. If it is then the next lines are used. First it
to worry about references when using dictionaries and is converted into a location so that a = 0, b = 1, c = 2 and
so on with the line: location = ord(character) - ord('a').
lists. Numbers and strings create references when as-
signed but every operation on numbers and strings that Next the new value is found with new_ascii = location +
ord('A'). This value is converted back to a character that
modies them creates a new copy so you can never mod-
ify them unexpectedly. You do have to think about ref- is now upper case. Note that if you really need the upper
case of a letter, you should use u=var.upper() which will
erences when you are modifying a list or a dictionary.
work with other languages as well.
By now you are probably wondering why are references
used at all? The basic reason is speed. It is much faster to Now for some interactive typing exercise:
make a reference to a thousand element list than to copy >>> # Integer to String >>> 2 2 >>> repr(2) '2' >>>
all the elements. The other reason is that it allows you to 123 123 >>> repr(123) '123' >>> # String to
have a function to modify the inputed list or dictionary. Integer >>> 23 '23' >>> int(23) 23 >>> 23 * 2
Just remember about references if you ever have some '2323' >>> int(23) * 2 46 >>> # Float to String >>>
weird problem with data being changed when it shouldn't 1.23 1.23 >>> repr(1.23) '1.23' >>> # Float to Integer
be. >>> 1.23 1.23 >>> int(1.23) 1 >>> int(1.23) 1 >>>
# String to Float >>> oat(1.23) 1.23 >>> 1.23
And now presenting a cool trick that can be done with
strings: '1.23' >>> oat(123) 123.0
def shout(string): for character in string: print(Gimme If you haven't guessed already the function repr() can con-
a " + character) print("'" + character + "'") shout(Lose) vert an integer to a string and the function int() can con-
def middle(string): print(The middle character is:", vert a string to an integer. The function oat() can convert
string[len(string) // 2]) middle(abcdefg) middle(The a string to a oat. The repr() function returns a printable
Python Programming Language) middle(Atlanta) representation of something. Here are some examples of
this:
And the output is: >>> repr(1) '1' >>> repr(234.14) '234.14' >>> repr([4,
42, 10]) '[4, 42, 10]'
Gimme a L 'L' Gimme a o 'o' Gimme a s 's Gimme a e
'e' The middle character is: d The middle character is: r The int() function tries to convert a string (or a oat) into
an integer. There is also a similar function called oat()
The middle character is: a
that will convert a integer or a string into a oat. Another
What these programs demonstrate is that strings are sim- function that Python has is the eval() function. The eval()
ilar to lists in several ways. The shout() function shows function takes a string and returns data of the type that
that for loops can be used with strings just as they can python thinks it found. For example:
be used with lists. The middle procedure shows that that
strings can also use the len() function and array indexes >>> v = eval('123') >>> print(v, type(v)) 123 <type
and slices. Most list features work on strings as well. 'int'> >>> v = eval('645.123') >>> print(v, type(v))
645.123 <type 'oat'> >>> v = eval('[1, 2, 3]') >>>
The next feature demonstrates some string specic fea- print(v, type(v)) [1, 2, 3] <type 'list'>
tures:
If you use the eval() function you should check that it re-
def to_upper(string): ## Converts a string to upper case turns the type that you expect.
upper_case = "" for character in string: if 'a' <= character
<= 'z': location = ord(character) - ord('a') new_ascii One useful string function is the split() method. Heres an
= location + ord('A') character = chr(new_ascii) up- example:
per_case = upper_case + character return upper_case >>> This is a bunch of words.split() ['This, 'is, 'a',
print(to_upper(This is Text)) 'bunch', 'of', 'words] >>> text = First batch, second
batch, third, fourth >>> text.split(",) ['First batch',
with the output being: ' second batch', ' third', ' fourth']
THIS IS TEXT Notice how split() converts a string into a list of strings.
The string is split by whitespace by default or by the op-
This works because the computer represents the charac- tional argument (in this case a comma). You can also
ters of a string as numbers from 0 to 1,114,111. For ex- add another argument that tells split() how many times
ample 'A' is 65, 'B' is 66 and is 1488. The values are the the separator will be used to split the text. For example:
0.43 File I/O 27
>>> list = text.split(",) >>> len(list) 4 >>> list[1] '0: out_str = str(in_int % 10) + out_str in_int = in_int
fourth' >>> list = text.split(",, 2) >>> len(list) 3 >>>// 10 out_str = str(in_int % 10) + out_str return prex
list[1] ' third, fourth' + out_str def to_int(in_str): """Converts a string to an
integer""" out_num = 0 if in_str[0] == "-": multiplier =
1 in_str = in_str[1:] else: multiplier = 1 for c in in_str:
0.41 Slicing strings (and lists) out_num = out_num * 10 + int(c) return out_num *
multiplier print(to_string(2)) print(to_string(23445))
Strings can be cut into pieces in the same way as it print(to_string(23445)) print(to_int(14234))
was shown for lists in the previous chapter by using print(to_int(12345)) print(to_int("3512))
the slicing operator []. The slicing operator works in
the same way as before: text[first_index:last_index] (in
very rare cases there can be another colon and a third The output is:
argument, as in the example shown below). 2 23445 23445 14234 12345 3512
In order not to get confused by the index numbers, it is
easiest to see them as clipping places, possibilities to cut
a string into parts. Here is an example, which shows the
0.43 File I/O
clipping places (in yellow) and their index numbers (red
Here is a simple example of le I/O (input/output):
and blue) for a simple text string:
# Write a le with open(test.txt, wt) as out_le:
Note that the red indexes are counted from the beginning
out_le.write(This Text is going to out le\nLook at
of the string and the blue ones from the end of the string
it and see!") # Read a le with open(test.txt, rt) as
backwards. (Note that there is no blue 0, which could
in_le: text = in_le.read() print(text)
seem to be logical at the end of the string. Because 0
== 0, 0 means beginning of the string as well.) Now
we are ready to use the indexes for slicing operations: The output and the contents of the le test.txt are:
text[1:4] gives us all of the text string between clipping This Text is going to out le Look at it and see!
places 1 and 4, TRI. If you omit one of the [first_index: Notice that it wrote a le called test.txt in the directory
last_index] arguments, you get the beginning or end of that you ran the program from. The \n in the string tells
the string as default: text[:5] gives STRIN. For both Python to put a newline where it is.
rst_index and last_index we can use both the red and
the blue numbering schema: text[:1] gives the same A overview of le I/O is:
as text[:5], because the index 1 is at the same place
as 5 in this case. If we do not use an argument con- Get a le object with the open function
taining a colon, the number is treated in a dierent way:
text[2] gives us one character following the second clip- Read or write to the le object (depending on how it
ping point, R. The special slicing operation text[:] was opened)
means from the beginning to the end and produces a
If you did not use with to open the le, you'd have
copy of the entire string (or list, as shown in the previous
to close it manually
chapter).
Last but not least, the slicing operation can have a second The rst step is to get a le object. The way to do this
colon and a third argument, which is interpreted as the is to use the open function. The format is le_object =
step size": text[::1] is text from beginning to the end, open(lename, mode) where le_object is the variable to
with a step size of 1. 1 means every character, but in put the le object, lename is a string with the lename,
the other direction. STRING backwards is GNIRTS and mode is rt to read a le as text or wt to write
(test a step length of 2, if you have not got the point here). a le as text (and a few others we will skip here). Next
All these slicing operations work with lists as well. In that the le objects functions can be called. The two most
sense strings are just a special case of lists, where the list common functions are read and write. The write function
elements are single characters. Just remember the con- adds a string to the end of the le. The read function reads
cept of clipping places, and the indexes for slicing things the next thing in the le and returns it as a string. If no
will get a lot less confusing. argument is given it will return the whole le (as done in
the example).
Now here is a new version of the phone numbers program
0.42 Examples
that we made earlier:
# This program requires an excellent understanding of def print_numbers(numbers): print(Telephone Num-
decimal numbers. def to_string(in_int): """Converts an bers:") for k, v in numbers.items(): print(Name:",
integer to a string""" out_str = "" prex = "" if in_int k, "\tNumber:", v) print() def add_number(numbers,
< 0: prex = "-" in_int = -in_int while in_int // 10 != name, number): numbers[name] = number def
28
just understand that in this program, '/p' is the subprocess # Change from oat(input()) to input() to avoid an error
used to access your printer through the specied applica- when saving grades[which] = grade elif which != 1:
tion. The last argument should be the name of the le you print(Invalid Grade Number) else: print(Student not
want to send to the printing subprocess. In this case, it is found) elif menu_choice == 5: print_all_grades() elif
the same le used earlier in this chapter. menu_choice == 6: gradesle = input(Save grades to
which le? ") save_grades(gradesle) elif menu_choice
!= 9: print_menu()
0.45 Exercises
Now when we run the new program and give it @#& it be exact), an earlier version was written entirely
tells us That was not a number. and continues with what by Josh Cogliati, and it was up on his webpage
it was doing before. http://www.honors.montana.edu/~{}jjc/easytut
When your program keeps having some error that you and it was good. Then the server rupert, like all
know how to handle, put code in a try block, and put the good things than have a beginning came to an end,
way to handle the error in the except block. and Josh moved it to Wikibooks, but the rst person
writing stuck. If someone really wants to change it,
I will not revert it, but I don't see much point.
0.49 Exercises My question is not answered. Ask on the discussion
page or add it to this FAQ, or email one of the
Update at least the phone numbers program (in section Authors.
Dictionaries) so it doesn't crash if a user doesn't enter any
data at the menu.
For other FAQs, you may want to see the Python 2.6 ver-
So here we are at the end, or maybe the beginning. This sion of this page Non-Programmers Tutorial for Python
tutorial is on Wikibooks, so feel free to make improve- 2.6/FAQ, or the Python FAQ.
ments to it. If you want to learn more about Python, The
Python Tutorial by Guido van Rossum has more topics [1] The 'with' statement
that you can learn about. If you have been following this
tutorial, you should be able to understand a fair amount [2] 'The Python with Statement by Example'
of it. The Python Programming wikibook can be worth
looking at, too. Here are few other books which cover
Python 3:
1.2 Images
File:Clipboard.svg Source: https://upload.wikimedia.org/wikipedia/commons/1/1f/Clipboard.svg License: GPL Contributors: Self-made.
Based on Image:Evolution-tasks-old.png, which was released into the public domain by its creator AzaToth. Original artist: Tkgd2007