列表的百分比计算

时间:2017-11-12 21:29:17

标签: python

我创建了一个测验系统,用于测试用户的两个不同主题。他们可以选择他们想要做的主题以及他们希望完成它的难度。如果问题得到纠正,他们会得到一个点,如果他们不这样做,它会显示正确的答案。

我正在努力根据用户的正确答案计算百分比。例如,我想出了“百分比=得分/ 100 x 100”,这是行不通的。有关从这些清单计算百分比的建议吗?

t = input("Choose 'a' for arithmetics or 'g' for german:")
d = input("Choose 'e' for easy , 'm' for medium , 'h' for hard:")


arithQeasy = [
    ("What is 4 + 4? Choose 1 or 2: 1) 8 2) 7","1"),
    ("What is 16 + 16? Choose 1 or 2: 1) 26 2) 32","2"),
    ]


arithQmedium = [
    ("How many 6's in 36? Choose 1, 2 or 3: 1) 6 2) 12 3) 3","1"),
    ("What is the Square root of 100? Choose 1, 2 or 3: 1) 50 2) 100 3) 10","3"),
    ("What is 0x1000? Choose 1, 2 or 3: 1) 1000 2) 0 3) 100","2"),
    ]

if t == "a" and d == "e":
    questions = arithQeasy

elif t == "a" and d == "m":
    questions = arithQmedium

for question, answer in questions:
    userInput = input(question + '')
    if userInput == answer:
       score +=1
       print ("correct your score is:",score)
    elif:
       print ("Incorrect the anseer is:",answer)

1 个答案:

答案 0 :(得分:0)

以下似乎有效。请注意,您的代码段存在一些问题:

  • elif循环中的for必须是else
  • 在进入score循环之前,您需要将for初始化为零。

我已修复了这些问题并在最后添加了一些代码,说明如何计算正确答案的百分比,如您所知:

...
score = 0
for question, answer in questions:
    userInput = input(question + '')
    if userInput == answer:
       score += 1
       print("correct your score is:", score)
    else:
       print("Incorrect the anseer is:", answer)

percent = round((score / len(questions)) * 100, 2)
print('percent right: {}%'.format(percent))

<强>解释

这是有效的,因为百分比是&#34;数字或比率表示为100&#34; (来自percentage上的维基百科文章),因此表达式计算正确答案score与问题总数len(questions)的比率。然后它将其乘以100,因为百分比总是将该比率表示为100&#34;的分数。

我还添加了对round()的调用 - 这并非严格必要 - 将小数点后的位数限制为2,因此像6.666666666666666%这样的长数字会被转换为6.67%。从技术上讲,这使得计算出的最终值略微不准确,但我怀疑这一点很重要。