目前正在进行真或假测验。有人会善意帮我解决问题吗?因为我无法显示用户想要回答的问题数量。这些问题都排列在一个数组中,但我遇到了麻烦。
例如:
- 有20个问题,测验询问用户他们想要回答多少问题
- 用户输入5个问题
-Quiz在列表中的20个中显示5个随机问题
提前谢谢!
questionlist = [" "]
answerslist=[" "]
score = 0
questions = 0
while True :
questions = int(input("How many questions do you want to answer today? "))
if questions <= len(questionslist) :
break
print("I only have ", len(questions_list), " in my database")
while len(questionslist) > 0 :
I need help after this please
答案 0 :(得分:1)
使用python 2.7:
import random
questions_answers = {"Question1?":"answer1","Question2?":"answer2","Question3?":"answer3","Question4?":"answer4","Question5?":"answer5"}
score = 0
while True :
questions = int(raw_input("How many questions do you want to answer today? "))
if questions == 0:
break
if questions > len(questions_answers) :
print("I only have {} in my database".format(len(questions_answers)))
break
for i in range(1, questions+1):
rand_item = random.choice(questions_answers.keys())
print(rand_item)
answer = raw_input("Enter your answer:")
if answer == questions_answers[rand_item]:
print("Correct")
score+=1
else:
print("Wrong")
print ("Your score is {} out of {}".format(score, questions))
答案 1 :(得分:0)
将此问题分解为多个步骤,然后专注于每个单独部分的代码。
我会检索用户输入他/她想要多少问题并创建一个循环,从该哈希映射中随机检索所请求的问题数量的问题!为了随机检索问题,你应该使用一个随机生成器,它将返回0到1之间的数字。然后你应该将这个数字乘以测验的长度并将这个数字转换成一个整数。这将是您的数组的索引。然后,您必须将问题编号存储在另一个数组中,并检查下次选择随机问题时是否已经询问此问题。
以伪代码形式:
number_of_questions = retrieve_user_input()
questions_asked_thus_far = [] //empty array
question_number = 1
while (question_number<=number_of_questions):
question_number = int(random_number_generator * quiz_array.length)
if question_number is not in questions_asked_thus_ far
questions_asked_thus_far.append(question_number)
question_number ++
print question_number