Lab Practice for lists, tuples, sets, and dictionaries
1. (Dict)Given a dictionary
grade={“A” : 8, “D” : 3, “B”:15, “F” : 2, “C”: 6}
write python statement(s) to print:
a. All the keys
b. All the values
c. All the key and value pairs
d. All the key and value pairs in key order
e. The average value
2. (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 both
b. 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 three
sets 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 or
divisible 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 and
print the original list and the sum.
5. (dict)Consider the program below. The program determines the admission fee of the ageGroup
that user inputs. You can use the if‐else statements to match the ageGroup and the fee. But you
can also use a dictionary instead of the if‐else to accomplish the same task with only one line of
code.
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
##return8
defdetermineAdmissionFee(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 year
and 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:
Files
Open text files using the open, read/write, close
outfile = open(“test.txt”, “w”)
outfile.write(“Score”)
outfile.close()
Opens a text using the with statement. Using the with statement will automatically closes the file
With open(“test.txt,”w”) as outfile:
outfile.write(“Score”) #need to indent
More List stuff
List 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 errors
Exception
OSError
FileExistsError
FileNotFoundError
ValueError
How 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")
版权所有:编程辅导网 2021 All Rights Reserved 联系方式:QQ:99515681 微信:codinghelp 电子信箱:99515681@qq.com
免责声明:本站部分内容从网络整理而来,只供参考!如有版权问题可联系本站删除。