Я пытаюсь сделать тест с несколькими вариантами ответов, используя Python. Сначала это казалось чем-то простым, но теперь я много чешу в затылке, пытаясь понять, как делать определенные вещи.
Я использую два списка; один для вопросов и один для ответов. Я хотел бы сделать так, чтобы случайный вопрос выбирался из списка вопросов, а также 2 случайных элемента из списка ответов (неправильные ответы) и, наконец, правильный ответ (который имеет тот же индекс, что и случайно выбранный вопрос). Я дошел до выбора случайного вопроса и двух случайных неправильных ответов
- Моя первая проблема - заставить программу отображать правильный ответ.
- Вторая проблема - как проверить, правильно ли вводит пользователь ответ.
Буду признателен за любые отзывы о моем коде. Я новичок в этом, так что расслабьтесь, пожалуйста! Я надеюсь, что мои материалы читабельны (извините, это длинновато)
заранее спасибо
import random
print ("Welcome to your giongo quiz\n")
x=0
while True:
def begin(): # would you like to begin? yes/no... leaves if no
wanna_begin = input("Would you like to begin?: ").lower()
if wanna_begin == ("yes"):
print ("Ok let's go!\n")
get_username()#gets the user name
elif wanna_begin != ("no") and wanna_begin != ("yes"):
print ("I don't understand, please enter yes or no:")
return begin()
elif wanna_begin == ("no"):
print ("Ok seeya!")
break
def get_username(): #get's username, checks whether it's the right length, says hello
username = input("Please choose a username (1-10 caracters):")
if len(username)>10 or len(username)<1:
print("Username too long or too short, try again")
return get_username()
else:
print ("Hello", username, ", let's get started\n\n")
return randomq(questions)
##########
questions = ["waku waku", "goro goro", "kushu", "bukubuku", "wai-wai", "poro", "kipashi", "juru", "pero"]
answers = ["excited", "cat purring", "sneezing", "bubbling", "children playing", "teardrops falling", "crunch", "slurp", "licking"]
score = 0
if len(questions) > 0: #I put this here because if i left it in ONly inside the function, it didnt work...
random_item = random.randint(0, len(questions)-1)
asked_question = questions.pop(random_item)
###########
def randomq(questions):
if len(questions) > 0:
random_item = random.randint(0, len(questions)-1)
asked_question = questions.pop(random_item)
print ("what does this onomatopea correspond to?\n\n%s" % asked_question, ":\n" )
return choices(answers, random_item)
else:
print("You have answered all the questions")
#return final_score
def choices(answers, random_item):
random_item = random.randint(0, len(questions)-1)
a1 = answers.pop(random_item)
a2 = answers.pop(random_item)
possible_ans = [a1, a2, asked_question"""must find way for this to be right answer"""]
random.shuffle(possible_ans)
n = 1
for i in possible_ans:
print (n, "-", i)
n +=1
choice = input("Enter your choice :")
"""return check_answer(asked_question, choice)"""
a = questions.index(asked_question)
b = answers.index(choice)
if a == b:
return True
return False
begin()