This is theprint version ofNon-Programmer's Tutorial for Python 2.6 You won't see this message or any elements not part of the book's content when you print orpreview this page. |
Python 3 notice: it's not recommended to learn Python 2 since it has been deprecated and replaced by Python 3. If you're new to Python, start learning Python 3. There's aPython 3 version of this Wikibook.
All example Python source code in this tutorial is granted to the public domain. Therefore, you may modify it and relicense it under any license you please. Since you are expected to learn programming, the GNU Free Documentation License would require you to keep all programs that are derived from the source code in this tutorial under that license. Since the python source code is granted to the public domain, that requirement is waived.
This tutorial was originally written in LaTeX and was available at:http://www.honors.montana.edu/~jjc/easytut/. It was moved here because the other server is going away and it was being read at least ten times a day. This document is available as LaTeX, HTML, PDF, and Postscript. Go tohttp://jjc.freeshell.org/easytut/ (Also could tryhttp://web.archive.org/web/*/http://www.honors.montana.edu/~jjc/easytut/ orhttp://www.geocities.com/jrincayc/easytut.tar.gz ) to see all these forms.There are also versions of this in Korean, Spanish, Italian and Greek in the tar file.
TheNon-Programmers' Tutorial For Python is a tutorial designed to be an introduction to the Python programming language. This guide is for someone with no programming experience.
If you have programmed in other languages I recommend usingPython Tutorial for Programmers written by Guido van Rossum.
If you have any questions or comments please use the discussion pages or seeNon-Programmer's Tutorial for Python 2.6/Authors for author contact information. I welcome questions and comments about this tutorial. I will try to answer any questions you have as best I can.
Thanks go to James A. Brown for writing most of the Windows install info. Thanks also to Elizabeth Cogliati for complaining enough : about the original tutorial (that is almost unusable for a non-programmer), for proofreading, and for many ideas and comments on it. Thanks to Joe Oppegaard for writing almost all the exercises. Thanks to everyone I have missed.
See also chapterThe End for some more comments.
So, you've never programmed before. As we go through this tutorial, Iwill attempt to teach you how to program. There really is only oneway to learn to program. You must readcode and writecode (as computer programs are often called).I'm going to show you lots of code. You should type in code that Ishow you to see what happens. Play around with it and make changes.The worst that can happen is that it won't work. When I type in codeit will be formatted like this:
##Python is easy to learnprint"Hello, World!"
That's so it is easy to distinguish from the other text. If you're reading this on the web, you'll notice the code is in color -- that's just to make it stand out, and to make the different parts of the code stand out from each other. The code you enter will probably not be colored, or the colors may be different, but it won't affect the code as long as you enter it the same way as it's printed here.
If the computer prints something out it will be formatted like this:
Hello, World!
(Note that printed text goes to your screen, and does not involve paper. Before computers had screens, the output of computer programs would be printed on paper.)
If you try this program out and you get a syntax error, check and see what version of python you have. If you have python 3.0, you should be using theNon-Programmer's Tutorial for Python 3.0. This article was made for Python 2.6
There will often be a mixture of the text you type (which is shown inbold) and the text the program prints to the screen, which would look like this:
Halt!Who Goes there?JoshYou may pass, Josh
(Some of the tutorial has not been converted to this format. Since this is a wiki, you can convert it when you find it.)
I will also introduce you to the terminology of programming - for example, that programming is often referred to ascoding. This will not only help you understand what programmers are talking about, but also help the learning process.
Now, on to more important things. In order to program in Python you need the Python software. If you don't already have the Python software go tohttp://www.python.org/download/ and get the proper version for your platform. Download it, read the instructions and get it installed.
For Python programming you need a working Python installation and a text editor. Python comes with its own editorIDLE, which is quite nice and totally sufficient for the beginning. As you get more into programming, you will probably switch to some other editor likeemacs,vi or another.
The Python download page ishttp://www.python.org/download. The most recent version is 3.1, but anyPython 2.x version since 2.2 will work for this tutorial. Be careful with the upcomingPython 3, though, as some major details will change and break this tutorial's examples. A version of this tutorial for Python 3 is atNon-Programmer's Tutorial for Python 3. There are various different installation files for different computer platforms available on the download site. Here are some specific instructions for the most common operating systems:
You are probably lucky and Python is already installed on your machine. To test it typepython on a command line. If you see something like that in the following section, you are set.
If you have to install Python, just use the operating system's package manager or go to the repository where your packages are available and get Python. Alternatively, you can compile Python from scratch after downloading the source code. If you get the source code make sure you compile in the Tk extension if you want to use IDLE.
Starting from Mac OS X (Tiger), Python ships by default with the operating system, but you might want to update to the newer version (check the version by startingpython in a command line terminal). Also IDLE (the Python editor) might be missing in the standard installation. If you want to (re-)install Python, have a look at theMac page on the Python download site.
Some computer manufacturers pre-install Python. To check if you already have it installed, open command prompt (cmd in run menu) or MS-DOS and type python. If it says "Bad command or file name" you will need to download the appropriate Windows installer (the normal one, if you do not have a 64-bit AMD or Intel chip). Start the installer by double-clicking it and follow the procedure.Python for windows can be downloaded from the officialsite of python
Go into IDLE (also called the Python GUI). You should see a window that has some text like this:
Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32Type "copyright", "credits" or "license()" for more information. **************************************************************** Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet. ****************************************************************IDLE 1.2.1 >>>
The>>> is Python's way of telling you that you are ininteractive mode. In interactive mode what you type is immediatelyrun. Try typing1+1 in. Python will respond with2.Interactive mode allows you to test out and see what Python will do.If you ever feel you need to play with new Python statements, go intointeractive mode and try them out.
Go into IDLE if you are not already. In the menu at the top, selectFile thenNew Window. In the new window that appears, type the following:
print"Hello, World!"
Now save the program: selectFile from the menu, thenSave. Save it as "hello.py" (you can save it in any folder you want). Now that it is saved it can be run.
Next run the program by going toRun thenRun Module (or if you have a older version of IDLE useEdit thenRun script). This will outputHello, World! on the*Python Shell* window.
For a more in-depth introduction to IDLE, a longer tutorial with screenshots can be found athttp://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html
If you are using Unix (such as Linux, Mac OSX, or BSD), if you make the program executable withchmod, and have as the first line:
#!/usr/bin/env python2you can run the python program with./hello.py like any other command.
Note: In some computer environments, you need to write:
#!/usr/bin/env pythonExample for Solaris:
#!/usr/bin/pythonIt is very useful to stick to some rules regarding the file names of Python programs. Otherwise some thingsmight go wrong unexpectedly. These don't matter as much for programs, but you can have weird problems if you don't follow them for module names (modules will be discussed later).
If you don't want to use Python from the command line, you don't have to, just use IDLE. To get into interactive mode just typepython without any arguments. To run a program, create it with a text editor (Emacs has a good Python mode) and then run it withpython program_name.
Additionally, to use Python within Vim, you may want to visitUsing vim as a Python IDE
At some point in your Python career you will probably get stuck and have no clue about how to solve the problem you are supposed to work on. This tutorial only covers the basics of Python programming, but there is a lot of further information available.
First of all, Python is very well documented. There might even be copies of these documents on your computer, which came with your Python installation:* The officialPython Tutorial by Guido van Rossum is often a good starting point for general questions.
There are a lot of other Python users out there, and usually they are nice and willing to help you. This very active user community is organised mostly through mailing lists and a newsgroup:
In order not to reinvent the wheel and discuss the same questions again and again, people will appreciate very much if youdo a web search for a solution to your problem before contacting these lists!
You should know how to edit programs in a text editor or IDLE, save the file and run the file once the files have been saved to your disk.
Programming tutorials since the beginning of time have started with a little program called "Hello, World!"[1] The syntax changed in Python 3.0. If you are using Python 3.0, you should be readingNon-Programmer's Tutorial for Python 3 instead. So here is the Python 2.6 example:
print"Hello, World!"
If you are using the command line to run programs then type it in with a text editor, save it ashello.py and run it withpython hello.py
Otherwise go into IDLE, create a new window, and create the program asin sectionCreating and Running Programs.
When this program is run here's what it prints:
Hello, World!
Now I'm not going to tell you this every time, but when I show you aprogram I recommend that you type it in and run it. I learn betterwhen I type it in and you probably do too.
Now here is a more complicated program:
print"Jack and Jill went up a hill"print"to fetch a pail of water;"print"Jack fell down, and broke his crown,"print"and Jill came tumbling after."
When you run this program it prints out:
Jack and Jill went up a hillto fetch a pail of water;Jack fell down, and broke his crown,and Jill came tumbling after.
When the computer runs this program it first sees the line:
print"Jack and Jill went up a hill"
so the computer prints:
Jack and Jill went up a hill
Then the computer goes down to the next line and sees:
print"to fetch a pail of water;"
So the computer prints to the screen:
to fetch a pail of water;
The computer keeps looking at each line, follows the command and then goes on to the next line. The computer keeps running commands until it reaches the end of the program.
Now is probably a good time to give you a bit of an explanation of what is happening - and a little bit of programming terminology.
What we were doing above was using acommand calledprint. Theprint command is followed by one or morearguments. So in this example
print"Hello, World!"
there is oneargument, which is"Hello, World!". Note that this argument is a group of characters enclosed in double quotes ("). This is commonly referred to as astring of characters, orstring, for short. Another example of a string is"Jack and Jill went up a hill".
A command and its arguments are collectively referred to as astatement, so
print"Hello, World!"
is an example of a statement.
That's probably more than enough terminology for now.
Here is another program:
print"2 + 2 is",2+2print"3 * 4 is",3*4print"100 - 1 is",100-1print"(33 + 2) / 5 + 11.5 is",(33+2)/5+11.5
And here is theoutput when the program is run:
2 + 2 is 43 * 4 is 12100 - 1 is 99(33 + 2) / 5 + 11.5 is 18.5
As you can see, Python can turn your six hundred dollar computer into a 2 dollar calculator.
In this example, the print command is followed by two arguments, with each of the arguments separated by a comma. So with the first line of the program
print"2 + 2 is",2+2
The first argument is the string"2 + 2 is" and the second argument is themathematical expression2 + 2, which is commonly referred to as anexpression.
What is important to note is that a string is printed as is (the string is what is within the double quotes but doesn't include the double quotes themselves. So the string is printed without the enclosing double quotes.) But anexpression isevaluated, (in other words, converted) to its actual value.
Python has six basic operations for numbers:
| Operation | Symbol | Example |
|---|---|---|
| Power (exponentiation) | ** | 5 ** 2 == 25 |
| Multiplication | * | 2 * 3 == 6 |
| Division | / | 14 / 3 == 4 |
| Remainder (modulo) | % | 14 % 3 == 2 |
| Addition | + | 1 + 2 == 3 |
| Subtraction | - | 4 - 3 == 1 |
Notice that division follows the rule,if there are no decimals to start with, there will be no decimals to end with. The following program shows this:
print"14 / 3 = ",14/3print"14 % 3 = ",14%3printprint"14.0 / 3.0 =",14.0/3.0print"14.0 % 3.0 =",14.0%3.0printprint"14.0 / 3 =",14.0/3print"14.0 % 3 =",14.0%3printprint"14 / 3.0 =",14/3.0print"14 % 3.0 =",14%3.0print
With the output:
14 / 3 = 414 % 3 = 214.0 / 3.0 = 4.6666666666714.0 % 3.0 = 2.014.0 / 3 = 4.6666666666714.0 % 3 = 2.014 / 3.0 = 4.6666666666714 % 3.0 = 2.0
Notice how Python gives different answers for some problems depending on whether or not decimal values are used.
The order of operations is the same as in math:
()***, division/, and remainder%+ and subtraction-So use parentheses to structure your formulas when needed.
Often in programming you are doing something complicated and may not in the future remember what you did. When this happens, the program should probably be commented. Acomment is a note to you and other programmers explaining what is happening. For example:
# Not quite PI, but an incredible simulationprint22.0/7.0# 355/113 is even more incredible rational approx to PI
Which outputs
3.14285714286
Notice that the comment starts with a hash:#. Comments are used to communicate with others who read the program and your future self to make clear what is complicated.
Note that any text can follow a comment, and that when the program is run, the text after the# through to the end of that line is ignored. The# does not have to be at the beginning of a new line:
# Output PI on the screenprint22.0/7.0# Well, just a good approximation
Each chapter (eventually) will contain examples of the programming features introduced in the chapter. You should at least look over them and see if you understand them. If you don't, you may want to type them in and see what happens. Mess around with them, change them and see what happens.
Denmark.py
print"Something's rotten in the state of Denmark."print" -- Shakespeare"
Output:
Something's rotten in the state of Denmark. -- Shakespeare
School.py
# This is not quite true outside of USA# and is based on my dim memories of my younger yearsprint"First Grade"print"1 + 1 =",1+1print"2 + 4 =",2+4print"5 - 2 =",5-2printprint"Third Grade"print"243 - 23 =",243-23print"12 * 4 =",12*4print"12 / 3 =",12/3print"13 / 3 =",13/3,"R",13%3printprint"Junior High"print"123.56 - 62.12 =",123.56-62.12print"(4 + 3) * 2 =",(4+3)*2print"4 + 3 * 2 =",4+3*2print"3 ** 2 =",3**2print
Output:
First Grade1 + 1 = 22 + 4 = 65 - 2 = 3Third Grade243 - 23 = 22012 * 4 = 4812 / 3 = 413 / 3 = 4 R 1Junior High123.56 - 62.12 = 61.44(4 + 3) * 2 = 144 + 3 * 2 = 103 ** 2 = 9
1. Write a program that prints your full name and your birthday as separate strings.
print"Ada Lovelace","born on","November 27, 1852"
2. Write a program that shows the use of all 6 math operations.
#Anything along these lines is acceptable:#Additionprint"2 + 5 = ",2+5#subtractionprint"9 - 3 = ",9-3#multiplicationprint"3 * 3 = ",3*3#divisionprint"90 / 5 = ",90/5#exponentsprint"7 to the power of 2 (squared) = ",7**2#remainderprint"the remainder when doing 22 / 9 = ",22%9
Now I feel it is time for a really complicated program. Here it is:
print"Halt!"user_reply=raw_input("Who goes there? ")print"You may pass,",user_reply
(user response: using Linux and Geany editor...only option shown was 'user_return'...output was correct. However, when manually typed 'user_reply' also worked correctly, even though not displayed as a option in Geany...what is the functional difference between these two?)
WhenI ran it, here is whatmy screen showed:
Halt!Who goes there?JoshYou may pass, Josh
Note: After running the code by pressing F5, the Python shell will only give the output:
Halt!Who goes there?
You need to enter your name in the Python shell, and then press Enter to get the rest of the output.
Of course when you run the program your screen will look differentbecause of theraw_input() statement. When you ran the programyou probably noticed (you did run the program, right?) that you had totype in your name and then press Enter. Then the program printed outsome more text and also your name. This is an example ofinput. Theprogram reaches a certain point and then waits for the user to inputsome data that the program can use later.
Of course, getting information from the user would be useless if we didn't have anywhere to put that information and this is where variables come in. In the previous program,user_reply is avariable. Variables are like a box that can store some piece of data. Here is a program to show examples of variables:
a=123.4b23='Spam'first_name="Bill"b=432c=a+bprint"a + b is",cprint"first_name is",first_nameprint"Sorted Parts, After Midnight or",b23
And here is the output:
a + b is 555.4first_name is BillSorted Parts, After Midnight or Spam
The variables in the above program area,b23,first_name,b, andc. A variable in Python can store any type of data - in this example we stored some strings (e.g. "Bill") and some numbers (e.g. 432).
Note the difference between strings and variable names. Strings are marked with quotation marks, which tells the computer "don't try to understand, just take this text as it is":
print"first_name"
This would print the text:
first_name
as-is. Variable names are written without any quotation marks and instruct the computer "use the value I've previously stored under this name":
printfirst_name
which would print (after the previous example):
Bill
Okay, so we have these boxes called variables and also data that can go into the variable. The computer will see a line likefirst_name = "Bill" and it reads it as "Put the stringBill into the box (or variable)first_name". Later on it sees the statementc = a + b and it reads it as "put the sum ofa + b or123.4 + 432 which equals555.4 intoc". The right hand side of the statement (a + b) isevaluated and the result is stored in the variable on the left hand side (c). This is calledassignment, and you should not confuse the assignment equal sign (=) with "equality" in a mathematical sense here (that's what== will be used for later).
Here is another example of variable usage:
a=1printaa=a+1printaa=a*2printa
And of course here is the output:
124
Even if it is the same variable on both sides the computer still reads it as "First find out the data to store and then find out where the data goes".
One more program before I end this chapter:
number=input("Type in a number: ")text=raw_input("Type in a string: ")print"number =",numberprint"number is a",type(number)print"number * 2 =",number*2print"text =",textprint"text is a",type(text)print"text * 2 =",text*2
The output I got was:
Type in a Number:12.34Type in a String:Hellonumber = 12.34number is a <type 'float'>number * 2 = 24.68text = Hellotext is a <type 'str'>text * 2 = HelloHello
Notice thatnumber was gotten withinput() whiletext was gotten withraw_input().raw_input() returns a string whileinput() returns a number. When you want the user to type in a number useinput() but if you want the user to type in a string useraw_input().
Only use input() when you trust your users with the computer the program runs on.Everything entered into input() dialog is evaluated as a Python expression and thus allows the user to take control of your program. For example, entering__import__('os').system('dir') executes thedir command. You should instead get a string and convert it to the necessary type likeint(raw_input()) orfloat(raw_input()). |
The second half of the program usestype() which tells what avariable is. Numbers are of typeint orfloat, which areshort forinteger andfloating point (mostly used for decimal numbers), respectively. Text strings are of typestr, short forstring. Integers and floats can be worked on by mathematical functions, strings cannot. Notice how when pythonmultiplies a number by an integer the expected thing happens. Howeverwhen a string is multiplied by an integer the result is that multiplecopies of the string are produced (i.e.,text * 2 = HelloHello).
The operations with strings do different things than operations with numbers. Here are some interactive mode examplesto show that some more.
>>> "This" + " " + "is" + " joined."'This is joined.'>>> "Ha, " * 5'Ha, Ha, Ha, Ha, Ha, '>>> "Ha, " * 5 + "ha!"'Ha, Ha, Ha, Ha, Ha, ha!'>>>
This could also be done as a program:
print"This"+" "+"is"+" joined."print"Ha, "*5print"Ha, "*5+"ha!"
Here is the list of some string operations:
| Operation | Symbol | Example |
|---|---|---|
| Repetition | * | "i" * 5 == "iiiii" |
| Concatenation | + | "Hello, " + "World!" == "Hello, World!" |
Rate_times.py
# This program calculates rate and distance problemsprint"Input a rate and a distance"rate=input("Rate: ")distance=input("Distance: ")print"Time:",(distance/rate)
Sample runs:
Input a rate and a distanceRate:5Distance:10Time: 2
Input a rate and a distanceRate:3.52Distance:45.6Time: 12.9545454545
Area.py
# This program calculates the perimeter and area of a rectangleprint"Calculate information about a rectangle"length=input("Length: ")width=input("Width: ")print"Area",length*widthprint"Perimeter",2*length+2*width
Sample runs:
Calculate information about a rectangleLength:4Width:3Area 12Perimeter 14
Calculate information about a rectangleLength:2.53Width:5.2Area 13.156Perimeter 15.46
temperature.py
# Converts Fahrenheit to Celsiustemp=input("Fahrenheit temperature: ")print(temp-32.0)*5.0/9.0
Sample runs:
Fahrenheit temperature:320.0
Fahrenheit temperature:-40-40.0
Fahrenheit temperature:212100.0
Fahrenheit temperature:98.637.0
Write a program that gets 2 string variables and 2 integer variablesfrom the user, concatenates (joins them together with no spaces) anddisplays the strings, then multiplies the two numbers on a new line.
string1=raw_input('String 1: ')string2=raw_input('String 2: ')int1=input('Integer 1: ')int2=input('Integer 2: ')printstring1+string2printint1*int2
Another Solution
print"this is an exercise"number_1=input("please input the first number: ")number_2=input("Please input the second number: ")string_1=raw_input("Please input the first half of the word: ")string_2=raw_input("please input the second half of the word: ")print"the words you input is '"+string_1+string_2+"'"print"the result of the 2 numbers is:",number_1*number_2
Here we present our firstcontrol structure. Ordinarily, the computer starts with the first line and then goes down from there. However, control structures change the order of how the statements are executed and/or decide if a certain statement(s) will be run. Here's the source for a program that uses thewhile control structure:
a=0whilea<10:a=a+1print(a)
And here is the extremely exciting output:
12345678910
And you thought it couldn't get any worse after turning your computer into a five dollar calculator?
So what does the program do? First, it sees the linea = 0 which tells the computer to setsa to the value of zero. Then, it seeswhile a < 10: which tells the computer to check whethera < 10. The first time the computer sees this while statement,a is equal to zero, which meansa is less than 10, so the computer proceeds to run the succeeding indented, or tabbed in, statements. After the last statement,print (a), within this while "loop" is run, the computer goes back up again to thewhile a < 10 to check the current value ofa. In other words, as long asa is less than ten, the computer will run the tabbed in statements. Witha = a + 1 repeatedly adding one toa, eventually the while loop makesa equal to ten, and makes thea < 10 no longer true. Reaching that point, the program will not run the indented lines any longer.
Always remember to put a colon ":" after the "while" statement!
Here is another example of the use ofwhile:
a=1s=0print('Enter Numbers to add to the sum.')print('Enter 0 to quit.')whilea!=0:print'Current Sum:',sa=input('Number? ')s=s+aprint'Total Sum =',round(s,2)
Enter Numbers to add to the sum.Enter 0 to quit.Current Sum: 0Number?200Current Sum: 200Number?-15.25Current Sum: 184.75Number?-151.85Current Sum: 32.9Number?10.00Current Sum: 42.9Number?0Total Sum = 42.9
Notice howprint 'Total Sum =', s is only run at the end. Thewhile statement only affects the lines that are indented with whitespace. The!= means "does not equal" so"while a != 0:" means: "untila is zero, run the tabbed statements that follow."
Now that we have while loops, it is possible to have programs that run forever. An easy way to do this is to write a program like this:
while1==1:print"Help, I'm stuck in a loop."
The "==" operator is used to test equality of the expressions on the two sides of the operator, just as "<" was used for "less than" before (you will get a complete list of all comparison operators in the next chapter).
This program will outputHelp, I'm stuck in a loop. until the heat death of the universe or until you stop it, because 1 will forever be equal to 1. The way to stop it is to hit the Control (orCtrl) button andC (the letter) at the same time. This will kill the program. (Note: sometimes you will have to hit enter after the Control-C.)
Fibonacci.py
# This program calculates the Fibonacci sequencea=0b=1count=0max_count=20whilecount<max_count:count=count+1# we need to keep track of a since we change itold_a=aold_b=ba=old_bb=old_a+old_b# Notice that the , at the end of a print statement keeps it# from switching to a new lineprint(old_a),
Output:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
Note the output on a single line by use of a comma at the end of theprint statement.
Password.py
# Waits until a password has been entered. Use Control-C to break out without# the password# Note that this must not be the password so that the# while loop runs at least once.password="no password"# note that != means not equalwhilepassword!="unicorn":password=raw_input("Password: ")print"Welcome in"
Sample run:
Password:auoPassword:y22Password:passwordPassword:open sesamePassword:unicornWelcome in
Write a program that asks the user for a Login Name and password. Then when they type "lock", they need to type in their name and password to unlock the program.
Write a program that asks the user for a Login Name and password. Then when they type "lock", they need to type in their name and password to unlock the program.
name=raw_input("What is your UserName: ")password=raw_input("What is your Password: ")print"To lock your computer type lock."command=""input1=""input2=""whilecommand!="lock":command=raw_input("What is your command: ")whileinput1!=name:input1=raw_input("What is your username: ")whileinput2!=password:input2=raw_input("What is your password: ")print"Welcome back to your system!"
If you would like the program to run continuously, just add awhile 1 == 1: loop around the whole thing.You will have to indent the rest of the program when you add 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 you want to indent and click on "Indent" under "Format" in the top bar of the python window. Note that you can use empty strings like this:"".
Another way of doing this could be:
name=raw_input('Set name: ')password=raw_input('Set password: ')while1==1:nameguess=passwordguess=key=""# multiple assignmentwhile(nameguess!=name)or(passwordguess!=password):nameguess=raw_input('Name? ')passwordguess=raw_input('Password? ')print"Welcome,",name,". Type lock to lock."whilekey!="lock":key=raw_input("")
Notice theor in while(name != "user") or (password != "pass"):, which we haven't yet introduced. You can probably figure out how it works.
login="john"password="tucker"logged=2whilelogged!=0:whilelogin!="Phil":login=raw_input("Login : ")whilepassword!="McChicken":password=raw_input("Password: ")logged=1print"Welcome!"print"To leave type lock "whilelogged==1:leave=raw_input(">> ")ifleave=="lock":logged=0print"Goodbye!!"
This method, although a bit more crude also works. Notice it uses the as of yet un-introducedif function.
As always I believe I should start each chapter with a warm-up typing exercise, so here is a short program to compute the absolute value of a number:
n=int(input("Type in a number: "))ifn<0:print('The absolute value of',int(n),'is: ',abs(-n))else:print('The absolute value of',int(n),'is: ',abs(n))
Here is the output from the two times that I ran this program:
Type in a number: -14The absolute value of -14 is: 14
Type in a number: 24The absolute value of 24 is: 24
So what does the computer do when it sees this piece of code? First it prompts the user for a number with the statement "n = input("Number? ")". Next it reads the line "if n < 0:". Ifn is less than zero Python runs the line "print('The absolute value of', int(n), 'is: ', abs(-n))". Otherwise it runs the line "print('The absolute value of', int(n), 'is: ', abs(n))".
More formally Python looks at whether theexpressionn < 0 is true or false. Anif statement is followed by an indentedblock of statements that are run when the expression is true. Optionally after theif statement is anelse statement and another indentedblock of statements. This second block of statements is run if the expression is false.
There are a number of different tests that an expression can have. Here is a table of all of them:
| operator | function |
|---|---|
< | less than |
<= | less than or equal to |
> | greater than |
>= | greater than or equal to |
== | equal |
!= | not equal |
<> | another way to say not equal (old style, not recommended) |
Another feature of the if command is the elif statement. It stands for else if and means if the original if statement is false but the elif part is true, then do theelif part. And if neither theif orelif expressions are true, then do what's in theelse block. Here's an example:
a=0whilea<10:a=a+1ifa>5:printa,">",5elifa<=7:printa,"<=",7else:print"Neither test was true"
and the output:
1 <= 72 <= 73 <= 74 <= 75 <= 76 > 57 > 58 > 59 > 510 > 5
Notice how theelif a <= 7 is only tested when theif statement fails to be true. There can be more than oneelif expression, allowing multiple tests to be done in a singleif statement.
# This Program Demonstrates the use of the == operator# using numbersprint5==6# Using variablesx=5y=8printx==y
And the output
FalseFalse
High_low.py
# Plays the guessing game higher or lower# This should actually be something that is semi random like the# last digits of the time or something else, but that will have to# wait till a later chapter. (Extra Credit, modify it to be random# after the Modules chapter)number=78guess=0whileguess!=number:guess=input("Guess a number: ")ifguess>number:print"Too high"elifguess<number:print"Too low"print"Just right"
Sample run:
Guess a number:100Too highGuess a number:50Too lowGuess a number:75Too lowGuess a number:87Too highGuess a number:81Too highGuess a number:78Just right
even.py
# Asks for a number.# Prints if it is even or oddnumber=input("Tell me a number: ")ifnumber%2==0:printnumber,"is even."elifnumber%2==1:printnumber,"is odd."else:printnumber,"is very strange."
Sample runs:
Tell me a number:33 is odd.
Tell me a number:22 is even.
Tell me a number:3.141593.14159 is very strange.
average1.py
# keeps asking for numbers until 0 is entered.# Prints the average value.count=0sum=0.0number=1# set to something that will not exit the while loop immediately.print"Enter 0 to exit the loop"whilenumber!=0:number=input("Enter a number: ")ifnumber!=0:count=count+1sum=sum+numberprint"The average was:",sum/count
Sample runs:
Enter 0 to exit the loopEnter a number:3Enter a number:5Enter a number:0The average was: 4.0
Enter 0 to exit the loopEnter a number:1Enter a number:4Enter a number:3Enter a number:0The average was: 2.66666666667
average2.py
# keeps asking for numbers until count numbers have been entered.# Prints the average value.sum=0.0print"This program will take several numbers then average them"count=input("How many numbers would you like to average: ")current_count=0whilecurrent_count<count:current_count=current_count+1print"Number",current_countnumber=input("Enter a number: ")sum=sum+numberprint"The average was:",sum/count
Sample runs:
This program will take several numbers then average themHow many numbers would you like to average:2Number 1Enter a number:3Number 2Enter a number:5The average was: 4.0
This program will take several numbers then average themHow many numbers would you like to average:3Number 1Enter a number:1Number 2Enter a number:4Number 3Enter a number:3The average was: 2.66666666667
Modify the higher or lower program from this section to keep track of how many times the user has entered the wrong number. If it is more than 3 times, print"That must have been complicated."
number=42guess=0count=0whileguess!=number:count=count+1guess=input('Guess a number: ')ifguess>number:print'Too high'elifguess<number:print'Too low'else:print'Just right'breakifcount>2:print'That must have been complicated.'break
Write a program that asks for two numbers. If the sum of the numbers is greater than 100, print "That is a big number."
number1=input('1st number: ')number2=input('2nd number: ')ifnumber1+number2>100:print'That is a big number.'
Write a program that asks the user their name, if they enter your namesay "That is a nice name", if they enter "John Cleese" or "MichaelPalin", tell them how you feel about them ;), otherwise tell them "Youhave a nice name."
name=raw_input('Your name: ')ifname=='Ada':print'That is a nice name.'elifname=='John Cleese'orname=='Michael Palin':print'... some funny text.'else:print'You have a nice name.'
By now if you have been messing around with the programs you have probably found that sometimes the program does something you didn't want it to do. This is fairly common. Debugging is the process of figuring out what the computer is doing and then getting it to do what you want it to do. This can be tricky. I once spent nearly a week tracking down and fixing a bug that was caused by someone putting anx where ay should have been.
This chapter will be more abstract than previous chapters.
The first thing to do (this sounds obvious) is to figure out what theprogram should be doing if it is running correctly. Come up with sometest cases and see what happens. For example, let's say I have aprogram to compute the perimeter of a rectangle (the sum of the lengthof all the edges). I have the following test cases:
| height | width | perimeter |
|---|---|---|
| 3 | 4 | 14 |
| 2 | 3 | 10 |
| 4 | 4 | 16 |
| 2 | 2 | 8 |
| 5 | 1 | 12 |
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 find out what the computer isdoing.
More commonly some of the test cases will work and some will not. If that is the case you should try and figure out what the working ones have in common. For example here is the output for a perimeter program (you get to see the code in a minute):
Height:3Width:4perimeter = 15
Height:2Width:3perimeter = 11
Height:4Width:4perimeter = 16
Height:2Width:2perimeter = 8
Height:5Width:1perimeter = 8
Notice that it didn't work for the first two inputs, it worked for the nexttwo and it didn't work on the last one. Try and figure out what is in common with the working ones. Once you have some idea what the problem is finding thecause is easier. With your own programs you should try more test cases if you need them.
The next thing to do is to look at the source code. One of the most important things to do while programming is reading source code. The primary way to do this is code walkthroughs.
A code walkthrough starts at the first line, and works its way down until the program is done.While loops andif statements mean that some lines may never be run and some lines are run many times. At each line you figure out what Python has done.
Lets start with the simple perimeter program. Don't type it in, you are going to read it, not run it. The source code is:
height=input("Height: ")width=input("Width: ")print"perimeter =",width+height+width+width
height = input("Height: ") Height:, waits for the user to type a number in, and puts that in the variable height.width = input("Width: ")Width:, waits for the user to type a number in, and puts what the user types in the variable width.print "perimeter = ", width + height + width + width (It may also run a function in the current line, but that's a future chapter.) What does that line do?perimeter =, then it printswidth + height + width + width.width + height + width + width calculate the perimeter properly?The next program we will do a code walkthrough for is a program that is supposed to print out 5 dots on the screen. However, this is what the program is outputting:
. . . .
And here is the program:
number=5whilenumber>1:print".",number=number-1print
This program will be more complex to walkthrough since it now has indented portions (or control structures). Let us begin.
number = 5while number > 1:while statements in general look at their expression, and if it is true they do the next indented block of code, otherwise they skip the next indented block of code.number > 1 is true then the next two lines will be run.number > 1?number was5 and5 > 1 so yes. while was true the next line is:print ".",number = number - 1 since that is following line and there are no indent changes.number - 1, which is the current value ofnumber (or 5) subtracts 1 from it, and makes that the new value of number. So basically it changes number's value from 5 to 4.while loop, so we have to go back to thewhile clause which iswhile number > 1:4 > 1 the while loop continues.print ".",number = number - 1while number > 1:3 > 1 so the while loop continues.print ".",number = number - 1while number > 1:2 > 1 the while loop continues.print ".",number = number - 1while number > 1:1 > 1 is false (one is not greater than one), the while loop exits.printwhile number > 0: Another way would be to change the conditional to:number >= 1 There are a couple others.You need to figure out what the program is doing. You need to figure out what the program should do. Figure out what the difference between the two is. Debugging is a skill that has to be practiced to be learned. If you can't figure it out after an hour, take a break, talk to someone about the problem or contemplate the lint in your navel. Come back in a while and you will probably have new ideas about the problem. Good luck.
To start off this chapter I am going to give you an example of what you could do but shouldn't (so don't type it in):
a=23b=-23ifa<0:a=-aifb<0:b=-b#Or use the command: elif (if+else)ifa==b:print"The absolute values of",a,"and",b,"are equal"else:print"The absolute values of",a,"and",b,"are different"
with the output being:
The absolute values of 23 and 23 are equal
The program seems a little repetitive. Programmers hate to repeat things -- that's what computers are for, after all! (Note also that finding the absolute value changed the value of the variable, which is why it is printing out 23, and not -23 in the output.) Fortunately Python allows you to create functions to remove duplication. Here is the rewritten example:
defabsolute_value(n):ifn<0:n=-nreturnna=23b=-23ifabsolute_value(a)==absolute_value(b):print"The absolute values of",a,"and",b,"are equal"else:print"The absolute values of",a,"and",b,"are different"
with the output being:
The absolute values of 23 and -23 are equal
The key feature of this program is thedef statement. Thedef keyword(short for "define") starts a function definition. "def" is followed by the name of the function "absolute_value". Next, comes the single function parameter named, "n". A parameter holds a value passed into the function from the program that "calls" the function. Parameters of a function in thedef statement, must be enclosed within a parenthesis. The value that is passed to a function parameter is called an argument. So for now, a parameter and argument points to the same thing. The block of indented statements after the ":" are then executed whenever the function is used. The statements within the function continue to be run until either the indented statements end, or a "return" statement is encountered. Thereturn statement returns a value back to the place where the function was called in the calling program.
Notice how the values ofa andb are not changed. Functions can be used to repeat tasks that don't return values. Here are some examples:
defhello():print"Hello"defarea(w,h):returnw*hdefprint_welcome(name):print"Welcome",namehello()hello()print_welcome("Fred")w=4h=5print"width =",w,"height =",h,"area =",area(w,h)
with output being:
HelloHelloWelcome Fredwidth = 4 height = 5 area = 20
That example shows some more stuff that you can do with functions. Notice that you can use one or more parameters, or none at all. Notice also that a function doesn't necessarily need to "return" a value, so areturn statement is optional.
When eliminating repeated code, you often notice that variables are repeated in the code. In Python, these are dealt with in a special way. So far, all variables we have seen are global variables. Functions work with a special type of variables called local variables. These variables only exist within the function and only while the function is running. When a local variable has the same name as another variable (such as a global variable), the local variable hides the other. Sound confusing? Well, these next examples (which are a bit contrived) should help clear things up.
a=4defprint_func():a=17print"in print_func a = ",aprint_func()print"a = ",a,"which is global variable assigned prior to the function print_func"
When run, we will receive an output of:
in print_func a = 17a = 4 which is global variable assigned prior to the function print_func
Variable assignments inside a function do not override global variables, they exist only inside the function. Even thougha was assigned a new value inside the function, this newly assigned value exists only within theprint_func function. After the function finishes running and the value of ana variable is printed again, we see the value assigned to the globala variable being printed.
a_var=10b_var=15c_var=25defa_func(a_var):print("in a_func a_var = ",a_var)b_var=100+a_vard_var=2*a_varprint("in a_func b_var = ",b_var)print("in a_func d_var = ",d_var)print("in a_func c_var = ",c_var)returnb_var+10c_var=a_func(b_var)print("a_var = ",a_var)print("b_var = ",b_var)print("c_var = ",c_var)print("d_var = ",d_var)
The output is:
in a_func a_var = 15 in a_func b_var = 115 in a_func d_var = 30 in a_func c_var = 25 a_var = 10 b_var = 15 c_var = 125 d_var = Traceback (most recent call last): File "C:\Python24\def2", line 19, in -toplevel- print "d_var = ", d_var NameError: name 'd_var' is not defined
In this example the variablesa_var,b_var, andd_var are all local variables when they are inside the functiona_func. After the statementreturn b_var + 10 is run, they all cease to exist. The variablea_var is "automatically" a local variable since it is a parameter named by the function definition. The variablesb_var andd_var are local variables since they appear on the left of an equals sign within the function in the statements:b_var = 100 + a_var andd_var = 2 * a_var.
Inside of the functiona_var has no value assigned to it. When the function is called withc_var = a_func(b_var), 15 is assigned toa_var since at that point in timeb_var is 15, making the call to the functiona_func(15). This ends up setting the value ofa_var to 15 when it is inside ofa_func function.
As you can see, once the function finishes running, the local variablesa_var andb_var that had hidden the global variables of the same name are gone. Then the statementprint "a_var = ", a_var prints the value10 rather than the value15 since the local variable that hid the global variable is gone.
Another thing to notice is theNameError that happens at the end. This appears since the variabled_var no longer exists sincea_func finished. All the local variables are deleted when the functionexits. If you want to get something back from a function, then you will have to usereturn statement within the function.
One last thing to notice is that the value ofc_var remains unchanged insidea_func since it is not a parameter and it never appears on the left of an equals sign inside of the functiona_func. When a global variable is accessed inside a function, the function uses only value of the global variable but it cannot change the value assigned to the global variable outside the function.
Functions allow local variables that exist only inside the function and can hide other variables that are outside the function.
temperature2.py
# converts temperature to fahrenheit or celsiusdefprint_options():print"Options:"print" 'p' print options"print" 'c' convert from celsius"print" 'f' convert from fahrenheit"print" 'q' quit the program"defcelsius_to_fahrenheit(c_temp):return9.0/5.0*c_temp+32deffahrenheit_to_celsius(f_temp):return(f_temp-32.0)*5.0/9.0choice="p"whilechoice!="q":ifchoice=="c":temp=input("Celsius temperature: ")print"Fahrenheit:",celsius_to_fahrenheit(temp)elifchoice=="f":temp=input("Fahrenheit temperature: ")print"Celsius:",fahrenheit_to_celsius(temp)elifchoice=="p":print_options()choice=raw_input("option: ")
Sample Run:
Options: 'p' print options 'c' convert from celsius 'f' convert from fahrenheit 'q' quit the programoption:cCelsius temperature:30 Fahrenheit: 86.0option:fFahrenheit temperature:60Celsius: 15.5555555556option:q
area2.py
# By Amos Satterleeprintdefhello():print'Hello!'defarea(width,height):returnwidth*heightdefprint_welcome(name):print'Welcome,',namename=raw_input('Your Name: ')hello(),print_welcome(name)printprint'To find the area of a rectangle,'print'enter the width and height below.'printw=input('Width: ')whilew<=0:print'Must be a positive number'w=input('Width: ')h=input('Height: ')whileh<=0:print'Must be a positive number'h=input('Height: ')print'Width =',w,'Height =',h,'so Area =',area(w,h)
Sample Run:
Your Name:JoshHello!Welcome, JoshTo find the area of a rectangle,enter the width and height below.Width:-4Must be a positive numberWidth:4Height:3Width = 4 Height = 3 so Area = 12
Rewrite the area2.py program from the Examples above to have a separate function for the area of a square, the area of a rectangle, and the area of a circle (3.14 * radius ** 2). This program should include a menu interface.
Rewrite the area2.py program from the Examples above to have a separate function for the area of a square, the area of a rectangle, and the area of a circle (3.14 * radius ** 2). This program should include a menu interface.
defsquare(length):returnlength*lengthdefrectangle(width,height):returnwidth*heightdefcircle(radius):return3.14*radius**2defoptions():printprint"Options:"print"s = calculate the area of a square."print"c = calculate the area of a circle."print"r = calculate the area of a rectangle."print"q = quit"printprint"This program will calculate the area of a square, circle or rectangle."choice="x"options()whilechoice!="q":choice=raw_input("Please enter your choice: ")ifchoice=="s":length=input("Length of square: ")print"The area of this square is",square(length)options()elifchoice=="c":radius=input("Radius of the circle: ")print"The area of the circle is",circle(radius)options()elifchoice=="r":width=input("Width of the rectangle: ")height=input("Height of the rectangle: ")print"The area of the rectangle is",rectangle(width,height)options()elifchoice=="q":print"",else:print"Unrecognized option."options()
Some people find this section useful, and some find it confusing. If you find it confusing you can skip it (or just look at the examples.) Now we will do a walk through for the following program:
defmult(a,b):ifb==0:return0rest=mult(a,b-1)value=a+restreturnvalueresult=mult(3,2)print"3 * 2 = ",result
3*2=6
Basically this program creates a positive integer multiplication function(that is far slower than the built in multiplication function) and thendemonstrates this function with a use of the function. This program demonstrates the use of recursion, that is a form of iteration (repetition) in which there is a function that repeatedly calls itself until an exit condition is satisfied. It uses repeated additions to give the same result as mutiplication: e.g. 3 + 3 (addition) gives the same result as 3 * 2 (multiplication).
RUN 1
defmult(a,b):ifb==0:return0rest=mult(a,b-1)value=a+restreturnvalue
result = mult(3, 2) is run.mult(3, 2) to the variableresult.mult(3, 2) return?mult function to find out.RUN 2
a gets the value 3 assigned to it and the variableb gets the value 2 assigned to it.if b == 0: is run. Sinceb has the value 2 this is false so the linereturn 0 is skipped.rest = mult(a, b - 1) is run. This line sets the local variablerest to the value ofmult(a, b - 1). The value of a is 3 and the value of b is 2 so the function call ismult(3,1)mult(3, 1) ? mult with the parameters 3 and 1.defmult(3,2):ifb==0:return0rest=mult(3,2-1)value=3+restreturnvalue
RUN 3
a has the value 3 and b has the value 1. Since these are local values these do not affect the previous values ofa andb. b has the value 1 the if statement is false, so the next line becomesrest = mult(a, b - 1).mult(3, 0) to rest.a has the value 3 andb has the value 0.if b == 0:. b has the value 0 so the next line to run isreturn 0return 0 do?mult(3, 0) has the value 0. Now we know what the linerest = mult(a, b - 1) did since we have run the functionmult with the parameters 3 and 0. We have finished runningmult(3, 0) and are now back to running mult(3, 1). The variablerest gets assigned the value 0.value = a + rest is run next. In this run of the function,a = 3 andrest = 0 so nowvalue = 3.return value is run. This returns 3 from the function. This also exits from the run of the function mult(3, 1). Afterreturn is called, we go back to running mult(3, 2). mult(3, 2)?a = 3 andb = 2 and were examining the linerest = mult(a, b - 1).rest get 3 assigned to it. The next linevalue = a + rest setsvalue to3 + 3 or 6.result = mult(3, 2). Now the return value can be assigned to the variableresult.print "3 * 2 = ", result is run.3 * 2 = and the value ofresult which is 6. The complete line printed is3 * 2 = 6x * 0 = 0). The second is that a number times another number is equal to the first number plus the first number times one less than the second number (x * y = x + x * (y - 1)). So what happens is3 * 2 is first converted into 3 + 3 * 1. Then3 * 1 is converted into3 + 3 * 0. Then we know that any number times 0 is 0 so3 * 0 is 0. Then we can calculate that3 + 3 * 0 is3 + 0 which is3. Now we know what3 * 1 is so we can calculate that3 + 3 * 1 is3 + 3 which is6.This is how the whole thing works:
mult(3, 2)3 + mult(3, 1)3 + 3 + mult(3, 0)3 + 3 + 03 + 36
Should you still have problems with this example, look at the process backwards. What is the laststep that happens? We can easily make out that the result ofmult(3, 0) is0. Sinceb is0, the functionmult(3, 0) will return0 and stop.
So what does the previous step do?mult(3, 1) does not return0becauseb is not0. So the next lines are executed:rest = mult (a, b - 1), which isrest = mult (3, 0), which is0 as we just worked out. So now the variablerest is set to0.
The next line adds the value ofrest toa, and sincea is3 andrestis0, the result is3.
Now we know that the functionmult(3, 1) returns3. But we want toknow the result ofmult(3,2). Therefore, we need to jump back to thestart of the program and execute it one more round:mult(3, 2) setsrest to the result ofmult(3, 1). We knowfrom the last round that this result is3. Thenvalue calculates asa + rest,i. e.3 + 3. Then the result of 3 * 2 is printed as 6.
The point of this example is that the functionmult(a, b) starts itself insideitself. It does this untilb reaches0 and then calculates the result as explained above.
Programming constructs of this kind are calledrecursive and probably the most intuitive definition ofrecursion is:
These last two sections were recently written. If you have anycomments, found any errors or think I need more/clearer explanationsplease email. I have been known in the past to make simple thingsincomprehensible. If the rest of the tutorial has made sense, but thissection didn't, it is probably my fault and I would like to know.Thanks.
factorial.py
#defines a function that calculates the factorialdeffactorial(n):ifn<=1:return1returnn*factorial(n-1)print"2! =",factorial(2)print"3! =",factorial(3)print"4! =",factorial(4)print"5! =",factorial(5)
Output:
2! = 23! = 64! = 245! = 120
countdown.py
defcount_down(n):printnifn>0:returncount_down(n-1)count_down(5)
Output:
543210
Commented_mult.py
# The comments below have been numbered as steps, to make explanation# of the code easier. Please read according to those steps.# (step number 1, for example, is at the bottom)defmult(a,b):# (2.) This function will keep repeating itself, because....ifb==0:return0rest=mult(a,b-1)# (3.) ....Once it reaches THIS, the sequence starts over again and goes back to the top!value=a+restreturnvalue# (4.) therefore, "return value" will not happen until the program gets past step 3 aboveprint"3 * 2 = ",mult(3,2)# (1.) The "mult" function will first initiate here# The "return value" event at the end can therefore only happen# once b equals zero (b decreases by 1 everytime step 3 happens).# And only then can the print command at the bottom be displayed.# See it as kind of a "jump-around" effect. Basically, all you# should really understand is that the function is reinitiated# WITHIN ITSELF at step 3. Therefore, the sequence "jumps" back# to the top.
Commented_factorial.py
# Another "jump-around" function example:deffactorial(n):# (2.) So once again, this function will REPEAT itself....ifn<=1:return1returnn*factorial(n-1)# (3.) Because it RE-initiates HERE, and goes back to the top.print"2! =",factorial(2)# (1.) The "factorial" function is initiated with this lineprint"3! =",factorial(3)print"4! =",factorial(4)print"5! =",factorial(5)
Commented_countdown.py
# Another "jump-around", nice and easy:defcount_down(n):# (2.) Once again, this sequence will repeat itself....printnifn>0:returncount_down(n-1)# (3.) Because it restarts here, and goes back to the topcount_down(5)# (1.) The "count_down" function initiates here
You have already seen ordinary variables that store a single value. However other variable types can hold more than one value. The simplest type is called a list. Here is an example of a list being used:
which_one=input("What month (1-12)? ")months=['January','February','March','April','May','June','July','August','September','October','November','December']if1<=which_one<=12:print"The month is",months[which_one-1]
and an output example:
What month (1-12)?3The month is March
In this example themonths is a list.months is defined with the lines months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', and'August', 'September', 'October', 'November', 'December'] (note that a\ could also be used to split a long line, but that is not necessary in this case because Python is intelligent enough to recognize that everything within brackets belongs together). The[ and] start and end the list with commas (,) separating the list items. The list is used inmonths[which_one - 1]. A list consists of items that are numbered starting at 0. In other words if you wanted January you would usemonths[0]. Give a list a number and it will return the value that is stored at that location.
The statement if 1 <= which_one <= 12: will only be true if which_one is between one and twelve inclusive (in other words it is what you would expect if you have seen that in algebra).
Lists can be thought of as a series of boxes. Each box has a different value. For example, the boxes created bydemolist = ['life', 42, 'the universe', 6, 'and', 9] would look like this:
| box number | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| demolist | "life" | 42 | "the universe" | 6 | "and" | 9 |
Each box is referenced by its number so the statementdemolist[0] would get'life',demolist[1] would get42 and so on up todemolist[5] getting9.
The next example is just to show a lot of other stuff lists can do (for once I don't expect you to type it in, but you should probably play around with lists until you are comfortable with them.). Here goes:
demolist=["life",42,"the universe",6,"and",9]print"demolist = ",demolistdemolist.append("everything")print"after 'everything' was appended demolist is now:"printdemolistprint"len(demolist) =",len(demolist)print"demolist.index(42) =",demolist.index(42)print"demolist[1] =",demolist[1]# Next we will loop through the listc=0whilec<len(demolist):print"demolist[",c,"] =",demolist[c]c=c+1deldemolist[2]print"After 'the universe' was removed demolist is now:"printdemolistif"life"indemolist:print"'life' was found in demolist"else:print"'life' was not found in demolist"if"amoeba"indemolist:print"'amoeba' was found in demolist"if"amoeba"notindemolist:print"'amoeba' was not found in demolist"demolist.sort()print"The sorted demolist is",demolist
The output is:
demolist = ['life', 42, 'the universe', 6, 'and', 9]after 'everything' was appended demolist is now:['life', 42, 'the universe', 6, 'and', 9, 'everything']len(demolist) = 7demolist.index(42) = 1demolist[1] = 42demolist[ 0 ] = lifedemolist[ 1 ] = 42demolist[ 2 ] = the universedemolist[ 3 ] = 6demolist[ 4 ] = anddemolist[ 5 ] = 9demolist[ 6 ] = everythingAfter 'the universe' was removed demolist is now:['life', 42, 6, 'and', 9, 'everything']'life' was found in demolist'amoeba' was not found in demolistThe sorted demolist is [6, 9, 42, 'and', 'everything', 'life']
This example uses a whole bunch of new functions. Notice that you canjustprint a whole list. Next theappend function is usedto add a new item to the end of the list.len returns how manyitems are in a list. The valid indexes (as in numbers that can beused inside of the[]) of a list range from 0 tolen - 1. Theindex function tells where the first location of an item islocated in a list. Notice howdemolist.index(42) returns 1, andwhendemolist[1] is run it returns 42. The line# Next we will loop through the list is a just a reminder to the programmer (also called acomment). Python will ignore any lines that start with a#. Next the lines:
c=0whilec<len(demolist):print'demolist[',c,'] =',demolist[c]c=c+1
create a variablec, which starts at 0 and is incremented until it reaches the last index of the list. Meanwhile theprint statement prints out each element of the list. Thedel command can be used to remove a given element in a list. The next few lines use thein operator to test if an element is in or is not in a list. Thesort function sorts the list. This is useful if you need alist in order from smallest number to largest or alphabetical. Notethat this rearranges the list. In summary, for a list, the following operations occur:
| example | explanation |
|---|---|
demolist[2] | accesses the element at index 2 |
demolist[2] = 3 | sets the element at index 2 to be 3 |
del demolist[2] | removes the element at index 2 |
len(demolist) | returns the length ofdemolist |
"value" in demolist | isTrue if"value" is an element indemolist |
"value" not in demolist | isTrue if"value" is not an element indemolist |
demolist.sort() | sortsdemolist |
demolist.index("value") | returns the index of the first place that"value" occurs |
demolist.append("value") | adds an element"value" at the end of the list |
demolist.remove("value") | removes the first occurrence of value fromdemolist (same asdel demolist[demolist.index("value")]) |
This next example uses these features in a more useful way:
menu_item=0namelist=[]whilemenu_item!=9:print"--------------------"print"1. Print the list"print"2. Add a name to the list"print"3. Remove a name from the list"print"4. Change an item in the list"print"9. Quit"menu_item=input("Pick an item from the menu: ")ifmenu_item==1:current=0iflen(namelist)>0:whilecurrent<len(namelist):printcurrent,".",namelist[current]current=current+1else:print"List is empty"elifmenu_item==2:name=raw_input("Type in a name to add: ")namelist.append(name)elifmenu_item==3:del_name=raw_input("What name would you like to remove: ")ifdel_nameinnamelist:# namelist.remove(del_name) would work just as fineitem_number=namelist.index(del_name)delnamelist[item_number]# The code above only removes the first occurrence of# the name. The code below from Gerald removes all.# while del_name in namelist:# item_number = namelist.index(del_name)# del namelist[item_number]else:printdel_name,"was not found"elifmenu_item==4:old_name=raw_input("What name would you like to change: ")ifold_nameinnamelist:item_number=namelist.index(old_name)new_name=raw_input("What is the new name: ")namelist[item_number]=new_nameelse:printold_name,"was not found"print"Goodbye"
And here is part of the output:
--------------------1. Print the list2. Add a name to the list3. Remove a name from the list4. Change an item in the list9. QuitPick an item from the menu:2Type in a name to add:JackPick an item from the menu:2Type in a name to add:JillPick an item from the menu:10 . Jack1 . JillPick an item from the menu:3What name would you like to remove:JackPick an item from the menu:4What name would you like to change:JillWhat is the new name:Jill PetersPick an item from the menu:10 . Jill PetersPick an item from the menu:9Goodbye
That was a long program. Let's take a look at the source code. The linenamelist = [] makes the variablenamelist a list with no items (or elements). The next important line iswhile menu_item != 9:. This line starts a loop that allows the menu system for this program. The next few lines display a menu and decide which part of the program to run.
The section
current=0iflen(namelist)>0:whilecurrent<len(namelist):printcurrent,".",namelist[current]current=current+1else:print"List is empty"
goes through the list and prints each name.len(namelist) tells how many items are in the list. Iflen returns0, then the list is empty.
Then, a few lines later, the statementnamelist.append(name) appears. It uses theappend function to add an item to the end of the list. Jump down another two lines, and notice this section of code:
item_number=namelist.index(del_name)delnamelist[item_number]
Here theindex function is used to find the index value that will be used later to remove the item.del namelist[item_number] is used to remove a element of the list.
The next section
old_name=raw_input("What name would you like to change: ")ifold_nameinnamelist:item_number=namelist.index(old_name)new_name=raw_input("What is the new name: ")namelist[item_number]=new_nameelse:printold_name,"was not found"
usesindex to find theitem_number and then putsnew_name where theold_name was.
Congratulations, with lists under your belt, you now know enough of the languagethat you could do any computations that a computer can do (this is technically known as Turing-Completeness). Of course, there are still many features thatare used to make your life easier.
test.py
## This program runs a test of knowledge# First get the test questions# Later this will be modified to use file io.defget_questions():# notice how the data is stored as a list of listsreturn[["What color is the daytime sky on a clear day? ","blue"],["What is the answer to life, the universe and everything? ","42"],["What is a three letter word for mouse trap? ","cat"]]# This will test a single question# it takes a single question in# it returns True if the user typed the correct answer, otherwise Falsedefcheck_question(question_and_answer):# extract the question and the answer from the listquestion=question_and_answer[0]answer=question_and_answer[1]# give the question to the usergiven_answer=raw_input(question)# compare the user's answer to the testers answerifanswer==given_answer:print"Correct"returnTrueelse:print"Incorrect, correct was:",answerreturnFalse# This will run through all the questionsdefrun_test(questions):iflen(questions)==0:print"No questions were given."# the return exits the functionreturnindex=0right=0whileindex<len(questions):# Check the questionifcheck_question(questions[index]):right=right+1index=index+1# go to the next questionelse:index=index+1# notice the order of the computation, first multiply, then divideprint"You got",right*100/len(questions),\"% right out of",len(questions)# now let's run the questionsrun_test(get_questions())
The valuesTrue andFalse point to 1 and 0, respectively. They are often used in sanity checks, loop conditions etc. You will learn more about this a little bit later (chapterBoolean Expressions).
Sample Output:
What color is the daytime sky on a clear day?greenIncorrect, correct was: blueWhat is the answer to life, the universe and everything?42CorrectWhat is a three letter word for mouse trap?catCorrectYou got 66 % right out of 3
Expand the test.py program so it has a menu giving the option of takingthe test, viewing the list of questions and answers, and an option toquit. Also, add a new question to ask, "What noise does a trulyadvanced machine make?" with the answer of "ping".
Expand the test.py program so it has menu giving the option of takingthe test, viewing the list of questions and answers, and an option toquit. Also, add a new question to ask, "What noise does a trulyadvanced machine make?" with the answer of "ping".
## This program runs a test of knowledgequestions=[["What color is the daytime sky on a clear day? ","blue"],["What is the answer to life, the universe and everything? ","42"],["What is a three letter word for mouse trap? ","cat"],["What noise does a truly advanced machine make?","ping"]]# This will test a single question# it takes a single question in# it returns True if the user typed the correct answer, otherwise Falsedefcheck_question(question_and_answer):# extract the question and the answer from the listquestion=question_and_answer[0]answer=question_and_answer[1]# give the question to the usergiven_answer=raw_input(question)# compare the user's answer to the testers answerifanswer==given_answer:print"Correct"returnTrueelse:print"Incorrect, correct was:",answerreturnFalse# This will run through all the questionsdefrun_test(questions):iflen(questions)==0:print"No questions were given."# the return exits the functionreturnindex=0right=0whileindex<len(questions):# Check the questionifcheck_question(questions[index]):right=right+1# go to the next questionindex=index+1# notice the order of the computation, first multiply, then divideprint"You got",right*100/len(questions),\"% right out of",len(questions)#showing a list of questions and answersdefshowquestions(questions):q=0whileq<len(questions):a=0print"Q:",questions[q][a]a=1print"A:",questions[q][a]q=q+1# now let's define the menu functiondefmenu():print"-----------------"print"Menu:"print"1 - Take the test"print"2 - View a list of questions and answers"print"3 - View the menu"print"5 - Quit"print"-----------------"choice="3"whilechoice!="5":ifchoice=="1":run_test(questions)elifchoice=="2":showquestions(questions)elifchoice=="3":menu()printchoice=raw_input("Choose your option from the menu above: ")
And here is the new typing exercise for this chapter:
onetoten=range(1,11)forcountinonetoten:printcount
and the ever-present output:
12345678910
The output looks awfully familiar but the program code looks different. The first line uses therange function. Therange function uses two arguments like thisrange(start, finish).start is the first number that is produced.finish is one larger than the last number. Note that this program could have been done in a shorter way:
forcountinrange(1,11):printcount
Here are some examples to show what happens with therange command:
>>>range(1, 10)[1, 2, 3, 4, 5, 6, 7, 8, 9]>>>range(-32, -20)[-32, -31, -30, -29, -28, -27, -26, -25, -24, -23, -22, -21]>>>range(5,21)[5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]>>>range(5)[0, 1, 2, 3, 4]>>>range(21, 5)[]
The next linefor count in onetoten: uses thefor control structure. Afor control structure looks likefor variable in list:.list is gone through starting with the first element of the list and going to the last. Asfor goes through each element in a list it puts each intovariable. That allowsvariable to be used in each successive time thefor loop is run through. Here is another example (you don't have to type this) to demonstrate:
demolist=['life',42,'the universe',6,'and',9,'everything']foritemindemolist:print"The Current item is:",printitem
The output is:
The Current item is: lifeThe Current item is: 42The Current item is: the universeThe Current item is: 6The Current item is: andThe Current item is: 9The Current item is: everything
Notice how thefor loop goes through and sets item to each element in the list. Notice how if you don't wantprint to go to the next line add a comma at the end of the statement (i.e. if you want to print something else on that line). So, what isfor good for? The first use is to go through all the elements of a list and do something with each of them. Here's a quick way to add up all the elements:
list=[2,4,6,8]sum=0fornuminlist:sum=sum+numprint"The sum is:",sum
with the output simply being:
The sum is: 20
Or you could write a program to find out if there are any duplicates in a list like this program does:
list=[4,5,7,8,9,1,0,7,10]list.sort()prev=list[0]dellist[0]foriteminlist:ifprev==item:print"Duplicate of",prev,"found"prev=item
and for good measure:
Duplicate of 7 Found
Okay, so how does it work? Here is a special debugging version to help you understand (you don't need to type this in):
l=[4,5,7,8,9,1,0,7,10]print"l = [4, 5, 7, 8, 9, 1, 0, 7, 10]","\t\tl:",ll.sort()print"l.sort()","\t\tl:",lprev=l[0]print"prev = l[0]","\t\tprev:",prevdell[0]print"del l[0]","\t\tl:",lforiteminl:ifprev==item:print"Duplicate of",prev,"found"print"if prev == item:","\tprev:",prev,"\titem:",itemprev=itemprint"prev = item","\t\tprev:",prev,"\titem:",item
with the output being:
l = [4, 5, 7, 8, 9, 1, 0, 7, 10] l: [4, 5, 7, 8, 9, 1, 0, 7, 10]l.sort() l: [0, 1, 4, 5, 7, 7, 8, 9, 10]prev = l[0] prev: 0del l[0] l: [1, 4, 5, 7, 7, 8, 9, 10]if prev == item: prev: 0 item: 1prev = item prev: 1 item: 1if prev == item: prev: 1 item: 4prev = item prev: 4 item: 4if prev == item: prev: 4 item: 5prev = item prev: 5 item: 5if prev == item: prev: 5 item: 7prev = item prev: 7 item: 7Duplicate of 7 foundif prev == item: prev: 7 item: 7prev = item prev: 7 item: 7if prev == item: prev: 7 item: 8prev = item prev: 8 item: 8if prev == item: prev: 8 item: 9prev = item prev: 9 item: 9if prev == item: prev: 9 item: 10prev = item prev: 10 item: 10
The reason I put so manyprint statements in the code was so that you can see what is happening in each line. (By the way, if you can't figure out why a program is not working, try putting in lots of print statements so you can see what is happening.) First the program starts with a boring old list. Next the program sorts the list. This is so that any duplicates get put next to each other. The program then initializes aprev(ious) variable. Next the first element of the list is deleted so that the first item is not incorrectly thought to be a duplicate. Next afor loop is gone into. Each item of the list is checked to see if it is the same as the previous. If it is a duplicate was found. The value ofprev is then changed so that the next time thefor loop is run throughprev is the previous item to the current. Sure enough, the 7 is found to be a duplicate. (Notice how\t is used to print a tab.)
The other way to usefor loops is to do something a certain number of times. Here is some code to print out the first 9 numbers of the Fibonacci series:
a=1b=1forcinrange(1,10):printa,n=a+ba=bb=n
with the surprising output:
1 1 2 3 5 8 13 21 34
Everything that can be done withfor loops can also be done withwhile loops butfor loops give an easy way to go through all the elements in a list or to do something a certain number of times.
Here is a little example of boolean expressions (you don't have to type it in):
a=6b=7c=42print1,a==6print2,a==7print3,a==6andb==7print4,a==7andb==7print5,nota==7andb==7print6,a==7orb==7print7,a==7orb==6print8,not(a==7andb==6)print9,nota==7andb==6
With the output being:
1 True2 False3 True4 False5 True6 True7 False8 True9 False
What is going on? The program consists of a bunch of funny lookingprint statements. Eachprint statement prints a number and an expression. The number is to help keep track of which statement I am dealing with. Notice how each expression ends up being eitherFalse orTrue. In Python, false can also be written as 0 and true as 1.
The lines:
print1,a==6print2,a==7
print out aTrue and aFalse respectively just as expected since the first is true and the second is false. The third print,print 3, a == 6 and b == 7, is a little different. The operatorand means if both the statement before and the statement after are true then the whole expression is true otherwise the whole expression is false. The next line,print 4, a == 7 and b == 7, shows how if part of anand expression is false, the whole thing is false. The behavior ofand can be summarized as follows:
| expression | result |
|---|---|
trueand true | true |
trueand false | false |
falseand true | false |
falseand false | false |
Notice that if the first expression is false Python does not check the second expression since it knows the whole expression is false.
The next line,print 5, not a == 7 and b == 7, uses thenot operator.not just gives the opposite of the expression. (The expression could be rewritten as print 5, a != 7 and b == 7). Here is the table:
| expression | result |
|---|---|
not true | false |
not false | true |
The two following lines,print 6, a == 7 or b == 7 andprint 7, a == 7 or b == 6, use theor operator. Theor operator returns true if the first expression is true, or if the second expression is true or both are true. If neither are true it returns false. Here's the table:
| expression | result |
|---|---|
trueor true | true |
trueor false | true |
falseor true | true |
falseor false | false |
Notice that if the first expression is true Python doesn't check the second expression since it knows the whole expression is true. This works sinceor is true if at least one half of the expression is true. The first part is true so the second part could be either false or true, but the whole expression is still true.
The next two lines,print 8, not (a == 7 and b == 6) andprint 9, not a == 7 and b == 6, show that parentheses can be used to group expressions and force one part to be evaluated first. Notice that the parentheses changed the expression from false to true. This occurred since the parentheses forced thenot to apply to the whole expression instead of just thea == 7 portion.
Here is an example of using a boolean expression:
list=["Life","The Universe","Everything","Jack","Jill","Life","Jill"]# make a copy of the list. See the More on Lists chapter to explain what [:] means.copy=list[:]# sort the copycopy.sort()prev=copy[0]delcopy[0]count=0# go through the list searching for a matchwhilecount<len(copy)andcopy[count]!=prev:prev=copy[count]count=count+1# If a match was not found then count can't be < len# since the while loop continues while count is < len# and no match is foundifcount<len(copy):print"First Match:",prev
And here is the output:
First Match: Jill
This program works by continuing to check for matchwhile count < len(copy) and copy[count] is not equal to prev. When eithercount is greater than the last index ofcopy or a match has been found theand is no longer true so the loop exits. Theif simply checks to make sure that thewhile exited because a match was found.
The other "trick" ofand is used in this example. If you look at the table forand notice that the third entry is "false and won't check". Ifcount >= len(copy) (in other wordscount < len(copy) is false) thencopy[count] is never looked at. This is because Python knows that if the first is false then they can't both be true. This is known as a short circuit and is useful if the second half of theand will cause an error if something is wrong. I used the first expression (count < len(copy)) to check and see ifcount was a valid index forcopy. (If you don't believe me remove the matches "Jill" and "Life", check that it still works and then reverse the order ofcount < len(copy) and copy[count] != prev tocopy[count] != prev and count < len(copy).)
Boolean expressions can be used when you need to check two or more different things at once.
A common mistake for people new to programming is a misunderstanding of the way that boolean operators works, which stems from the way the python interpreter reads these expressions. For example, after initially learning about "and " and "or" statements, one might assume that the expressionx == ('a' or 'b') would check to see if the variablex was equivalent to one of the strings'a' or'b'. This is not so. To see what I'm talking about, start an interactive session with the interpreter and enter the following expressions:
>>> 'a' == ('a' or 'b')>>> 'b' == ('a' or 'b')>>> 'a' == ('a' and 'b')>>> 'b' == ('a' and 'b')And this will be the unintuitive result:
>>> 'a' == ('a' or 'b')True>>> 'b' == ('a' or 'b')False>>> 'a' == ('a' and 'b')False >>> 'b' == ('a' and 'b')TrueAt this point, theand andor operators seem to be broken. It doesn't make sense that, for the first two expressions,'a' is equivalent to'a' or'b' while'b' is not. Furthermore, it doesn't make any sense that 'b' is equivalent to'a' and'b'. After examining what the interpreter does with boolean operators, these results do in fact exactly what you are asking of them, it's just not the same as what you think you are asking.
When the Python interpreter looks at anor expression, it takes the first statement and checks to see if it is true. If the first statement is true, then Python returns that object's value without checking the second statement. This is because for anor expression, the whole thing is true if one of the values is true; the program does not need to bother with the second statement. On the other hand, if the first value is evaluated as false Python checks the second half and returns that value. That second half determines the truth value of the whole expression since the first half was false. This "laziness" on the part of the interpreter is called "short circuiting" and is a common way of evaluating boolean expressions in many programming languages.
Similarly, for anand expression, Python uses a short circuit technique to speed truth value evaluation. If the first statement is false then the whole thing must be false, so it returns that value. Otherwise if the first value is true it checks the second and returns that value.
One thing to note at this point is that the boolean expression returns a value indicatingTrue orFalse, but that Python considers a number of different things to have a truth value assigned to them. To check the truth value of any given objectx, you can use the functionbool(x) to see its truth value. Below is a table with examples of the truth values of various objects:
| True | False |
|---|---|
| True | False |
| 1 | 0 |
| Numbers other than zero | The string 'None' |
| Nonempty strings | Empty strings |
| Nonempty lists | Empty lists |
| Nonempty dictionaries | Empty dictionaries |
Now it is possible to understand the perplexing results we were getting when we tested those boolean expressions before. Let's take a look at what the interpreter "sees" as it goes through that code:
First case:
>>> 'a' == ('a' or 'b') # Look at parentheses first, so evaluate expression "('a' or 'b')" # 'a' is a nonempty string, so the first value is True # Return that first value: 'a'>>> 'a' == 'a' # the string 'a' is equivalent to the string 'a', so expression is TrueTrueSecond case:
>>> 'b' == ('a' or 'b') # Look at parentheses first, so evaluate expression "('a' or 'b')" # 'a' is a nonempty string, so the first value is True # Return that first value: 'a'>>> 'b' == 'a' # the string 'b' is not equivalent to the string 'a', so expression is FalseFalseThird case:
>>> 'a' == ('a' and 'b') # Look at parentheses first, so evaluate expression "('a' and 'b')" # 'a' is a nonempty string, so the first value is True, examine second value # 'b' is a nonempty string, so second value is True # Return that second value as result of whole expression: 'b'>>> 'a' == 'b' # the string 'a' is not equivalent to the string 'b', so expression is FalseFalseFourth case:
>>> 'b' == ('a' and 'b') # Look at parentheses first, so evaluate expression "('a' and 'b')" # 'a' is a nonempty string, so the first value is True, examine second value # 'b' is a nonempty string, so second value is True # Return that second value as result of whole expression: 'b'>>> 'b' == 'b' # the string 'b' is equivalent to the string 'b', so expression is TrueTrueSo Python was really doing its job when it gave those apparently bogus results. As mentioned previously, the important thing is to recognize what value your boolean expression will return when it is evaluated, because it isn't always obvious.
Going back to those initial expressions, this is how you would write them out so they behaved in a way that you want:
>>> 'a' == 'a' or 'a' == 'b'True>>> 'b' == 'a' or 'b' == 'b'True>>> 'a' == 'a' and 'a' == 'b'False>>> 'b' == 'a' and 'b' == 'b'False
When these comparisons are evaluated they return truth values in terms of True or False, not strings, so we get the proper results.
password1.py
## This programs asks a user for a name and a password.# It then checks them to make sure the user is allowed in.name=raw_input("What is your name? ")password=raw_input("What is the password? ")ifname=="Josh"andpassword=="Friday":print"Welcome Josh"elifname=="Fred"andpassword=="Rock":print"Welcome Fred"else:print"I don't know you."
Sample runs
What is your name?JoshWhat is the password?FridayWelcome Josh
What is your name?BillWhat is the password?MoneyI don't know you.
Write a program that has a user guess your name, but they only get 3 chances to do so until the program quits.
Write a program that has a user guess your name, but they only get 3 chances to do so until the program quits.
print"Try to guess my name!"count=3name="Tony"guess=raw_input("What is my name? ")whilecount>1andguess!=name:print"You are wrong!"guess=raw_input("What is my name? ")count=count-1ifguess!=name:print"You are wrong!"# this message isn't printed in the third chance, so we print it nowprint"You ran out of chances."quitelse:print"Yes! My name is",name+"!"
This chapter is about dictionaries. If you open a dictionary, you should notice every entry consists of two parts, a word and the word's definition. The word is the key to finding out what a word means, and what the word means is considered the value for that key. In Python, dictionaries have keys and values. Keys are used to find values. Here is an example of a dictionary in use:
defprint_menu():print'1. Print Dictionary'print'2. Add definition'print'3. Remove word'print'4. Lookup word'print'5. Quit'printwords={}menu_choice=0print_menu()whilemenu_choice!=5:menu_choice=input("Type in a number (1-5): ")ifmenu_choice==1:print"Definitions:"forxinwords.keys():printx,": ",words[x]printelifmenu_choice==2:print"Add definition"name=raw_input("Word: ")means=raw_input("Definition: ")words[name]=meanselifmenu_choice==3:print"Remove word"name=raw_input("Word: ")ifnameinwords:delwords[name]printname," was removed."else:printname," was not found."elifmenu_choice==4:print"Lookup Word"name=raw_input("Word: ")ifnameinwords:print"The definition of ",name," is: ",words[name]else:print"No definition for ",name," was found."elifmenu_choice!=5:print_menu()
And here is my output:
1. Print Dictionary2. Add definition3. Remove word4. Lookup word5. QuitType in a number (1-5):2Add definitionWord:PythonDefinition:A snake, a programming language, and a British comedy.Type in a number (1-5):2Add definitionWord:DictionaryDefinition:A book where words are defined.Type in a number (1-5):1Definitions:Python: A snake, a programming language, and a British comedy.Dictionary: A book where words are defined.Type in a number (1-5):4Lookup WordWord:PythonThe definition of Python is: A snake, a programming language, and a British comedy.Type in a number (1-5):3Remove WordWord:DictionaryDictionary was removed.Type in a number (1-5):1Definitions:Python: A snake, a programming language, and a British comedy. Type in a number (1-5):5
This program is similar to the name list from the earlier chapter on lists (note that lists use indexes and dictionaries don't). Here's how the program works:
print_menu is defined.print_menu just prints a menu that is later used twice in the program.words = {}. All that line does is tell Python thatwords is a dictionary.forxinwords.keys():printx,": ",words[x]
words.keys() returns a list that is then used by thefor loop. The list returned bykeys() is not in any particular order so if you want it in alphabetic order it must be sorted. Similar to lists the statementwords[x] is used to access a specific member of the dictionary. Of course in this casex is a string.words[name] = means adds a word and definition to the dictionary. Ifname is already in the dictionarymeans replaces whatever was there before.ifnameinwords:delwords[name]
name in words returns true ifname is a key inwords but otherwise returns false. The linedel words[name] removes the keyname and the value associated with that key.ifnameinwords:print"The definition of ",name," is: ",words[name]
A recap: Dictionaries have keys and values. Keys can be strings ornumbers. Keys point to values. Values can be any type of variable(including lists or even dictionaries (those dictionaries or lists ofcourse can contain dictionaries or lists themselves (scary right? :-))). Here is an example of using a list in a dictionary:
max_points=[25,25,50,25,100]assignments=['hw ch 1','hw ch 2','quiz ','hw ch 3','test']students={'#Max':max_points}defprint_menu():print"1. Add student"print"2. Remove student"print"3. Print grades"print"4. Record grade"print"5. Print Menu"print"6. Exit"defprint_all_grades():print'\t',foriinrange(len(assignments)):printassignments[i],'\t',printkeys=students.keys()keys.sort()forxinkeys:printx,'\t',grades=students[x]print_grades(grades)defprint_grades(grades):foriinrange(len(grades)):printgrades[i],'\t','\t',printprint_menu()menu_choice=0whilemenu_choice!=6:printmenu_choice=input("Menu Choice (1-6): ")ifmenu_choice==1:name=raw_input("Student to add: ")students[name]=[0]*len(max_points)elifmenu_choice==2:name=raw_input("Student to remove: ")ifnameinstudents:delstudents[name]else:print"Student:",name,"not found"elifmenu_choice==3:print_all_grades()elifmenu_choice==4:print"Record Grade"name=raw_input("Student: ")ifnameinstudents:grades=students[name]print"Type in the number of the grade to record"print"Type a 0 (zero) to exit"foriinrange(len(assignments)):printi+1,assignments[i],'\t',printprint_grades(grades)which=1234whilewhich!=-1:which=input("Change which Grade: ")which=which-1if0<=which<len(grades):grade=input("Grade: ")grades[which]=gradeelifwhich!=-1:print"Invalid Grade Number"else:print"Student not found"elifmenu_choice!=6:print_menu()
and here is a sample output:
1. Add student2. Remove student3. Print grades4. Record grade5. Print Menu6. ExitMenu Choice (1-6):3 hw ch 1 hw ch 2 quiz hw ch 3 test #Max 25 25 50 25 100 Menu Choice (1-6):51. Add student2. Remove student3. Print grades4. Record grade5. Print Menu6. ExitMenu Choice (1-6):1Student to add:BillMenu Choice (1-6):4Record GradeStudent:BillType in the number of the grade to recordType a 0 (zero) to exit1 hw ch 1 2 hw ch 2 3 quiz 4 hw ch 3 5 test 0 0 0 0 0 Change which Grade:1Grade:25Change which Grade:2Grade:24Change which Grade:3Grade:45Change which Grade:4Grade:23Change which Grade:5Grade:95Change which Grade:0Menu Choice (1-6):3 hw ch 1 hw ch 2 quiz hw ch 3 test #Max 25 25 50 25 100Bill 25 24 45 23 95 Menu Choice (1-6):6
Here's how the program works. Basically the variablestudents isa dictionary with the keys being the name of the students and thevalues being their grades. The first two lines just create two lists.The next linestudents = {'#Max': max_points} creates a newdictionary with the key {#Max} and the value is set to be[25, 25, 50, 25, 100], since thats whatmax_points was when the assignment is made (I use the key#Max since# is sortedahead of any alphabetic characters). Nextprint_menu isdefined. Next theprint_all_grades function is defined in thelines:
defprint_all_grades():print'\t',foriinrange(len(assignments)):printassignments[i],'\t',printkeys=students.keys()keys.sort()forxinkeys:printx,'\t',grades=students[x]print_grades(grades)
Notice how first the keys are gotten out of thestudents dictionary with thekeys function in the linekeys = students.keys().keys is a list so all the functions for lists can be used on it. Next the keys are sorted in the linekeys.sort() since it is a list.for is used to go through all the keys. The grades are stored as a list inside the dictionary so the assignmentgrades = students[x] givesgrades the list that is stored at the keyx. The functionprint_grades just prints a list and is defined a few lines later.
The later lines of the program implement the various options of the menu. The linestudents[name] = [0] * len(max_points) adds a student to the key of their name. The notation[0] * len(max_points) just creates a list of 0's that is the same length as themax_points list.
The remove student entry just deletes a student similar to the telephone book example. The record grades choice is a little more complex. The grades are retrieved in the linegrades = students[name] gets a reference to the grades of the studentname. A grade is then recorded in the linegrades[which] = grade. You may notice thatgrades is never put back into the students dictionary (as in nostudents[name] = grades). The reason for the missing statement is thatgrades is actually another name forstudents[name] and so changinggrades changesstudent[name].
Dictionaries provide a easy way to link keys to values. This can be used to easily keep track of data that is attached to various keys.
Here's this chapter's typing exercise (name it cal.py).import actually looks for a file named calendar.py and reads it in. If the file is named calendar.py and it sees an "import calendar" it tries to read in itself which works poorly at best.)):
importcalendaryear=input("Type in the year number: ")calendar.prcal(year)
And here is part of the output I got:
Type in the year number: 2001 2001 January February March Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su1 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 1115 16 17 18 19 20 21 12 13 14 15 16 17 18 12 13 14 15 16 17 18 22 23 24 25 26 27 28 19 20 21 22 23 24 25 19 20 21 22 23 24 25 29 30 31 26 27 28 26 27 28 29 30 31
(I skipped some of the output, but I think you get the idea.) So what does the program do? The first lineimport calendar uses a new commandimport. The commandimport loads a module (in this case thecalendar module). To see the commands available in the standard modules either look in the library reference for python (if you downloaded it) or go tohttp://docs.python.org/library/. If you look at the documentation for the calendar module, it lists a function calledprcal that prints a calendar for a year. The linecalendar.prcal(year) uses this function. In summary to use a moduleimport it and then usemodule_name.function for functions in the module. Another way to write the program is:
fromcalendarimportprcalyear=input("Type in the year number: ")prcal(year)
This version imports a specific function from a module. Here is another program that uses the Python Library (name it something like clock.py) (press Ctrl and the 'c' key at the same time to terminate the program):
fromtimeimporttime,ctimeprev_time=""whileTrue:the_time=ctime(time())ifprev_time!=the_time:print"The time is:",ctime(time())prev_time=the_time
With some output being:
The time is: Sun Aug 20 13:40:04 2000The time is: Sun Aug 20 13:40:05 2000The time is: Sun Aug 20 13:40:06 2000The time is: Sun Aug 20 13:40:07 2000Traceback (innermost last): File "clock.py", line 5, in ? the_time = ctime(time())KeyboardInterrupt
The output is infinite of course so I canceled it (or the output at least continues until Ctrl+C is pressed). The program just does a infinite loop (True is always true, sowhile True: goes forever) and each time checks to see if the time has changed and prints it if it has. Notice how multiple names after the import statement are used in the linefrom time import time, ctime.
The Python Library contains many useful functions. These functions give your programs more abilities and many of them can simplify programming in Python.
Rewrite the High_low.py program from sectionDecisions to use a random integer between 0 and 99 instead of the hard-coded 78. Use the Python documentation to find an appropriate module and function to do this.
Rewrite the High_low.py program from sectionDecisions to use an random integer between 0 and 99 instead of the hard-coded 78. Use the Python documentation to find an appropriate module and function to do this.
fromrandomimportrandintnumber=randint(0,99)guess=-1whileguess!=number:guess=input("Guess a number: ")ifguess>number:print"Too high"elifguess<number:print"Too low"print"Just right"
We have already seen lists and how they can be used. Now that you have some more background I will go into more detail about lists. First we will look at more ways to get at the elements in a list and then we will talk about copying them.
Here are some examples of using indexing to access a single element of a list:
>>>some_numbers = ['zero', 'one', 'two', 'three', 'four', 'five']>>>some_numbers[0]'zero'>>>some_numbers[4]'four'>>>some_numbers[5]'five'
All those examples should look familiar to you. If you want the first item in the list just look at index 0. The second item is index 1 and so on through the list. However what if you want the last item in the list? One way could be to use thelen() function likesome_numbers[len(some_numbers) - 1]. This way works since thelen() function always returns the last index plus one. The second from the last would then besome_numbers[len(some_numbers) - 2]. There is an easier way to do this. In Python the last item is always index -1. The second to the last is index -2 and so on. Here are some more examples:
>>>some_numbers[len(some_numbers) - 1]'five'>>>some_numbers[len(some_numbers) - 2]'four'>>>some_numbers[-1]'five'>>>some_numbers[-2]'four'>>>some_numbers[-6]'zero'
Thus any item in the list can be indexed in two ways: from the front and from the back.
Another useful way to get into parts of lists is using slicing. Here is another example to give you an idea what they can be used for:
>>>things = [0, 'Fred', 2, 'S.P.A.M.', 'Stocking', 42, "Jack", "Jill"]>>>things[0]0>>>things[7]'Jill'>>>things[0:8][0, 'Fred', 2, 'S.P.A.M.', 'Stocking', 42, 'Jack', 'Jill']>>>things[2:4][2, 'S.P.A.M.']>>>things[4:7]['Stocking', 42, 'Jack']>>>things[1:5]['Fred', 2, 'S.P.A.M.', 'Stocking']
Slicing is used to return part of a list. The slicing operator is in the formthings[first_index:last_index]. Slicing cuts the list before thefirst_index and before thelast_index and returns the parts inbetween. You can use both types of indexing:
>>>things[-4:-2]['Stocking', 42]>>>things[-4]'Stocking'>>>things[-4:6]['Stocking', 42]
Another trick with slicing is the unspecified index. If the first index is not specified the beginning of the list is assumed. If the last index is not specified the whole rest of the list is assumed. Here are some examples:
>>>things[:2][0, 'Fred']>>>things[-2:]['Jack', 'Jill']>>>things[:3][0, 'Fred', 2]>>>things[:-5][0, 'Fred', 2]
Here is a (HTML inspired) program example (copy and paste in the poem definition if you want):
poem=["<B>","Jack","and","Jill","</B>","went","up","the","hill","to","<B>","fetch","a","pail","of","</B>","water.","Jack","fell","<B>","down","and","broke","</B>","his","crown","and","<B>","Jill","came","</B>","tumbling","after"]defget_bolds(text):true=1false=0## is_bold tells whether or not we are currently looking at## a bold section of text.is_bold=false## start_block is the index of the start of either an unbolded## segment of text or a bolded segment.start_block=0forindexinrange(len(text)):## Handle a starting of bold textiftext[index]=="<B>":ifis_bold:print"Error: Extra Bold"## print "Not Bold:", text[start_block:index]is_bold=truestart_block=index+1## Handle end of bold text## Remember that the last number in a slice is the index## after the last index used.iftext[index]=="</B>":ifnotis_bold:print"Error: Extra Close Bold"print"Bold [",start_block,":",index,"]",text[start_block:index]is_bold=falsestart_block=index+1get_bolds(poem)
with the output being:
Bold [ 1 : 4 ] ['Jack', 'and', 'Jill']Bold [ 11 : 15 ] ['fetch', 'a', 'pail', 'of']Bold [ 20 : 23 ] ['down', 'and', 'broke']Bold [ 28 : 30 ] ['Jill', 'came']
Theget_bold() function takes in a list that is broken into wordsand tokens. The tokens that it looks for are<B> which startsthe bold text and</B> which ends bold text. The functionget_bold() goes through and searches for the start and endtokens.
The next feature of lists is copying them. If you try something simple like:
>>>a = [1, 2, 3]>>>b = a>>>print b[1, 2, 3]>>>b[1] = 10>>>print b[1, 10, 3]>>>print a[1, 10, 3]
This probably looks surprising since a modification tobresulted ina being changed as well. What happened is that thestatementb = a makesb areference toa.This means thatb can be thought of as another name fora.Hence any modification tob changesa as well. Howeversome assignments don't create two names for one list:
>>>a = [1, 2, 3]>>>b = a * 2>>>print a[1, 2, 3]>>>print b[1, 2, 3, 1, 2, 3]>>>a[1] = 10>>>print a[1, 10, 3]>>>print b[1, 2, 3, 1, 2, 3]
In this caseb is not a reference toa since theexpressiona * 2 creates a new list. Then the statementb = a * 2 givesb a reference toa * 2 rather than areference toa. All assignment operations create a reference.When you pass a list as an argument to a function you create areference as well. Most of the time you don't have to worry aboutcreating references rather than copies. However when you need to makemodifications to one list without changing another name of the listyou have to make sure that you have actually created a copy.
There are several ways to make a copy of a list. The simplest thatworks most of the time is the slice operator since it always makes anew list even if it is a slice of a whole list:
>>>a = [1, 2, 3]>>>b = a[:]>>>b[1] = 10>>>print a[1, 2, 3]>>>print b[1, 10, 3]
Taking the slice[:] creates a new copy of the list. However itonly copies the outer list. Any sublist inside is still a referencesto the sublist in the original list. Therefore, when the listcontains lists, the inner lists have to be copied as well. You coulddo that manually but Python already contains a module to do it. Youuse thedeepcopy function of thecopy module:
>>>import copy>>>a = [[1, 2, 3], [4, 5, 6]]>>>b = a[:]>>>c = copy.deepcopy(a)>>>b[0][1] = 10>>>c[1][1] = 12>>>print a[[1, 10, 3], [4, 5, 6]]>>>print b[[1, 10, 3], [4, 5, 6]]>>>print c[[1, 2, 3], [4, 12, 6]]
First of all notice thata is a list of lists. Then noticethat whenb[0][1] = 10 is run botha andb arechanged, butc is not. This happens because the inner arraysare still references when the slice operator is used. However withdeepcopyc was fully copied.
So, should I worry about references every time I use a function or=? The good news is that you only have to worry aboutreferences when using dictionaries and lists. Numbers and stringscreate references when assigned but every operation on numbers andstrings that modifies them creates a new copy so you can never modifythem unexpectedly. You do have to think about references when you aremodifying a list or a dictionary.
By now you are probably wondering why are references used at all? Thebasic reason is speed. It is much faster to make a reference to athousand element list than to copy all the elements. The other reasonis that it allows you to have a function to modify the inputted listor dictionary. Just remember about references if you ever have someweird problem with data being changed when it shouldn't be.
And now presenting a cool trick that can be done with strings:
defshout(string):forcharacterinstring:print"Gimme a "+characterprint"'"+character+"'"shout("Lose")defmiddle(string):print"The middle character is:",string[len(string)/2]middle("abcdefg")middle("The Python Programming Language")middle("Atlanta")
And the output is:
Gimme a L'L'Gimme a o'o'Gimme a s's'Gimme a e'e'The middle character is: dThe middle character is: rThe middle character is: a
What these programs demonstrate is that strings are similar to lists in several ways. Theshout() function shows thatfor loops can be used with strings just as they can be used with lists. Themiddle procedure shows that that strings can also use thelen() function and array indexes and slices. Most list features work on strings as well.
The next feature demonstrates some string specific features:
defto_upper(string):## Converts a string to upper caseupper_case=""forcharacterinstring:if'a'<=character<='z':location=ord(character)-ord('a')new_ascii=location+ord('A')character=chr(new_ascii)upper_case=upper_case+characterreturnupper_caseprintto_upper("This is Text")
with the output being:
THIS IS TEXT
This works because the computer represents the characters of a string as numbers from 0 to 255. Python has a function calledord() (short for ordinal) that returns a character as a number. There is also a corresponding function calledchr() that converts a number into a character. With this in mind the program should start to be clear. The first detail is the line:if 'a' <= character <= 'z': which checks to see if a letter is lower case. If it is then the next lines are used. First it is converted into a location so that a = 0, b = 1, c = 2 and so on with the line:location = ord(character) - ord('a'). Next the new value is found withnew_ascii = location + ord('A'). This value is converted back to a character that is now upper case.
Now for some interactive typing exercise:
>>># Integer to String>>>22>>>repr(2)'2'>>>-123-123>>>repr(-123)'-123'>>>`123`'123'>>># String to Integer>>>"23"'23'>>>int("23")23>>>"23" * 2'2323'>>>int("23") * 246>>># Float to String>>>1.231.23>>>repr(1.23)'1.23'>>># Float to Integer>>>1.231.23>>>int(1.23)1>>>int(-1.23)-1>>># String to Float>>>float("1.23")1.23>>>"1.23" '1.23'>>>float("123")123.0>>>`float("1.23")`'1.23'If you haven't guessed already the functionrepr() can convert a integer to a string and the functionint() can convert a string to an integer. The functionfloat() can convert a string to a float. Therepr() function returns a printable representation of something.`...` converts almost everything into a string, too. Here are some examples of this:
>>>repr(1)'1'>>>repr(234.14)'234.14'>>>repr([4, 42, 10])'[4, 42, 10]'>>>`[4, 42, 10]`'[4, 42, 10]'
Theint() function tries to convert a string (or a float) into a integer. There is also a similar function calledfloat() that will convert a integer or a string into a float. Another function that Python has is theeval() function. Theeval() function takes a string and returns data of the type that python thinks it found. For example:
>>>v = eval('123')>>>print v, type(v)123 <type 'int'>>>>v = eval('645.123')>>>print v, type(v)645.123 <type 'float'>>>>v = eval('[1, 2, 3]')>>>print v, type(v)[1, 2, 3] <type 'list'>If you use theeval() function you should check that it returns the type that you expect.
One useful string function is thesplit() method. Here's an example:
>>>"This is a bunch of words".split()['This', 'is', 'a', 'bunch', 'of', 'words']>>>text = "First batch, second batch, third, fourth">>>text.split(",")['First batch', ' second batch', ' third', ' fourth']Notice howsplit() converts a string into a list of strings. The string is split by whitespace by default or by the optional argument (in this case a comma).You can also add another argument that tellssplit() how many times the separator will be used to split the text. For example:
>>>list = text.split(",")>>>len(list)4>>>list[-1]' fourth'>>>list = text.split(",", 2)>>>len(list)3>>>list[-1]' third, fourth'Strings can be cut into pieces — in the same way as it was shown for lists in the previous chapter — by using theslicing "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 argument, as in the example shown below).
In order not to get confused by the index numbers, it is easiest to see them asclipping places, possibilities to cut a string into parts. Here is an example, which shows the clipping places (in yellow) and their index numbers (red and blue) for a simple text string:
| 0 | 1 | 2 | ... | -2 | -1 | ||||||||||
| ↓ | ↓ | ↓ | ↓ | ↓ | ↓ | ↓ | |||||||||
| text = | " | S | T | R | I | N | G | " | |||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| ↑ | ↑ | ||||||||||||||
| [: | :] |
Note that the red indexes are counted from the beginning of the string and the blue ones from the end of the string backwards. (Note that there is no blue -0, which could 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:
| text[1:4] | → | "TRI" |
| text[:5] | → | "STRIN" |
| text[:-1] | → | "STRIN" |
| text[-4:] | → | "RING" |
| text[2] | → | "R" |
| text[:] | → | "STRING" |
| text[::-1] | → | "GNIRTS" |
text[1:4] gives us all of thetext string between clipping places 1 and 4, "TRI". If you omit one of the [first_index:last_index] arguments, you get the beginning or end of the string as default:text[:5] gives "STRIN". For bothfirst_index andlast_index we can use both the red and the blue numbering schema:text[:-1] gives the same astext[:5], because the index -1 is at the same place as 5 in this case. If we do not use an argument containing a colon, the number is treated in a different way:text[2] gives us one character following the second clipping point, "R". The special slicing operationtext[:] means "from the beginning to the end" and produces a copy of the entire string (or list, as shown in the previous chapter).
Last but not least, the slicing operation can have a second colon and a third argument, which is interpreted as the "step size":text[::-1] istext from beginning to the end, with a step size of -1. -1 means "every character, but in the other direction". "STRING" backwards is "GNIRTS" (test a step length of 2, if you have not got the point here).
All these slicing operations work with lists as well. In that sense strings are just a special case of lists, where the list elements are single characters. Just remember the concept ofclipping places, and the indexes for slicing things will get a lot less confusing.
# This program requires an excellent understanding of decimal numbersdefto_string(in_int):"""Converts an integer to a string"""out_str=""prefix=""ifin_int<0:prefix="-"in_int=-in_intwhilein_int/10!=0:out_str=chr(ord('0')+in_int%10)+out_strin_int=in_int/10out_str=chr(ord('0')+in_int%10)+out_strreturnprefix+out_strdefto_int(in_str):"""Converts a string to an integer"""out_num=0ifin_str[0]=="-":multiplier=-1in_str=in_str[1:]else:multiplier=1forxinrange(0,len(in_str)):out_num=out_num*10+ord(in_str[x])-ord('0')returnout_num*multiplierprintto_string(2)printto_string(23445)printto_string(-23445)printto_int("14234")printto_int("12345")printto_int("-3512")
The output is:
223445-234451423412345-3512
Here is a simple example of file I/O (input/output):
# Write a fileout_file=open("test.txt","w")out_file.write("This Text is going to out file\nLook at it and see!")out_file.close()# Read a filein_file=open("test.txt","r")text=in_file.read()in_file.close()printtext
The output and the contents of the filetest.txt are:
This Text is going to out fileLook at it and see!
Notice that it wrote a file calledtest.txt in the directory that you ran the program from. The\n in the string tells Python to put anewline where it is.
A overview of file I/O is:
open function.The first step is to get a file object. The way to do this is to use theopen function. The format isfile_object = open(filename, mode) wherefile_object is the variable to put the file object,filename is a string with the filename, andmode is"r" toread a file or"w" towrite a file (and a few others we will skip here). Next the file objects functions can be called. The two most common functions areread andwrite. Thewrite function adds a string to the end of the file. Theread function reads the next thing in the file and returns it as a string. If no argument is given it will return the whole file (as done in the example).
Now here is a new version of the phone numbers program that we made earlier:
defprint_numbers(numbers):print"Telephone Numbers:"forxinnumbers.keys():print"Name:",x,"\tNumber:",numbers[x]printdefadd_number(numbers,name,number):numbers[name]=numberdeflookup_number(numbers,name):ifnameinnumbers:return"The number is "+numbers[name]else:returnname+" was not found"defremove_number(numbers,name):ifnameinnumbers:delnumbers[name]else:printname," was not found"defload_numbers(numbers,filename):in_file=open(filename,"r")forin_lineinin_file:in_line=in_line.rstrip('\n')#Eliminate end of line or entername,number=in_line.split(",")numbers[name]=numberin_file.close()defsave_numbers(numbers,filename):out_file=open(filename,"w")forxinnumbers.keys():out_file.write(x+","+numbers[x]+"\n")out_file.close()defprint_menu():print'1. Print Phone Numbers'print'2. Add a Phone Number'print'3. Remove a Phone Number'print'4. Lookup a Phone Number'print'5. Load numbers'print'6. Save numbers'print'7. Quit'printphone_list={}menu_choice=0print_menu()whileTrue:menu_choice=input("Type in a number (1-7): ")ifmenu_choice==1:print_numbers(phone_list)elifmenu_choice==2:print"Add Name and Number"name=raw_input("Name: ")phone=raw_input("Number: ")add_number(phone_list,name,phone)elifmenu_choice==3:print"Remove Name and Number"name=raw_input("Name: ")remove_number(phone_list,name)elifmenu_choice==4:print"Lookup Number"name=raw_input("Name: ")printlookup_number(phone_list,name)elifmenu_choice==5:filename=raw_input("Filename to load: ")load_numbers(phone_list,filename)elifmenu_choice==6:filename=raw_input("Filename to save: ")save_numbers(phone_list,filename)elifmenu_choice==7:breakelse:print_menu()print"Goodbye"
Notice that it now includes saving and loading files. Here is some output of my running it twice:
1. Print Phone Numbers2. Add a Phone Number3. Remove a Phone Number4. Lookup a Phone Number5. Load numbers6. Save numbers7. QuitType in a number (1-7):2Add Name and NumberName:JillNumber:1234Type in a number (1-7):2Add Name and NumberName:FredNumber:4321Type in a number (1-7):1Telephone Numbers:Name: Jill Number: 1234Name: Fred Number: 4321Type in a number (1-7):6Filename to save:numbers.txtType in a number (1-7):7Goodbye
1. Print Phone Numbers2. Add a Phone Number3. Remove a Phone Number4. Lookup a Phone Number5. Load numbers6. Save numbers7. QuitType in a number (1-7):5Filename to load:numbers.txtType in a number (1-7):1Telephone Numbers:Name: Jill Number: 1234Name: Fred Number: 4321Type in a number (1-7):7Goodbye
The new portions of this program are:
defload_numbers(numbers,filename):in_file=open(filename,"r")whileTrue:in_line=in_file.readline()ifnotin_line:breakin_line=in_line[:-1]name,number=in_line.split(",")numbers[name]=numberin_file.close()defsave_numbers(numbers,filename):out_file=open(filename,"w")forxinnumbers.keys():out_file.write(x+","+numbers[x]+"\n")out_file.close()
First we will look at the save portion of the program. First it creates a file object with the commandopen(filename, "w"). Next it goes through and creates a line for each of the phone numbers with the commandout_file.write(x + "," + numbers[x] + "\n"). This writes out a line that contains the name, a comma, the number and follows it by a newline.
The loading portion is a little more complicated. It starts by getting a file object. Then it uses awhile True: loop to keep looping until abreak statement is encountered. Next it gets a line with the linein_line = in_file.readline(). Thereadline function will return a empty string when the end of the file is reached. Theif statement checks for this andbreaks out of thewhile loop when that happens. Of course if thereadline function did not return the newline at the end of the line there would be no way to tell if an empty string was an empty line or the end of the file so the newline is left in whatreadline returns. Hence we have to get rid of the newline. The linein_line = in_line[:-1] does this for us by dropping the last character. Next the linename, number = in_line.split(",") splits the line at the comma into a name and a number. This is then added to thenumbers dictionary.
Now modify the grades program from sectionDictionaries so that it uses file I/O to keep a record of the students.
Now modify the grades program from sectionDictionaries so that it uses file I/O to keep a record of the students.
assignments=['hw ch 1','hw ch 2','quiz ','hw ch 3','test']students={}defload_grades(gradesfile):inputfile=open(gradesfile,"r")grades=[]whileTrue:student_and_grade=inputfile.readline()student_and_grade=student_and_grade[:-1]ifnotstudent_and_grade:breakelse:studentname,studentgrades=student_and_grade.split(",")studentgrades=studentgrades.split(" ")students[studentname]=studentgradesinputfile.close()print"Grades loaded."defsave_grades(gradesfile):outputfile=open(gradesfile,"w")foriinstudents.keys():outputfile.write(i+",")forxinstudents[i]:outputfile.write(x+",")#added missing commaoutputfile.write("\n")outputfile.close()print"Grades saved."defprint_menu():print"1. Add student"print"2. Remove student"print"3. Load grades"print"4. Record grade"print"5. Print grades"print"6. Save grades"print"7. Print Menu"print"9. Quit"defprint_all_grades():keys=students.keys()ifkeys:keys.sort()print'\t',foriinrange(len(assignments)):printassignments[i],'\t',printforxinkeys:printx,'\t',grades=students[x]print_grades(grades)else:print"There are no grades to print."defprint_grades(grades):foriinrange(len(grades)):printgrades[i],'\t',printprint_menu()menu_choice=0whilemenu_choice!=9:printmenu_choice=input("Menu Choice: ")ifmenu_choice==1:name=raw_input("Student to add: ")students[name]=[0]*len(assignments)elifmenu_choice==2:name=raw_input("Student to remove: ")ifnameinstudents:delstudents[name]else:print"Student:",name,"not found"elifmenu_choice==3:gradesfile=raw_input("Load grades from which file? ")load_grades(gradesfile)elifmenu_choice==4:print"Record Grade"name=raw_input("Student: ")ifnameinstudents:grades=students[name]print"Type in the number of the grade to record"print"Type a 0 (zero) to exit"foriinrange(len(assignments)):printi+1,assignments[i],'\t',printprint_grades(grades)which=1234whilewhich!=-1:which=input("Change which Grade: ")which=which-1if0<=which<len(grades):grade=raw_input("Grade: ")# Change from input() to raw_input() to avoid an error when savinggrades[which]=gradeelifwhich!=-1:print"Invalid Grade Number"else:print"Student not found"elifmenu_choice==5:print_all_grades()elifmenu_choice==6:gradesfile=raw_input("Save grades to which file? ")save_grades(gradesfile)elifmenu_choice!=9:print_menu()
So you now have the perfect program, it runs flawlessly, except for one detail, it will crash on invalid user input. Have no fear, for Python has a special control structure for you. It's calledtry and it tries to do something. Here is an example of a program with a problem:
print"Type Control C or -1 to exit"number=1whilenumber!=-1:number=int(raw_input("Enter a number: "))print"You entered:",number
Notice how when you enter@#& it outputs something like:
Traceback (innermost last): File "try_less.py", line 4, in ? number = int(raw_input("Enter a number: "))</syntaxhighlight>ValueError: invalid literal for int(): @#&As you can see theint() function is unhappy with the number@#& (as well it should be). The last line shows what the problem is; Python found aValueError. How can our program deal with this? What we do is first: put the place where the errors occurs in atry block, and second: tell Python how we wantValueErrors handled. The following program does this:
print"Type Control C or -1 to exit"number=1whilenumber!=-1:try:number=int(raw_input("Enter a number: "))print"You entered:",numberexceptValueError:print"That was not a number."
Now when we run the new program and give it@#& it tells us "That was not a number." and continues with what it was doing before.
When your program keeps having some error that you know how to handle, put code in atry block, and put the way to handle the error in theexcept block.
Here is a more complex example of Error Handling.
# Program by Mitchell Aikens 2012# No copyright.importmathdefmain():success=0while(success==0):try:epact()success=1exceptValueError:print"Error. Please enter an integer value."year=0exceptNameError:print"Error. Please enter an integer value."year=0exceptSyntaxError:print"Error. Please enter an integer value."year=0finally:print"Program Complete"defepact():year=int(input("What year is it?\n"))C=year/100epactval=(8+(C/4)-C+((8*C+13)/25)+11*(year%19))%30print"The Epact is: ",epactvalmain()
The program above uses concepts from previous lessons as well as the current lesson.Let's look at the above program in sections.
After we define the function called "main", we tell it that we want to "try" function named "epact". It does so "while" there is no "success". The interpreter then goes to the lineyear = int(input("What year is it?\n")).The interpreter takes the value entered by the user and stores it in the variable named "year".
If the value entered is not an integer or a floating point number (which would be converted to an integer by the interpreter), an exception would be raised, and execution of thetry block ends, just beforesuccess is assigned the value 1.
Let's look at some possible exceptions. the program above does not have anexcept clause for every possible exception, as there are numerous types or exceptions.
If the value entered for year is an alphabetical character, aNameError exception is raised. In the program above, this is caught by theexcept NameError: line, and the interpreter executes the print statement below theexcept NameError:, then it sets the value of "year" to 0 as a precaution, clearing it of any non-numeric number. The interpreter then jumps back to the first line of thewhile loop, and the process restarts.
The process above would be the same for the other exceptions we have. If an exception is raised, and there is an except clause for it in our program, the interpreter will jump to the statements under the appropriate except clause, and execute them.
Thefinally statement, is sometimes used in exception handling as well. Think of it as the trump card. Statements underneath thefinally clause will be executed regardless of if we raise and exception or not. Thefinally statement will be executed after anytry orexcept clauses prior to it.
Below is a simpler example where we are not looped, and thefinally clause is executed regardless of exceptions.
#Program By Mitchell Aikens 2012#Not copyright.defmain():try:number=int(input("Please enter a number.\n"))half=number/2print"Half of the number you entered is ",halfexceptNameError:print"Error."exceptValueError:print"Error."exceptSyntaxError:print"Error."finally:print"I am executing the finally clause."main()
If we were to enter an alphabetic value fornumber = int(input("Please enter a number.\n")), the output would be as follows:
Please enter a number.tError.I am executing the finally clause.
Update at least the phone numbers program (in sectionFile IO) so it doesn't crash if a user doesn't enter any data at the menu.
For the moment I recommend looking atThe Python 2 Tutorial byGuido van Rossum for more topics. If you have been following this tutorial, you should be able to understand a fair amount of it. If you want to get deeper into Python,Learn Python the Hard Way is a nice on-line textbook, although targeted at people with a more solid programming background. ThePython Programming wikibook can be worth looking at, too.
This tutorial is very much a work in progress. Thanks to everyone who has sent me emails about it. I enjoyed reading them, even when I have not always been the best replier.
Happy programming, may it change your life and the world.
To do: TODO=['errors','how to make modules','more on loops','more on strings','more on dictionaries','file io','how to use online help','try','pickle','break and continue'] |
easytut.tex file.>>> prompt in front of it.)The Non-Programmer's Tutorial for Python is licensed under the GNU Free Documentation License. All programming examples in the text are granted to the public domain.
As of July 15, 2009 Wikibooks has moved to a dual-licensing system that supersedes the previous GFDL only licensing. In short, this means that text licensed under the GFDL only can no longer be imported to Wikibooks, retroactive to 1 November 2008. Additionally, Wikibooks text might or might not now be exportable under the GFDL depending on whether or not any content was added and not removed since July 15. |
Version 1.3, 3 November 2008Copyright (C) 2000, 2001, 2002, 2007, 2008 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
The purpose of this License is to make a manual, textbook, or other functional and useful document "free" in the sense of freedom: to assure everyone the effective freedom to copy and redistribute it, with or without modifying it, either commercially or noncommercially. Secondarily, this License preserves for the author and publisher a way to get credit for their work, while not being considered responsible for modifications made by others.
This License is a kind of "copyleft", which means that derivative works of the document must themselves be free in the same sense. It complements the GNU General Public License, which is a copyleft license designed for free software.
We have designed this License in order to use it for manuals for free software, because free software needs free documentation: a free program should come with manuals providing the same freedoms that the software does. But this License is not limited to software manuals; it can be used for any textual work, regardless of subject matter or whether it is published as a printed book. We recommend this License principally for works whose purpose is instruction or reference.
This License applies to any manual or other work, in any medium, that contains a notice placed by the copyright holder saying it can be distributed under the terms of this License. Such a notice grants a world-wide, royalty-free license, unlimited in duration, to use that work under the conditions stated herein. The "Document", below, refers to any such manual or work. Any member of the public is a licensee, and is addressed as "you". You accept the license if you copy, modify or distribute the work in a way requiring permission under copyright law.
A "Modified Version" of the Document means any work containing the Document or a portion of it, either copied verbatim, or with modifications and/or translated into another language.
A "Secondary Section" is a named appendix or a front-matter section of the Document that deals exclusively with the relationship of the publishers or authors of the Document to the Document's overall subject (or to related matters) and contains nothing that could fall directly within that overall subject. (Thus, if the Document is in part a textbook of mathematics, a Secondary Section may not explain any mathematics.) The relationship could be a matter of historical connection with the subject or with related matters, or of legal, commercial, philosophical, ethical or political position regarding them.
The "Invariant Sections" are certain Secondary Sections whose titles are designated, as being those of Invariant Sections, in the notice that says that the Document is released under this License. If a section does not fit the above definition of Secondary then it is not allowed to be designated as Invariant. The Document may contain zero Invariant Sections. If the Document does not identify any Invariant Sections then there are none.
The "Cover Texts" are certain short passages of text that are listed, as Front-Cover Texts or Back-Cover Texts, in the notice that says that the Document is released under this License. A Front-Cover Text may be at most 5 words, and a Back-Cover Text may be at most 25 words.
A "Transparent" copy of the Document means a machine-readable copy, represented in a format whose specification is available to the general public, that is suitable for revising the document straightforwardly with generic text editors or (for images composed of pixels) generic paint programs or (for drawings) some widely available drawing editor, and that is suitable for input to text formatters or for automatic translation to a variety of formats suitable for input to text formatters. A copy made in an otherwise Transparent file format whose markup, or absence of markup, has been arranged to thwart or discourage subsequent modification by readers is not Transparent. An image format is not Transparent if used for any substantial amount of text. A copy that is not "Transparent" is called "Opaque".
Examples of suitable formats for Transparent copies include plain ASCII without markup, Texinfo input format, LaTeX input format, SGML or XML using a publicly available DTD, and standard-conforming simple HTML, PostScript or PDF designed for human modification. Examples of transparent image formats include PNG, XCF and JPG. Opaque formats include proprietary formats that can be read and edited only by proprietary word processors, SGML or XML for which the DTD and/or processing tools are not generally available, and the machine-generated HTML, PostScript or PDF produced by some word processors for output purposes only.
The "Title Page" means, for a printed book, the title page itself, plus such following pages as are needed to hold, legibly, the material this License requires to appear in the title page. For works in formats which do not have any title page as such, "Title Page" means the text near the most prominent appearance of the work's title, preceding the beginning of the body of the text.
The "publisher" means any person or entity that distributes copies of the Document to the public.
A section "Entitled XYZ" means a named subunit of the Document whose title either is precisely XYZ or contains XYZ in parentheses following text that translates XYZ in another language. (Here XYZ stands for a specific section name mentioned below, such as "Acknowledgements", "Dedications", "Endorsements", or "History".) To "Preserve the Title" of such a section when you modify the Document means that it remains a section "Entitled XYZ" according to this definition.
The Document may include Warranty Disclaimers next to the notice which states that this License applies to the Document. These Warranty Disclaimers are considered to be included by reference in this License, but only as regards disclaiming warranties: any other implication that these Warranty Disclaimers may have is void and has no effect on the meaning of this License.
You may copy and distribute the Document in any medium, either commercially or noncommercially, provided that this License, the copyright notices, and the license notice saying this License applies to the Document are reproduced in all copies, and that you add no other conditions whatsoever to those of this License. You may not use technical measures to obstruct or control the reading or further copying of the copies you make or distribute. However, you may accept compensation in exchange for copies. If you distribute a large enough number of copies you must also follow the conditions in section 3.
You may also lend copies, under the same conditions stated above, and you may publicly display copies.
If you publish printed copies (or copies in media that commonly have printed covers) of the Document, numbering more than 100, and the Document's license notice requires Cover Texts, you must enclose the copies in covers that carry, clearly and legibly, all these Cover Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on the back cover. Both covers must also clearly and legibly identify you as the publisher of these copies. The front cover must present the full title with all words of the title equally prominent and visible. You may add other material on the covers in addition. Copying with changes limited to the covers, as long as they preserve the title of the Document and satisfy these conditions, can be treated as verbatim copying in other respects.
If the required texts for either cover are too voluminous to fit legibly, you should put the first ones listed (as many as fit reasonably) on the actual cover, and continue the rest onto adjacent pages.
If you publish or distribute Opaque copies of the Document numbering more than 100, you must either include a machine-readable Transparent copy along with each Opaque copy, or state in or with each Opaque copy a computer-network location from which the general network-using public has access to download using public-standard network protocols a complete Transparent copy of the Document, free of added material. If you use the latter option, you must take reasonably prudent steps, when you begin distribution of Opaque copies in quantity, to ensure that this Transparent copy will remain thus accessible at the stated location until at least one year after the last time you distribute an Opaque copy (directly or through your agents or retailers) of that edition to the public.
It is requested, but not required, that you contact the authors of the Document well before redistributing any large number of copies, to give them a chance to provide you with an updated version of the Document.
You may copy and distribute a Modified Version of the Document under the conditions of sections 2 and 3 above, provided that you release the Modified Version under precisely this License, with the Modified Version filling the role of the Document, thus licensing distribution and modification of the Modified Version to whoever possesses a copy of it. In addition, you must do these things in the Modified Version:
If the Modified Version includes new front-matter sections or appendices that qualify as Secondary Sections and contain no material copied from the Document, you may at your option designate some or all of these sections as invariant. To do this, add their titles to the list of Invariant Sections in the Modified Version's license notice. These titles must be distinct from any other section titles.
You may add a section Entitled "Endorsements", provided it contains nothing but endorsements of your Modified Version by various parties—for example, statements of peer review or that the text has been approved by an organization as the authoritative definition of a standard.
You may add a passage of up to five words as a Front-Cover Text, and a passage of up to 25 words as a Back-Cover Text, to the end of the list of Cover Texts in the Modified Version. Only one passage of Front-Cover Text and one of Back-Cover Text may be added by (or through arrangements made by) any one entity. If the Document already includes a cover text for the same cover, previously added by you or by arrangement made by the same entity you are acting on behalf of, you may not add another; but you may replace the old one, on explicit permission from the previous publisher that added the old one.
The author(s) and publisher(s) of the Document do not by this License give permission to use their names for publicity for or to assert or imply endorsement of any Modified Version.
You may combine the Document with other documents released under this License, under the terms defined in section 4 above for modified versions, provided that you include in the combination all of the Invariant Sections of all of the original documents, unmodified, and list them all as Invariant Sections of your combined work in its license notice, and that you preserve all their Warranty Disclaimers.
The combined work need only contain one copy of this License, and multiple identical Invariant Sections may be replaced with a single copy. If there are multiple Invariant Sections with the same name but different contents, make the title of each such section unique by adding at the end of it, in parentheses, the name of the original author or publisher of that section if known, or else a unique number. Make the same adjustment to the section titles in the list of Invariant Sections in the license notice of the combined work.
In the combination, you must combine any sections Entitled "History" in the various original documents, forming one section Entitled "History"; likewise combine any sections Entitled "Acknowledgements", and any sections Entitled "Dedications". You must delete all sections Entitled "Endorsements".
You may make a collection consisting of the Document and other documents released under this License, and replace the individual copies of this License in the various documents with a single copy that is included in the collection, provided that you follow the rules of this License for verbatim copying of each of the documents in all other respects.
You may extract a single document from such a collection, and distribute it individually under this License, provided you insert a copy of this License into the extracted document, and follow this License in all other respects regarding verbatim copying of that document.
A compilation of the Document or its derivatives with other separate and independent documents or works, in or on a volume of a storage or distribution medium, is called an "aggregate" if the copyright resulting from the compilation is not used to limit the legal rights of the compilation's users beyond what the individual works permit. When the Document is included in an aggregate, this License does not apply to the other works in the aggregate which are not themselves derivative works of the Document.
If the Cover Text requirement of section 3 is applicable to these copies of the Document, then if the Document is less than one half of the entire aggregate, the Document's Cover Texts may be placed on covers that bracket the Document within the aggregate, or the electronic equivalent of covers if the Document is in electronic form. Otherwise they must appear on printed covers that bracket the whole aggregate.
Translation is considered a kind of modification, so you may distribute translations of the Document under the terms of section 4. Replacing Invariant Sections with translations requires special permission from their copyright holders, but you may include translations of some or all Invariant Sections in addition to the original versions of these Invariant Sections. You may include a translation of this License, and all the license notices in the Document, and any Warranty Disclaimers, provided that you also include the original English version of this License and the original versions of those notices and disclaimers. In case of a disagreement between the translation and the original version of this License or a notice or disclaimer, the original version will prevail.
If a section in the Document is Entitled "Acknowledgements", "Dedications", or "History", the requirement (section 4) to Preserve its Title (section 1) will typically require changing the actual title.
You may not copy, modify, sublicense, or distribute the Document except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, or distribute it is void, and will automatically terminate your rights under this License.
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, receipt of a copy of some or all of the same material does not give you any rights to use it.
The Free Software Foundation may publish new, revised versions of the GNU Free Documentation License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Seehttp://www.gnu.org/copyleft/.
Each version of the License is given a distinguishing version number. If the Document specifies that a particular numbered version of this License "or any later version" applies to it, you have the option of following the terms and conditions either of that specified version or of any later version that has been published (not as a draft) by the Free Software Foundation. If the Document does not specify a version number of this License, you may choose any version ever published (not as a draft) by the Free Software Foundation. If the Document specifies that a proxy can decide which future versions of this License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Document.
"Massive Multiauthor Collaboration Site" (or "MMC Site") means any World Wide Web server that publishes copyrightable works and also provides prominent facilities for anybody to edit those works. A public wiki that anybody can edit is an example of such a server. A "Massive Multiauthor Collaboration" (or "MMC") contained in the site means any set of copyrightable works thus published on the MMC site.
"CC-BY-SA" means the Creative Commons Attribution-Share Alike 3.0 license published by Creative Commons Corporation, a not-for-profit corporation with a principal place of business in San Francisco, California, as well as future copyleft versions of that license published by that same organization.
"Incorporate" means to publish or republish a Document, in whole or in part, as part of another Document.
An MMC is "eligible for relicensing" if it is licensed under this License, and if all works that were first published under this License somewhere other than this MMC, and subsequently incorporated in whole or in part into the MMC, (1) had no cover texts or invariant sections, and (2) were thus incorporated prior to November 1, 2008.
The operator of an MMC Site may republish an MMC contained in the site under CC-BY-SA on the same site at any time before August 1, 2009, provided the MMC is eligible for relicensing.
To use this License in a document you have written, include a copy of the License in the document and put the following copyright and license notices just after the title page:
If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts, replace the "with...Texts." line with this:
If you have Invariant Sections without Cover Texts, or some other combination of the three, merge those two alternatives to suit the situation.
If your document contains nontrivial examples of program code, we recommend releasing these examples in parallel under your choice of free software license, such as the GNU General Public License, to permit their use in free software.