【发布时间】:2017-10-30 23:54:26
【问题描述】:
我正在尝试使用 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()
【问题讨论】:
-
如您所见,您的代码很长。您应该将其减少到 minimal reproducible example。您可能想阅读How to Ask。然后描述您解决具体问题的尝试以及与您的期望有什么不同。
-
感谢您的反馈!下次我会尽量做到最小化
标签: python list loops random multiple-choice