Josh Cogliati - Non-Programmers Tutorial For Python (779876), страница 7
Текст из файла (страница 7)
For LoopsCHAPTERTENBoolean ExpressionsHere is a little example of boolean expressions (you don’t have to type it in):a = 6b = 7c = 42print 1, a == 6print 2, a == 7print 3,a == 6 and b == 7print 4,a == 7 and b == 7print 5,not a == 7 and b == 7print 6,a == 7 or b == 7print 7,a == 7 or b == 6print 8,not (a == 7 and b == 6)print 9,not a == 7 and b == 6With the output being:123456789101011010What is going on? The program consists of a bunch of funny looking print statements. Each print statementprints a number and a expression. The number is to help keep track of which statement I am dealing with. Notice howeach expression ends up being either 0 or 1. In Python false is written as 0 and true is written as 1. The lines:print 1, a == 6print 2, a == 7print out a 1 and a 0 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 operator and means if both the statement before andthe 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 an and expression is false, the whole thing is false. Thebehavior of and can be summarized as follows:49expressiontrue and truetrue and falsefalse and truefalse and falseresulttruefalsefalsefalseNotice that if the first expression is false Python does not check the second expression since it knows the wholeexpression is false.The next line, print 5,not a == 7 and b == 7, uses the not operator.
not just gives the opposite of theexpression (The expression could be rewritten as print 5,a != 7 and b == 7). Heres the table:expressionnot truenot falseresultfalsetrueThe two following lines, print 6,a == 7 or b == 7 and print 7,a == 7 or b == 6, use the oroperator. The or operator returns true if the first expression is true, or if the second expression is true or both aretrue. If neither are true it returns false. Here’s the table:expressiontrue or truetrue or falsefalse or truefalse or falseresulttruetruetruefalseNotice that if the first expression is true Python doesn’t check the second expression since it knows the whole expression is true.
This works since or is true if at least one half of the expression is true. The first part is true so the secondpart 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) and print 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 theparentheses changed the expression from false to true. This occurred since the parentheses forced the not to apply tothe whole expression instead of just the a == 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.#[:] means.copy = list[:]#sort the copycopy.sort()prev = copy[0]del copy[0]See the More on Lists chapter to explain whatcount = 0#go through the list searching for a matchwhile count < len(copy) and copy[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 foundif count < len(copy):print "First Match: ",prev50Chapter 10.
Boolean ExpressionsAnd here is the output:First Match:JillThis program works by continuing to check for match while count < len(copy and copy[count].When either count is greater than the last index of copy or a match has been found the and is no longer trueso the loop exits. The if simply checks to make sure that the while exited because a match was found.The other ‘trick’ of and is used in this example.
If you look at the table for and notice that the third entry is “falseand won’t check”. If count >= len(copy) (in other words count < len(copy) is false) then copy[count]is never looked at. This is because Python knows that if the first is false then they both can’t be true. This is knownas a short circuit and is useful if the second half of the and will cause an error if something is wrong. I used the firstexpression (count < len(copy)) to check and see if count was a valid index for copy.
(If you don’t believeme remove the matches ‘Jill’ and ‘Life’, check that it still works and then reverse the order of count < len(copy)and copy[count] != prev to copy[count] != prev and count < len(copy).)Boolean expressions can be used when you need to check two or more different things at once.10.1Examplespassword1.py## This programs asks a user for a name and a password.# It then checks them to make sure the the user is allowed in.name = raw_input("What is your name? ")password = raw_input("What is the password? ")if name == "Josh" and password == "Friday":print "Welcome Josh"elif name == "Fred" and password == "Rock":print "Welcome Fred"else:print "I don’t know you."Sample runsWhat is your name? JoshWhat is the password? FridayWelcome JoshWhat is your name? BillWhat is the password? MoneyI don’t know you.10.2ExercisesWrite a program that has a user guess your name, but they only get 3 chances to do so until the program quits.10.1.
Examples5152CHAPTERELEVENDictionariesThis chapter is about dictionaries. Dictionaries have keys and values. The keys are used to find the values. Here is anexample of a dictionary in use:def print_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. Quit’printnumbers = {}menu_choice = 0print_menu()while menu_choice != 5:menu_choice = input("Type in a number (1-5):")if menu_choice == 1:print "Telephone Numbers:"for x in numbers.keys():print "Name: ",x," \tNumber: ",numbers[x]printelif menu_choice == 2:print "Add Name and Number"name = raw_input("Name:")phone = raw_input("Number:")numbers[name] = phoneelif menu_choice == 3:print "Remove Name and Number"name = raw_input("Name:")if numbers.has_key(name):del numbers[name]else:print name," was not found"elif menu_choice == 4:print "Lookup Number"name = raw_input("Name:")if numbers.has_key(name):print "The number is",numbers[name]else:print name," was not found"elif menu_choice != 5:print_menu()And here is my output:531.2.3.4.5.Print Phone NumbersAdd a Phone NumberRemove a Phone NumberLookup a Phone NumberQuitType in a number (1-5):2Add Name and NumberName:JoeNumber:545-4464Type in a number (1-5):2Add Name and NumberName:JillNumber:979-4654Type in a number (1-5):2Add Name and NumberName:FredNumber:132-9874Type in a number (1-5):1Telephone Numbers:Name: JillNumber: 979-4654Name: JoeNumber: 545-4464Name: FredNumber: 132-9874Type in a number (1-5):4Lookup NumberName:JoeThe number is 545-4464Type in a number (1-5):3Remove Name and NumberName:FredType in a number (1-5):1Telephone Numbers:Name: JillNumber: 979-4654Name: JoeNumber: 545-4464Type in a number (1-5):5This program is similar to the name list earlier in the the chapter on lists.
Heres how the program works. First thefunction print_menu is defined. print_menu just prints a menu that is later used twice in the program. Nextcomes the funny looking line numbers = {}. All that line does is tell Python that numbers is a dictionary. Thenext few lines just make the menu work. The lines:for x in numbers.keys():print "Name: ",x," \tNumber: ",numbers[x]go through the dictionary and print all the information. The function numbers.keys() returns a list that is thenused by the for loop. The list returned by keys is not in any particular order so if you want it in alphabetic orderit must be sorted. Similar to lists the statement numbers[x] is used to access a specific member of the dictionary.Of course in this case x is a string. Next the line numbers[name] = phone adds a name and phone number tothe dictionary. If name had already been in the dictionary phone would replace whatever was there before.
Next thelines:54Chapter 11. Dictionariesif numbers.has_key(name):del numbers[name]see if a name is in the dictionary and remove it if it is. The function numbers.has_key(name) returns true ifname is in numbers but other wise returns false. The line del numbers[name] removes the key name and thevalue associated with that key. The lines:if numbers.has_key(name):print "The number is",numbers[name]check to see if the dictionary has a certain key and if it does prints out the number associated with it. Lastly if themenu choice is invalid it reprints the menu for your viewing pleasure.A recap: Dictionaries have keys and values.
Keys can be strings or numbers. Keys point to values. Values can be anytype of variable (including lists or even dictionaries (those dictionaries or lists of course can contain dictionaries orlists 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’,’quizstudents = {’#Max’:max_points}’,’hw ch 3’,’test’]def print_menu():print "1. Add student"print "2. Remove student"print "3. Print grades"print "4. Record grade"print "5.