Вы должны держать вопрос и ответ вместе, а затем вы можете использовать random.shuffle(list)
, чтобы создать список с элементами в случайном порядке. И тогда вы можете использовать обычный for
-l oop, чтобы получить вопрос и ответ - и они будут в случайном порядке и никогда не повторяться.
У вас есть вопрос и ответ вместе, поэтому нет проблем для проверки ввод пользователя с правильным ответом.
import random
data = [
["What star is in the center of the solar system?:", "Sun"],
["What is the 3rd planet of the solar system?:","Earth"],
["What can be broken, but is never held?:", "Promise"],
["What part of the body you use to smell?:", "Nose"],
["How many days in one year?:","365"],
["How many letters in the alphabet?:", "26"],
["Rival of Intel?:", "AMD"],
["No.8 element on periodic element?:", "Oxygen"],
["What is the galaxy that contains our solar system?:","Milky Way"],
["What animal is the king of the jungle?:", "Lion"],
]
random.shuffle(data) # run only once
for item in data:
print('question:', item[0])
print(' answer:', item[1])
print('---')
Кстати: Вы также можете написать l oop также таким образом
for question, answer in data:
print('question:', question)
print(' answer:', answer)
print('---')
РЕДАКТИРОВАТЬ: Рабочий код
import random
data = [
["What star is in the center of the solar system?:", "Sun"],
["What is the 3rd planet of the solar system?:","Earth"],
["What can be broken, but is never held?:", "Promise"],
["What part of the body you use to smell?:", "Nose"],
["How many days in one year?:","365"],
["How many letters in the alphabet?:", "26"],
["Rival of Intel?:", "AMD"],
["No.8 element on periodic element?:", "Oxygen"],
["What is the galaxy that contains our solar system?:","Milky Way"],
["What animal is the king of the jungle?:", "Lion"],
]
# TODO: read data from text file or CSV file
def player(number, data):
score = 0
print("====== Student no.", number, "======")
for question, answer in data:
guess = input(question)
if guess.lower() == answer.lower():
print("Correct!\n")
score += 1
else:
print("Wrong\n")
print("Your score is: ", score, "\n")
return score
# --- main ---
random.shuffle(data) # run only once
score1 = player(1, data)
#score1 = player(1, data[:5])
random.shuffle(data) # next player will have questions in different order
score2 = player(2, data)
#score1 = player(2, data[:5])
#score3 = player(3, data) # you can have more players (but you could use list for scores)
#score4 = player(4, data) # you can have more players (but you could use list for scores)
# best_score, best_player = max([score1, 1], [score2, 2], [score3, 3], [score4, 4])
# results_in_order = sort( [[score1, 1], [score2, 2], [score3, 3], [score4, 4]], reverse=True )
if score1 > score2:
print("Student 1 has the highest score!")
elif score1 < score1:
print("Student 2 has the highest score!")
else:
print("Students are tied!")