Ioct.tech



Python Activity 12: List FunctionsLearning ObjectivesStudents will be able to:Content:Explain how the following functions are used with lists: reverse(), sort(), max(), min()Explain how to use lists with filesProcess:Write code that reverses and sorts listsWrite code the finds the largest or smallest element of a listWrite code that reads from a file into a listPrior KnowledgePython concepts from previous Activities Further Reading -122830282130500Model 1: List functionsA method is a function that “belongs to” an object. Some of the methods available with a list object are shown below. Some of the methods have already been used in the previous activity. To use the method, you access them with the name of the list followed by the method and arguments in parenthesis e.g. list.append(“new data”)Some Python List Methodsappend()Add an element to the end of a listinsert()Insert an item at the defined indexremove()Removes an item from the listpop()Removes and returns an element at the given indexclear()Removes all items from the listIndex()Returns the index of the first matched itemCount()Returns the count of number of items passes as an argumentSort()Sort items in a list in ascending orderReverse()Reverse the order of items in the listPython Program 1letters = ['d', 'y', 'n', 'b', 'g', 'l', 'h', 'j', 'r', 'q', 't']print(letters)letters.reverse()print(letters)Critical Thinking Questions: 1.Enter and execute Python Program 1:What does the code print?1.a) What does the reverse() function do? 1.b) Revise the Python Program 1 to use the sort() method on the letters list. Write the revised line of code here:1.c) Do the list methods make a permanent change to the list? (Hint: Use the variables window in Thonny and the Debug current script run option. Step through each line of code.)1.d) What happens if you add the following line of code to the program?print(letters.sort())1.e) 2. The python predefined max() and min() functions can be used on multiple variables or with elements in a list. The ord() function will return the ASCII value for a character.Python Program 2letters = ['d', 'y', 'n', 'b', 'g', 'l', 'h', 'j', 'r', 'q', 't']print(letters)print(max(letters))print(min(letters))a= max(letters)b = min(letters)print(ord(a))print(ord(b))Which values get returned for the max() and min() functions?2.a) How does the ASCII value relate to the values returned in these functions?2.b) How is the syntax of the max() and min() functions different from the list method? Which of these can be arguments in other functions?2.c) 368491448300Information: The member operation determines if a given item is an element of a list. The operation returns True if the item is an element of the list and False otherwise. Syntax: <element> in <list name>.3.The following program demonstrates the member operation for a list. Enter and execute the program:Python Program 3numbers = [23,56,13,78,56,24,89,19,5]guess = int(input("Guess number between 1 and 100: "))print("Here is the list of numbers: ", end= " ")for x in numbers: print(x, end=" ")print()if guess in numbers: print("Good Job! ", guess," is in the list.")else: print("As you can see, ", guess, " is NOT in the list.")Circle the line of code in Python Program 3 that uses the member operation.3.a) Edit the program so that if the number the user entered is not in the list, it is added to the list. Print the list again to be sure the number is added to the list. Here is some sample output:3.b) 4.This exercise will guide you through writing a program that generates 100 numbers between 1 and 500 and puts them in a list. The program prints the numbers, sorts the numbers, reverses the order of the numbers, determines the number of times a given number is in the list and prints the largest and smallest number315925226061Create an empty list to store the numberCreate the code to generate 100 random numbers between 1 and 500 store then in the listCreate the code to print the list without the brackets. Create a separate function for this since you will be printing the list several times. Write the code that sorts and then reverses the numbers. (Does the order of these two lines of code matter?) Print the code after it is sorted and again after the numbers are reversed.Write the code that prompts the user for a number between 1 and 500 and prints how many times that number is in the list. If the number is not in the list print the message: “Sorry, your number is not here!”Print the largest and smallest number.Enter and execute the code from a-f. be sure that it executes properly. Examine the sample output to the right.To make the numbers appear in columns, replace the print statement in the print function with the following line of code: print("%3d" %x, end=" "). What causes the change in output format?b.c.d.h.5.Enter and execute the following code. Python Program 3import randomoutFile = open('numbers.txt','w')for x in range(100): outFile.write(str(random.randint(1,11)) + "\n")outFile.close()print("Done!")What does the program do?5) 6.Add the following code to the program above:21590019685myList = []inFile = open('numbers.txt','r')for y in range(100): myList.append(int(inFile.readline()))inFile.close()0myList = []inFile = open('numbers.txt','r')for y in range(100): myList.append(int(inFile.readline()))inFile.close()a.What does the program do once this code is added? 6.a) b.Explain what the following line of code does: inFile = open('numbers.txt','r')6.b) c.Explain what the following line of code does: myList.append(int(inFile.readline()))6.c) d.Add a final line of code to the program that prints the list.6.d) Individual Homework Activity: Step 1: Getting Data for Your List First, download the movies.txt file from Moodle and read the data for the list in from the file. Print out everything in the list to verify that your program is working. Now add code to add the item Top Gun at the end of the list. Print out the list again to verify that your program is working. Hint: You can count the number of movies in the file, or you can use the following lines of code to count the number of entries in the file:inFile = open('movies.txt','r') #opens the file for younum_lines = sum(1 for line in inFile) #gives the sum of each line in the movies.txt fileStep 2: Printing the Number of Items in a ListNow print the number of items in the list with the special function for doing that. Verify that your program is working. Step 3: Detecting if an Item Is in a ListNow determine if Adventures in Babysitting is in the list the quickest way possible and print YES if it is in the list or NO if it’s not in the list. Step 4: IndexingUse indexing to print the 5th item in the list. Step 5: Reversing a ListWrite code that reverses the list and print the new list out. Step 6: Sorting a ListWrite code to sort the list so the movies are in order alphabetically. Print out the sorted list. Step 7: Inserting ItemsWrite code to insert the movie Spaceballs as the 6th item in the sorted list. Print out the list.Step 8: Removing ItemsRemove Ferris Bueller’s Day Off from the list and print the list. Hint: the apostrophe of the movie name is a special character. Hint but not the answer: Step 9: Deleting ItemsDelete the item at the 5th position in the new list from step8 and print out the list.Step 10: Locating an ItemPrint the position in the list of The Goonies.Submit your python code through Moodle. (10 points) ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download