Для цикла в Python при обновлении нескольких индексов списка? - PullRequest
0 голосов
/ 11 февраля 2019

Я немного новичок в Python.Я закончил свою программу, состоящую из 15 вопросов, получаю 5 случайных ответов из 15 и печатаю вопросы один за другим для пользователя.Каждый вопрос имеет 4 возможных ответа.

Программа работает нормально, но вместо того, чтобы писать блок кода для каждого вопроса, я хотел бы пройтись по всем 5 случайным вопросам и сделать так же, как каждый отдельный блок кода для каждого вопроса.Я привык к Java, и похоже, что это не совсем так, поэтому я прокомментировал неудачную попытку цикла for.

Я просто пытаюсь сделать его более эффективным, поэтому полезны любые советы или рекомендации.Я не прошу полного ответа на мою проблему.Спасибо

#Print statement displaying a welcome message
print("***WELCOME TO THE RANDOM QUIZ***\n")

#Importing random library to use the random module
import random

#Creates a list with all 15 questions
questions = ['What is the capital city of Ireland?', 'What is the capital city of France?',
            'What is the capital city of Germany?', 'What is the capital city of Romania?',
            'What is the capital city of Russia?', 'What is the capital city of Belgium?',
            'What is the capital city of Switzerland?','What is the capital city of Egypt?',
            'What is the capital city of Japan?','What is the capital city of China?',
            'What is the capital city of Thailand?','What is the capital city of Brazil?',
            'What is the capital city of Argentina?','What is the capital city of Bolivia?',
            'What is the capital city of Mexico?']

#Creates a list with the answers for each of the 15 individual questions
possible_answers = ['a) Portlaoise | b) Waterford | c) Dublin | d) Galway ', 'a) Paris | b) Lyon | c) Nantes | d) Tolouse ',
                    'a) Frankfurt | b) Munich | c) Berlin | d) Dusseldorf ', 'a) Bucharest | b) Constanta | c) Galati | d) Sibiu ',
                    'a) Moscow | b) St.Petersburg | c) Novosirbirsk | d) Sochi ', 'a) Ghent | b) Bruges | c) Brussels | d) Antwerp ',
                    'a) Zurich | b) Geneva | c) Basel | d) Bern ', 'a) Cairo | b) Alexandria | c) Luxor | d) Giza ',
                    'a) Osaka | b) Yokohama | c) Nagoya | d) Tokyo ', 'a) Beijing | b) Shenzhen | c) Shanghai | d) Fuangzhou ',
                    'a) Bangkok | b) Chiang Mai | c) Pattaya | d) Hat Yai ', 'a) Rio de Janeiro | b) Sao Paolo | c) Salvador | d) Brasilia ',
                    'a) Mendoza | b) Rosario | c) Buenos Aires | d) Cordoba ', 'a) Santa Cruz de la Sierra | b) La Paz | c) El Alto | d) Oruro ',
                    'a) Mexico City | b) Guadalajara | c) Tijuana | d) Merida ']

#Creates a list with the right answers for each of the 15 individual questions
answers = ["Dublin","Paris","Berlin","Bucharest","Moscow","Brussels","Bern","Cairo","Tokyo","Beijing","Bangkok",
            "Brasilia","Buenos Aires","La Paz","Mexico City"]

#Creates variable and assigns the value of 5 which represents the number of random questions we need out of the possible 15
num_of_rand_q = 5

#This variable is created to keep track of the number of right answers by the user
right_q_count = 0

#Assign randomly selected question to a variable
list_of_rand_q = random.sample(questions, num_of_rand_q)


"""
In this operation we match the randomly selected question with the same question in the 'questions' list
to get its original index and assign the index value to a variable. This will help us later on to get the
answer of the exact question by using its original index value as indexes of each question and respective
answer match in both 'questions' and 'answers' lists. We do this for all 5 randomly selected questions.
"""
q_one_index = questions.index(list_of_rand_q[0])
q_two_index = questions.index(list_of_rand_q[1])
q_three_index = questions.index(list_of_rand_q[2])
q_four_index = questions.index(list_of_rand_q[3])
q_five_index = questions.index(list_of_rand_q[4])

"""
#Creating list of indexes so we can loop through them 
q_indexes = [q_one_index, q_two_index, q_three_index, q_four_index, q_five_index]

#Attempted for loop
i = 0
for i in list_of_rand_q[i]:
    print(list_of_rand_q[i])
    print(possible_answers[questions.index(list_of_rand_q[i])], "\n")
    answer_1 = input("Type the city name of which you think it's the capital! \n")

    if answer_1 in answers:
        print('Well done! This is the right answer!')
        right_q_count += 1
    else:
        print('It is the wrong answer...The right answer is actually : ', answers[q_indexes[i]])
"""


#First Question and same as other 4
#Print statement to ask the random question
print(list_of_rand_q[0])
#Print statement to display all 4 possible answers respective to the question
print(possible_answers[questions.index(list_of_rand_q[0])], "\n")
#We ask the user to type the capital city and store the user's input in the answer variable
answer = input("Type the city name of which you think it's the capital! \n")

#If statement checks if user's input matches the value in the answers list
if answer in answers:
    #If statement is true prints a message
    print('Well done! This is the right answer!\n')
    #right_q_count variable stores the number of right answers and we increment it everytime the answer given is right
    right_q_count += 1
#If the if statement is not true and user gets wrong answer then perform 'else'
else:
    #Prints a message and tells the user which is the right answer
    print('It is the wrong answer...The right answer is actually : ', answers[q_one_index], "\n")


#Print statement tells the user how many questions he got right out of the possible 5
print("You got ", right_q_count , "answers right out of 5!" )

Ответы [ 2 ]

0 голосов
/ 11 февраля 2019

Ваш цикл for должен выглядеть примерно так:

for question in list_of_rand_q:
    print(question)

или в другой ситуации:

sum = 0
for number in range(0,n):
    sum = sum + number

В python первая переменная (вопрос или число в приведенных выше случаях)является временным именем объектов, найденных в ходе итерации цикла for через вторую структуру (list_of_rand_q или range).

Другими словами, при выводе на печать нет необходимости указывать индекс вопроса в списке.вопрос, поскольку цикл for уже находится и создал временную ссылку на вопрос.

0 голосов
/ 11 февраля 2019

Вы должны zip три списка вместе, чтобы выполнить их одновременно.Кроме того, вы должны сделать random.sample из сжатых списков, чтобы избежать чрезмерной индексации.Обычно такое количество вызовов .index является запахом кода.

triplets = list(zip(questions, possible_answers, answers)

num_of_rand_q = 5
right_q_count = 0
list_of_rand_q = random.sample(triplets, num_of_rand_q)

for question, choices, answer in list_of_rand_q:
    print(question)
    print(choices, "\n")

    guess = input("Type the city name of which you think it's the capital! \n")

    if guess == answer:
        print('Well done! This is the right answer!\n')
        right_q_count += 1
    else:
        print('It is the wrong answer...The right answer is actually : ', answer, "\n")

print("You got ", right_q_count , "answers right out of 5!" )

Как вы можете видеть, это также немного более интуитивно понятно, так как вам не нужно делать всю эту подписку.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...