我正在创建欧盟测验。我已经做到了:
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"
答案 0 :(得分: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!'
答案 1 :(得分:0)
将国家/地区名称和资本存储为密钥:值对的字典,并查看答案值是否与密钥对匹配 - 如果答案不对,答案是正确的
答案 2 :(得分: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")