Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-我如何将具有A、B、C、D的问题随机化_Python_Python 3.x_Random - Fatal编程技术网

Python-我如何将具有A、B、C、D的问题随机化

Python-我如何将具有A、B、C、D的问题随机化,python,python-3.x,random,Python,Python 3.x,Random,我的目标是让它可以随机提问 例如,测试开始,第一个问题可能是问题8。问题这个词只是一时的评论 我希望它看起来像这样: What does OSI stand for? A- Open Systematic Information B- Open Systems Interconnect C- Organised Stairway Interweb D- Open Safe Internet 代码如下: #Intro name=input("Hello, what is your name?

我的目标是让它可以随机提问

例如,测试开始,第一个问题可能是问题8。问题这个词只是一时的评论

我希望它看起来像这样:

What does OSI stand for?

A- Open Systematic Information
B- Open Systems Interconnect
C- Organised Stairway Interweb
D- Open Safe Internet
代码如下:

#Intro

name=input("Hello, what is your name? ")
print()
print ("Hello "+ name)
print()

valid = False
while not valid:
    ready=input("Are you ready to begin the test? (Please enter YES/NO)")
    print()

    if ready.lower() =="yes":
        print ("Excellent. Welcome to the Networking Principles test. ")
        valid = True
    elif ready.lower() =="no":
        print ("Okay, tell me when your ready. ")
    else:
        print ("Please asnwer yes or no")

count=0


if ready.lower()=="yes":
    print()
    print("Please answer each answer with A,B,C or D only. The test will now begin..."
    )


#Question 1
    print()
    print('What does OSI stand for?')
    print()
    print("A- Open Systematic Information")
    print("B- Open Systems Interconnect")
    print("C- Organised Stairway Interweb")
    print("D- Open Safe Internet")
    answer = input()

    if answer.lower() =="b":
        print ("Correct, Well Done")
        count = count + 1
    else:
        print ("Wrong Answer. The asnwer was B, OSI stands for Open Systems Interconnect")


#Question 2
    print()
    print("What is the fourth Layer of the OSI Model?")
    print()
    print("A- Transport Layer")
    print("B- Teleport Layer")
    print("C- Telecommunications Layer")
    print("D- Topology Layer")
    answer = input()

    if answer.lower() =="a":
        print ("Correct, Well Done")
        count = count + 1
    else:
        print ("Wrong Answer. Layer 4 is the Transport Layer")

你可以把答案放在一个列表中,然后调用它:

每次运行时,可能会产生不同的输出,例如:

A- Organised Stairway Interweb
B- Open Systematic Information
C- Open Safe Internet
D- Open Systems Interconnect

您可以将所有问题保存在词典列表中:

questions = [{'question': 'What does OSI stand for?',
              'correct': ['Open Systems Interconnect'],
              'incorrect': ['Open Systematic Information', 
                            'Organised Stairway Interweb',
                            'Open Safe Internet']},
             {'question': "What is the fourth Layer of the OSI Model?",
              'correct': ['Transport Layer'],
              'incorrect': ['Teleport Layer', 
                            'Telecommunications Layer', 
                            'Topology Layer']}, 
             ...]
现在,您可以每次为用户随机选择给定数量的问题:

import random
import string

to_answer = random.sample(questions, number_of_questions)
然后问问题:

for q_num, question in enumerate(to_answer, 1):
    print("Question {0}: {1}".format(q_num, question['question']))
并以随机顺序呈现答案,将每个答案存储在
答案
中对应的键(
a
b
c
)中:

    answers = question['incorrect'] + question['correct']
    random.shuffle(answers)
    answer_key = {}
    for answer, key in zip(answers, string.ascii_lowercase):
        print("{0}: {1}".format(key, answer))
        answer_key[key] = answer
接受用户的输入:

    while True:
        user_answer = input().lower()
        if user_answer not in answer_key:
            print("Not a valid answer")
        else:
            break
最后检查它们是否正确并报告:

    correct = question['correct']
    if answer_key[user_answer] in correct:
        print("Correct!")
    else:
        s = "Incorrect; the correct answer{0}:"
        print(s.format(" was" if len(correct) == 1 else "s were"))
        for answer in correct:
            print(answer)
这支持一个问题有多个正确答案的可能性,并尽可能少地使用硬代码,因此整个问题都由
问题
配置。这减少了代码的重复,并使以后更容易发现bug

