编写一个计算两个类的百分比的代码
•每个部分有10名学生
O
每个部分让20名学生打分
•有效的输入只有A、B或C
—如果有A、B、C以外的输入,显示“输入错误”
请输入正确答案,然后重复问题
•所有数据输入后
计算A, B, C的学生在每个部分的百分比
在每个部分显示A、B、C的百分比
输入输出格式有要求没有
你题目的解答代码如下:
def func():
section1 = {'A':0,'B':0,'C':0}
section2 = {'A':0,'B':0,'C':0}
for i in range(10):
while True:
g = input(f"第一部分第{i+1}名学生打分:").strip().upper()
if g in section1.keys():
break
print("输入错误,请重新输入")
section1[g] += 1
for i in range(10):
while True:
g = input(f"第二部分第{i+1}名学生打分:").strip().upper()
if g in section2.keys():
break
print("输入错误,请重新输入")
section2[g] += 1
print(f'第一部分有{section1["A"]/10:.2%}的A学生,{section1["B"]/10:.2%}的B学生,{section1["C"]/10:.2%}的C学生')
print(f'第二部分有{section2["A"]/10:.2%}的A学生,{section2["B"]/10:.2%}的B学生,{section2["C"]/10:.2%}的C学生')
if section1["A"]>section2["A"]:
print('第一部分有更多的A')
elif section2["A"]>section1["A"]:
print('第二部分有更多的A')
else:
print('两部分的A一样多')
while True:
func()
if input("你想重复吗?(y/n)").strip().lower()=="n":
break
如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!
翻译得不太准确,这里的class指的是班级,不是类
def fun():
grades={"Section 1":{"A":0,"B":0,"C":0}, "Section 2":{"A":0,"B":0,"C":0}}
for i in range(2):
for j in range(10):
while True:
grade = input(f"Please input grade of student {j+1} for Section {i+1}: ")
if grade not in "ABC" or grade == "":
print("Wrong input please input correct answer")
else:
grades[f"Section {i+1}"][grade] += 1
break
for i in range(2):
print(f'Section{i+1} has {grades[f"Section {i+1}"]["A"]*10}% of A students, {grades[f"Section {i+1}"]["B"]*10}% of B students, {grades[f"Section {i+1}"]["C"]*10}% of C students')
if grades["Section 1"]["A"] != grades["Section 2"]["A"]:
print(f"{max(grades.keys(),key=lambda x:grades[x]['A'])} has more A student")
if __name__ == "__main__":
while True:
fun()
if input("Do you want to repeat? ").upper() != "Y":
break
如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!
def f():
options = ['A', 'B', 'C']
Section1 = {'A':0, 'B':0, 'C':0}
Section2 = {'A':0, 'B':0, 'C':0}
n = 0
while n < 10:
score1 = input(f'第一部分第{n + 1}名学生打分:')
if score1 in options :
Section1[score1] += 1
n += 1
else:
print('输入错误,请输入正确答案:')
key1 = list(Section1.keys())
value1 = [ (i / n) * 100 for i in list(Section1.values())]
Section1 = dict(zip(key1, value1))
m = 0
while m < 10:
score2 = input(f'第二部分第{m + 1}名学生打分:')
if score2 in options:
Section2[score2] += 1
m += 1
else:
print('输入错误,请输入正确答案:')
key2 = list(Section2.keys())
value2 = [(i / n) * 100 for i in list(Section2.values())]
Section2 = dict(zip(key2, value2))
print(f"第一部分有{Section1['A']:0.2f}%的A学生,{Section1['B']:0.2f}%的B学生,{Section1['C']:0.2f}%的C学生")
print(f"第二部分有{Section2['A']:0.2f}%的A学生,{Section2['B']:0.2f}%的B学生,{Section2['C']:0.2f}%的C学生")
if Section1['A'] > Section2['A']:
print('第一部分有更多的A')
elif Section1['A'] < Section2['A']:
print('第二部分有更多A')
else:
print('两部分A一样多')
def fn():
print('你想重复吗?')
result = input('yes或no:')
if result == 'yes':
f()
return fn()
elif result == 'no':
return
else:
print('请正确输入')
return fn()
f()
fn()
如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!