# 撩课-Python-每天5道面试题-第3天

#### 一. 代码实现: 计算1到100之间, 所有的奇数之和

``````result = 0
for i in range(1, 101):
result += i
print(result)
``````

#### 二. 代码实现: 接收用户输入数字, 求出从0至这个数字的累加和;

``````num_str = input("请输入一个数字(>=1): ")
num = int(num_str) # 可以使用try...except...以及判定语句进行容错处理
result = 0 # 保存最终结果
expression = "0" # 记录表达式
for i in range(1, num + 1):
result += i
expression += " + {}".format(i)
else:
expression += " = {}".format(result)
print(expression)
``````

#### 三. 将以下学生姓名和分数组成的列表, 转换成字典形式

stu_list = [“小王”, 90, “小强”, 60, “小华”, 80]

{‘小王’: 90, ‘小强’: 60, ‘小华’: 80}

``````stu_list = ["小王", 90, "小强", 60, "小华", 80] # 原始数据
stu_dic = {} # 结果字典
# 没隔一个位置, 取两个数据, 组成一个键值对
for idx in range(0, len(stu_list), 2):
name, score = stu_list[idx: idx + 2]
stu_dic[name] = score
print(stu_dic)
``````

#### 四. 代码实现: 将以上的学生分数替换成级别

stu_list = [“小王”, 90, “小强”, 60, “小华”, 80]

• 分数 < 60 为 不及格 D
• 80 > 分数 >= 60 为 及格 C
• 90 > 分数 >= 80 为 良好 B
• 分数 >= 90 为 优秀 A

{‘小王’: ‘A’, ‘小强’: ‘C’, ‘小华’: ‘B’}

``````stu_list = ["小王", 90, "小强", 60, "小华", 80]
stu_dic = {}
stu_list_len = len(stu_list)
for idx in range(0, stu_list_len, 2):
name, score = stu_list[idx: idx + 2]
if score >= 90:
level = "A"
elif score >= 80:
level = "B"
elif score >= 60:
level = "C"
else:
level = "D"
stu_dic[name] = level
print(stu_dic)
``````

#### 五. 代码实现: 完善以上案例, 求出所有学生的总分以及平均分

``````stu_list = ["小王", 90, "小强", 60, "小华", 80]
stu_dic = {}
stu_list_len = len(stu_list)
score_count = 0 # 用来记录分数
score_avg = 0 # 用来记录平均分数
for idx in range(0, stu_list_len, 2):
name, score = stu_list[idx: idx + 2]
score_count += score
if score >= 90:
level = "A"
elif score >= 80:
level = "B"
elif score >= 60:
level = "C"
else:
level = "D"
stu_dic[name] = level
else:
score_avg = score_count / (stu_list_len // 2)
print(stu_dic)
print("总分:{},平均分:{}".format(score_count, score_avg))

``````