示例输出(如上图所示,
number\u of_questions=1
questions
):


姓名
问题X
。 然后从这些
QuestionX
中随机选择一个或将其洗牌

例如:

import random
def Question1():
    print('Q1:What does OSI stand for?')
    answer = raw_input()
    print(answer)

def Question2():
    print("Q2:What is the fourth Layer of the OSI Model?")
    answer = raw_input()
    print(answer)

Questions = [Question1, Question2]

#Solution 1
q = random.choice(Questions)
q()

#Solution 2
for q in random.sample(Questions, len(Questions)):
    q()

#Solution 3
random.shuffle(Questions)
for q in Questions:
    q()
如果你想洗牌问题中的选择。 你可以在上面做同样的事情

def Question1():
    print('What does OSI stand for?')
    def A(): print("A- Open Systematic Information")
    def B(): print("B- Open Systems Interconnect")
    def C(): print("C- Organised Stairway Interweb")
    def D(): print("D- Open Safe Internet")
    choices = [A, B, C, D]
    random.shuffle(choices)
    for c in choices:
        c()

Question1()
输出:

What does OSI stand for?
B- Open Systems Interconnect
D- Open Safe Internet
C- Organised Stairway Interweb
A- Open Systematic Information

正如您在输出中看到的,似乎不应该硬编码选项的名称。你应该在洗牌后添加A、B、C、D。

你可以做一个简单的从文件中提取信息的操作,比如

while count < 10:
wordnum = random.randint(0, len(questionsfile)-1)
print 'What is:  ', answersfile[wordnum], ''
options = [random.randint(0, len(F2c)-1),
    random.randint(0, len(answersfile)-1),random.randint(0, len(answersfile)-1)]
options[random.randint(0, 2)] = wordnum
print '1 -', answersfile[options[0]],
print '2 -', answersfile[options[1]],
print '3 -', answersfile[options[2]],
print '4 -', answersfile[options[3]]
answer = input('\nYou  choose number ?: ')
if options[answer-1] == wordnum:
计数<10时:
wordnum=random.randint(0,len(问题文件)-1)
打印“What is:”,应答文件[wordnum],“”
选项=[random.randint(0,len(F2c)-1),
random.randint(0,len(answersfile)-1),random.randint(0,len(answersfile)-1)]
选项[random.randint(0,2)]=wordnum
打印“1-”,应答文件[选项[0]],
打印“2-”,应答文件[选项[1]],
打印“3-”,应答文件[选项[2],
打印“4-”,应答文件[选项[3]]
答案=输入(“\n您选择数字:”)
如果选项[answer-1]==wordnum:

将所有问题推到一个列表中,如果正确选择了,则将其从列表中删除。这意味着对每个
问题
函数重复相同的代码多次,引入大量错误源,使维护更加困难,并且,正如您在回答中指出的,还将重新排列答案字母。好的,喜欢随机洗牌。但是我该如何将问题随机化呢?random.shuffle()将问题随机化。在您的反馈良好的情况下尝试运行itOkay,我将如何添加答案?就像你刚才给出的示例输出的示例输入一样……输入在问题的开头。这是一个字典列表,每个问题一个:
[{'question':questiontext,'correct':correctanswerlist,'correct':incorrectanswerlist},…]
恐怕我不明白。特别是这部分=“不正确”:不正确的答案列表你希望我这样做吗=“不正确”:开放系统互连。不,它应该是一个不正确答案的列表,
不正确:['Open systemic Information',…]
,然后答案在列表中
正确:['Open Systems Interconnect']
。这是我答案的第一部分,请看下面的例子。python中也有这个函数,可以在回答选项中随机回答问题,而不必重复答案,函数是random.samlple。
What does OSI stand for?
B- Open Systems Interconnect
D- Open Safe Internet
C- Organised Stairway Interweb
A- Open Systematic Information
while count < 10:
wordnum = random.randint(0, len(questionsfile)-1)
print 'What is:  ', answersfile[wordnum], ''
options = [random.randint(0, len(F2c)-1),
    random.randint(0, len(answersfile)-1),random.randint(0, len(answersfile)-1)]
options[random.randint(0, 2)] = wordnum
print '1 -', answersfile[options[0]],
print '2 -', answersfile[options[1]],
print '3 -', answersfile[options[2]],
print '4 -', answersfile[options[3]]
answer = input('\nYou  choose number ?: ')
if options[answer-1] == wordnum: