1.牛牛的绩点
牛牛在门头沟大学学习,一学年过去了,需要根据他的成绩计算他的平均绩点,假如绩点与等级的对应关系如下表所示。请根据输入的等级和学分数,计算牛牛的均绩(每门课学分乘上单门课绩点,求和后对学分求均值)。
A | 4.0 |
B | 3.0 |
C | 2.0 |
D | 1.0 |
F | 0 |
enter = {"A": 4.0, "B": 3.0, "C": 2.0, "D": 1.0, "F": 0}
x = [] #等级列表
y = [] #学分列表
while True:
a = input() #输入等级
if a == "False":
break
n = int(input()) #输入学分
x.append(a)
y.append(n)
sum = 0
total = 0
for i in range(len(y)):
sum += enter[x[i]] * y[i] #学分*绩点
total += y[i]
print("%.2f" % (sum / total))
2.累加数与平均值
牛牛有一个列表,记录了他和同事们的年龄,你能用for循环遍历链表的每一个元素,将其累加求得他们年龄的总和与平均数吗?
a=input().split()
sum=0
num=0
for i in a:
sum+=int(i)
num+=1
print(sum,"{:.1f}".format(sum/num))
3.修改报名名单
牛牛和牛妹报名了牛客运动会的双人项目,但是由于比赛前一天牛妹身体不适,不能参加第二天的运动,于是想让牛可乐代替自己。
请创建一个依次包含字符串'Niuniu'和'Niumei'的元组entry_form,并直接输出整个元组。
然后尝试使用try- except代码块执行语句:entry-form[1] = 'Niukele',若是引发TypeError错误,请输出'The entry form cannot be modified!'
entry_form=('Niuniu','Niumei')
print(entry_form)
try:
entry_form[1] = 'Niukele'
except TypeError:
print('The entry form cannot be modified!')
try expect 结构
try:
正常情况下执行的代码块
expect 错误类型1:(可选)
错误类型1对应的处理方案
expect 错误类型2:(可选)
错误类型2对应的处理方案
expect:
剩下的错误类型对应的处理方案
else:(可选)
没有发生异常,会执行
finally:(可选)
有没有发生异常都会执行
4.遍历字典
创建一个依次包含键-值对'<': 'less than'和'==': 'equal'的字典operators_dict,
先使用print()语句一行打印字符串'Here is the original dict:',
再使用for循环遍历 已使用sorted()函数按升序进行临时排序的包含字典operators_dict的所有键的列表,使用print()语句一行输出类似字符串'Operator < means less than.'的语句;
对字典operators_dict增加键-值对'>': 'greater than'后,
输出一个换行,再使用print()语句一行打印字符串'The dict was changed to:',
再次使用for循环遍历 已使用sorted()函数按升序进行临时排序的包含字典operators_dict的所有键的列表,使用print()语句一行输出类似字符串'Operator < means less than.'的语句,确认字典operators_dict确实新增了一对键-值对。
operators_dict={"<":"less than","==":"equal"}
print("Here is the original dict:")
for i in sorted(operators_dict):
print("Operator %s means %s." %(i,operators_dict[i]) )
print(' ')
operators_dict.setdefault(">","greater than")
print('The dict was changed to:')
for x in sorted(operators_dict):
print("Operator %s means %s." %(x,operators_dict[x]) )
5.姓名与学号
创建一个依次包含键-值对{'name': 'Niuniu'和'Student ID': 1}的字典my_dict_1,
创建一个依次包含键-值对{'name': 'Niumei'和'Student ID': 2}的字典my_dict_2,
创建一个依次包含键-值对{'name': 'Niu Ke Le'和'Student ID': 3}的字典my_dict_3,
创建一个空列表dict_list,使用append()方法依次将字典my_dict_1、my_dict_2和my_dict_3添加到dict_list里,
使用for循环遍历dict_list,对于遍历到的字典,使用print()语句一行输出类似字符串"Niuniu's student id is 1."的语句以打印对应字典中的内容。
my_dict_1={'name': 'Niuniu','Student ID': 1}
my_dict_2={'name': 'Niumei','Student ID': 2}
my_dict_3={'name': 'Niu Ke Le','Student ID': 3}
dict_list=[]
dict_list.append(my_dict_1)
dict_list.append(my_dict_2)
dict_list.append(my_dict_3)
for i in dict_list:
print(f"{i['name']}'s student id is {i['Student ID']}.")
#注意,字符串中包含单引号,因此外部使用双引号。
#如果字符串中包含单引号和双引号,外部则使用三引号