Lab Practice for lists python编程辅导
- 首页 >> Python编程Lab Practice for lists, tuples, sets, and dictionaries1. (Dict)Given a dictionarygrade={“A” : 8, “D” : 3, “B”:15, “F” : 2, “C”: 6}write python statement(s) to print:a. All the keysb. All the valuesc. All the key and value pairsd. All the key and value pairs in key ordere. The average value2. (Sets)Given the sets below, write python statements to:set1 = {1,2,3,4,5}set2 = {2,4,6,8}set3 = {1,5,9,13,17}a. Create a new set of all elements that are in set1 or set2, but not bothb. Create a new set of all elements that are in only one of the three sets set11,set2, and set3.c. Create a new set of all elements that are exactly two of the sets set1, set2, and set3.d. Create a new set of all integer elements in the range 1 through 25 that are not in set1.e. Create a new set of all integer elements in the range 1 to 25 that are not in any of the threesets set1, set2, or set3.f. Create a new set of integer elements in the range 1 to 25 that are not in all three sets set1,set2, and set3.3. (list)write a program that creates a list of numbers from 1‐20 that are either divisible by 2 ordivisible by 4.Output : [2,4,6,8,10,12,14,16,18,20]4. (list)write a program to create a list of squares from 1 to 10. Sum the list of squares in the list.You are to create a function to create the list, a function to sum the list and the main to call andprint the original list and the sum.5. (dict)Consider the program below. The program determines the admission fee of the ageGroupthat user inputs. You can use the if‐else statements to match the ageGroup and the fee. But youcan also use a dictionary instead of the if‐else to accomplish the same task with only one line ofcode.defmain():##Determineanadmissionfeebasedonagegroup.print("Entertheperson'sagegroup",end="")ageGroup=input("(child,minor,adult,orsenior):")print("Theadmissionfeeis",determineAdmissionFee(ageGroup),"dollars.")##defdetermineAdmissionFee(ageGroup):##ifageGroup=="child":#age<6##return0#free##elifageGroup=="minor":#age6to17##return5#$5##elifageGroup=="adult":#age18to64##return10##elifageGroup=="senior":#age>=65##return8defdetermineAdmissionFee(ageGroup):dict={"child":0,"minor":5,"adult":10,"senior":8}returndict[ageGroup]main()a. Rewrite the code using a dict instead of if‐else, write the main to ask user to input what yearand then print the corresponding rank name eg 1 = Freshman.def determineRank(years): if years == 1: return "Freshman" elif years == 2:return "Sophomore" elif years== 3:return "Junior" else: return "Senior" Notes:FilesOpen text files using the open, read/write, closeoutfile = open(“test.txt”, “w”)outfile.write(“Score”)outfile.close()Opens a text using the with statement. Using the with statement will automatically closes the fileWith open(“test.txt,”w”) as outfile:outfile.write(“Score”) #need to indentMore List stuffList Methods for modifying a list append(item) append item to end of list. insert(index, item) insert item into specified index remove(item) removes first item in the list that is equal to the specified item. ValueError raised if not found index(item) returns the index of the first occurrence of specified item. ValueError raised if not found. pop(index) if no index argument is specified, this method gets the last item from the list and removes it. Otherwise, this method gets the item at the specified index and removes it.The pop() method inventory = ["staff", "hat", "robe", "bread"]item = inventory.pop() # item = "bread" since no arguments remove from the end of list# inventory = ["staff", "hat", "robe"]item = inventory.pop(1) # item = "hat" remove at index 1# inventory = ["staff", "robe"]The index() and pop() methods inventory = ["staff", "hat", "robe", "bread"] i = inventory.index("hat") # 1 inventory.pop(i) # ["staff", "robe", "bread"] try and except for trapping errors.The hierarchy for five common errorsException OSError FileExistsError FileNotFoundError ValueErrorHow to handle a ValueError exception try: number = int(input("Enter an integer: ")) print("You entered a valid integer of " + str(number) + ".") except ValueError: print("You entered an invalid integer. Please try again.") print("Thanks!")output with error:Enter an integer: five You entered an invalid integer. Please try again. Thanks!Code that handles multiple exceptions (example used with files)filename = input("Enter filename: ") movies = [] try: with open(filename) as file: for line in file: line = line.replace("\n", "") movies.append(line) except FileNotFoundError: print("Could not find the file named " + filename) except OSError: print("File found ‐ error reading file") except Exception: print("An unexpected error occurred")