4

我正在创建一个欧盟测验。我已经达到:

import random as r
import timeit as tr

import time as t

print "How many questions would you like?"
q = int(raw_input())

count = 0
while q > count:
        aus_country = r.randrange(1,29)
        from random import choice
        if aus_country == 28:
    country = "Austria"
        country_1 = ['Belgium', 'Bulgaria', 'Croatia', 'Cyprus', 'Czech Republic',           'Denmark', 'Estonia', 'Finland', 'France', 'Germany', 'Greece', 'Hungary', 'Ireland', 'Italy', 'Latvia', 'Lithuania', 'Luxembourg', 'Malta', 'Netherlands', 'Poland', 'Portugal', 'Romania', 'Slovakia', 'Slovenia', 'Spain', 'Sweden', 'United Kingdom']
        country = choice(country_1)
        print "What is the capital of", country
        ans = raw_input()
        """I would not like to have 28 if statements here like:
        count = count + 1

但是,我想知道是否有更好的方法来检查大写字母,然后使用 28 个 if 语句,例如:

if ans == London and country == United_Kindom:
    print "Correct"
if ans == Vienna and country == austria:
    print "Correct
...
else:
    print "Wrong"
4

3 回答 3

5

使用字典来存储 Country->Capital,然后使用它进行查找:

capital = {
    'UK': 'London',
    'Austria': 'Vienna'
}

if ans == capital[country]:
    # it's correct

我还会根据某些东西重新设计它以选择随机数量的国家(没有重复)并将其用作主循环......

import random    

number = int(raw_input())
countries = random.sample(capital, number)
for country in countries:
    guess = raw_input('What is the capital of {}?'.format(country))
    if guess == capital[country]:
        print 'Correct!'
于 2013-07-25T14:14:16.503 回答
0

将国家/地区名称和大写字母存储为键值对的字典,并查看答案值是否与键对匹配 - 如果不是答案错误,则答案是正确的

于 2013-07-25T14:14:52.100 回答
0

我建议使用一个类来处理字典,因为您可能希望随着时间的推移而增长并对数据保持灵活。另一方面,也许你想学习一些 OOP 风格的编码。

import random

class QuizLexicon(object):
    """
    A quiz lexicon with validation and random generator.

    """
    def __init__(self, data):
        self.data = data

    def validate_answer(self, key, answer):
        """Check if the answer matches the data, ignoring case."""
        if self.data[key].lower() == answer.lower():
            return True
        else:
            return False

    def random_choice(self):
        """Return one random key from the dictionary."""
        return random.choice([k for k in self.data])

sample_data = {'Hungary': 'Budapest', 'Germany': 'Berlin'}
quiz_lexicon = QuizLexicon(sample_data)

print "How many questions would you like?"
n_questions = int(raw_input())

for _ in range(n_questions):
    key = quiz_lexicon.random_choice()
    print("What is the capital of %s" % key)
    answer = raw_input()
    if quiz_lexicon.validate_answer(key, answer):
        print("That's right!")
    else:
        print("No, sorry")
于 2013-07-25T14:36:46.730 回答