Josh Cogliati - Non-Programmers Tutorial For Python (779876), страница 6
Текст из файла (страница 6)
Lists-------------------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: 9GoodbyeThat was a long program. Let’s take a look at the source code. The line list = [] makes the variable list a listwith no items (or elements). The next important line is while menu_item != 9:.
This line starts a loop thatallows the menu system for this program. The next few lines display a menu and decide which part of the program torun.The section:current = 0if len(list) > 0:while current < len(list):print current,". ",list[current]current = current + 1else:print "List is empty"goes through the list and prints each name. len(list_name) tell how many items are in a list. If len returns 0then the list is empty.Then a few lines later the statement list.append(name) appears.
It uses the append function to add a item tothe end of the list. Jump down another two lines and notice this section of code:item_number = list.index(del_name)del list[item_number]Here the index function is used to find the index value that will be used later to remove the item.del list[item_number] is used to remove a element of the list.8.2. More features of lists41The next sectionold_name = raw_input("What name would you like to change: ")if old_name in list:item_number = list.index(old_name)new_name = raw_input("What is the new name: ")list[item_number] = new_nameelse:print old_name," was not found"uses index to find the item_number and then puts new_name where the old_name was.Congraduations, with lists under your belt, you now know enough of the language that you could do any computationsthat a computer can do (this is technically known as Turing-Completness).
Of course, there are still many features thatare used to make your life easier.8.3Examplestest.py## This program runs a test of knowledgetrue = 1false = 0# First get the test questions# Later this will be modified to use file io.def get_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 falsedef check_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 answerif answer == given_answer:print "Correct"return trueelse:print "Incorrect, correct was:",answerreturn false42Chapter 8.
Lists# This will run through all the questionsdef run_test(questions):if len(questions) == 0:print "No questions were given."# the return exits the functionreturnindex = 0right = 0while index < len(questions):#Check the questionif check_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)#now lets run the questionsrun_test(get_questions())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 38.4ExercisesExpand the test.py program so it has menu giving the option of taking the test, viewing the list of questions andanswers, and an option to Quit.
Also, add a new question to ask, ”What noise does a truly advanced machine make?”with the answer of ”ping”.8.4. Exercises4344CHAPTERNINEFor LoopsAnd here is the new typing exercise for this chapter:onetoten = range(1,11)for count in onetoten:print countand the ever-present output:12345678910The output looks awfully familiar but the program code looks different. The first line uses the range function.
Therange function uses two arguments like this range(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:for count in range(1,11):print countHere are some examples to show what happens with the range 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(21,5)[]The next line for count in onetoten: uses the for control structure.
A for control structure looks like forvariable 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 into variable. That allows variable to be used in each45successive time the for loop is run through. Here is another example (you don’t have to type this) to demonstrate:demolist = [’life’,42, ’the universe’, 6,’and’,7,’everything’]for item in demolist:print "The Current item is:",print itemThe output is:TheTheTheTheTheTheTheCurrentCurrentCurrentCurrentCurrentCurrentCurrentitemitemitemitemitemitemitemis:is:is:is:is:is:is:life42the universe6and7everythingNotice how the for loop goes through and sets item to each element in the list.
(Notice how if you don’t want printto 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 is for good for? (groan) The first use is to go through all the elements of a list and do something with eachof them. Here a quick way to add up all the elements:list = [2,4,6,8]sum = 0for num in list:sum = sum + numprint "The sum is: ",sumwith the output simply being:The sum is:20Or 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]del list[0]for item in list:if prev == item:print "Duplicate of ",prev," Found"prev = itemand for good measure:Duplicate of7FoundOkay, so how does it work? Here is a special debugging version to help you understand (you don’t need to type thisin):46Chapter 9.
For Loopsl = [4, 5, 7, 8, 9, 1,0,7,10]print "l = [4, 5, 7, 8, 9, 1,0,7,10]","\tl:",ll.sort()print "l.sort()","\tl:",lprev = l[0]print "prev = l[0]","\tprev:",prevdel l[0]print "del l[0]","\tl:",lfor item in l:if prev == item:print "Duplicate of ",prev," Found"print "if prev == item:","\tprev:",prev,"\titem:",itemprev = itemprint "prev = item","\t\tprev:",prev,"\titem:",itemwith 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: 0item: 1prev = itemprev: 1item: 1if prev == item:prev: 1item: 4prev = itemprev: 4item: 4if prev == item:prev: 4item: 5prev = itemprev: 5item: 5if prev == item:prev: 5item: 7prev = itemprev: 7item: 7Duplicate of 7 Foundif prev == item:prev: 7item: 7prev = itemprev: 7item: 7if prev == item:prev: 7item: 8prev = itemprev: 8item: 8if prev == item:prev: 8item: 9prev = itemprev: 9item: 9if prev == item:prev: 9item: 10prev = itemprev: 10item: 10The reason I put so many print statements in the code was so that you can see what is happening in each line.(BTW, if you can’t figure out why a program is not working, try putting in lots of print statements to you can seewhat is happening) First the program starts with a boring old list.
Next the program sorts the list. This is so that anyduplicates get put next to each other. The program then initializes a prev(ious) variable. Next the first element of thelist is deleted so that the first item is not incorrectly thought to be a duplicate. Next a for loop is gone into. Each itemof the list is checked to see if it is the same as the previous.
If it is a duplicate was found. The value of prev is thenchanged so that the next time the for loop is run through prev is the previous item to the current. Sure enough, the 7 isfound to be a duplicate. (Notice how \t is used to print a tab.)The other way to use for loops is to do something a certain number of times. Here is some code to print out the first11 numbers of the Fibonacci series:47a = 1b = 1for c in range(1,10):print a,n = a + ba = bb = nwith the surprising output:1 1 2 3 5 8 13 21 34Everything that can be done with for loops can also be done with while loops but for loops give a easy way to gothrough all the elements in a list or to do something a certain number of times.48Chapter 9.