需要检查测验中的答案是否正确(Python)

时间:2016-02-17 12:02:58

标签: python dictionary

所以我有一本关于立法者及其所属政党的字典。用随机名称和派对输出五个问题,输入是Y或N.我现在需要弄清楚如何判断它是否真实但是我很难过。 代码:

from random import *

legislators = { "Tsang Yok-sing" : "DAB", "Albert Ho" :
"Democratic", "Lee Cheuk-yan" : "Labour", "James To" :
"Democratic", "Chan Kam-lam" : "DAB", "Lau Wong-fat" :
"Economic Synergy", "Emily Lau" : "Democratic" }

names = list(legislators.keys())
parties = list(legislators.values())

numberCorrect = 0

for i in range(0, 5):
    name = names[randrange(len(names))]
    party = parties[randrange(len(parties))]
    ans = input("Does "+name+" belong to "+party+" (Y/N)?\n")

只需要就从何处开始提出任何建议。非常感谢!

4 个答案:

答案 0 :(得分:2)

UINavigationController

答案 1 :(得分:1)

您的计划还有另一个问题:

挑选一名随机成员和一个随机派对会给出一个34/49或​​大约70%的派对错误的机会,所以总是回答'n'会给出平均得分3.47 / 5正确。

我们可以这样修理:

# 50% chance of using the correct party,
# 50% chance of using any other party
test_party = party if random() < 0.5 else choice(other_parties[party])

我也有:

  • 创建了一个函数get_yn(),它接受​​各种yes和no值,并返回True表示是和False表示否
  • 使用random.choice选择成员,而不是使用random.randrange
  • 编制索引
  • 将每个问题的代码移到do_question()函数中,该函数返回True表示正确答案,False表示错误答案
  • 添加了有关每个问题结果的用户反馈

结果:

from random import choice, random

NUM_QUESTIONS = 5

def get_yn(prompt, error_message=None, yes_values={'', 'y', 'yes'}, no_values={'n', 'no'}):
    """
    Prompt repeatedly for user input until a yes_value or no_value is entered
    """
    while True:
        result = input(prompt).strip().lower()
        if result in yes_values:
            return True
        elif result in no_values:
            return False
        elif error_message is not None:
            print(error_message)

# reference list of legislators            
member_party = {
    "Tsang Yok-sing": "DAB",
    "Albert Ho":      "Democratic",
    "Lee Cheuk-yan":  "Labour",
    "James To":       "Democratic",
    "Chan Kam-lam":   "DAB",
    "Lau Wong-fat":   "Economic Synergy",
    "Emily Lau":      "Democratic"
}

members = list(member_party.keys())
parties = list(member_party.values())
# For each party, we keep a list of all parties except itself
#   (this is used to balance questions so each question
#   has a 50% chance of being correct)
other_parties = {party:[p for p in parties if p != party] for party in parties}

def do_question():
    # pick a member at random
    member = choice(members)
    party = member_party[member]
    test_party = party if random() < 0.5 else choice(other_parties[party])
    # question user
    prompt = "Does {} belong to the {} party? [Y/n] ".format(member, test_party)
    answer = get_yn(prompt)
    # score answer
    if answer:
        if party == test_party:
            print("You are right!")
            return True
        else:
            print("Sorry, {} is from the {} party.".format(member, party))
            return False
    else:
        if party == test_party:
            print("Sorry, {} actually is from the {} party!".format(member, party))
            return False
        else:
            print("You are right! {} is from the {} party.".format(member, party))
            return True

def main():
    print("Welcome to the Whose Party Is This quiz:")
    correct = sum(do_question() for _ in range(NUM_QUESTIONS))
    print("You got {}/5 correct!".format(correct))

if __name__ == "__main__":
    main()

答案 2 :(得分:0)

由于您将原件存储在dict中,因此您只需检查是否legislators[name] == party

答案 3 :(得分:0)

添加代码示例。您的代码硬编码为大写Y / N.

input计算随机组合的有效性之前。

if legislators[name] == party:
    valid = "Y"
else:
    valid = "N"

现在input之后你需要这样做:

if ans==valid:
   if valid == 'N':
      print "Yes, the member does not belong to that party."
   else:
      print "Yes, the member belongs to that party."
else:
    print "Sorry, your answer is wrong."