How can I create an EU quiz without 28 if statements

I am creating a quiz in the EU. I got to:

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 

However, I would like to know if there is a better way to check the capital, then there are 28 such statements as:

 if ans == London and country == United_Kindom: print "Correct" if ans == Vienna and country == austria: print "Correct ... else: print "Wrong" 
+4
source share
3 answers

Use the dictionary to store Country-> Capital and look at it using this:

 capital = { 'UK': 'London', 'Austria': 'Vienna' } if ans == capital[country]: # it correct 

I would also rework it to be based on something, to select a random number of countries (without duplicates) and use this as a main loop ...

 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!' 
+5
source

save the country name and capital as a dictionary of the key: value pair and see if the answer value matches the key pair - the answer is correct, if the answer is incorrect

0
source

I would recommend using the class to handle the dictionary, since you probably want to grow over time and be flexible in data. On the other hand, perhaps you want to learn the OOP coding style.

 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 right!") else: print("No, sorry") 
0
source

Source: https://habr.com/ru/post/1493453/


All Articles