2013-07-25 61 views
4

我正在創建一個歐盟測驗。我已經得到了高達:如何創建不含28個「if」語句的歐盟測驗

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 ans == London and country == United_Kindom: 
    print "Correct" 
if ans == Vienna and country == austria: 
    print "Correct 
... 
else: 
    print "Wrong" 

回答

5

用來存儲國家字典 - >資本,並使用該關注一下吧:

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!' 
0

店國名和首都爲重點的字典:值對,看看答案值密鑰對匹配 - 答案是正確的,如果不是答案是錯的

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")