创建一个多项选择测验python

时间:2018-01-06 21:46:26

标签: python python-3.x

我试图编写一个程序来创建一个文件,该文件将包含一个多项选择测验,供人们打印或随心所欲。我知道如何写文件,但我仍然坚持如何做出问题的选择。这个问题会要求国家的资本,而选择将提供4种可能性,只有一种是正确的。这是代码:

import random

state_capitals = A DICTIONARY of the states and their capitals which I spared you because it was really big :D


file = open(r'''C:\Users\Leo\Desktop\Quiz1CSL.txt''',"w")
#The range(1) is just there as a place holder for later
for x in range(1):

    file.write("Austin's Computer Science State Capitals Quiz\n")

    for x in range(10):
        random_state = random.choice(list(state_capitals.keys()))
        main_typed = "What is the capital of"
        question_mark = "?"
        file.write("\n")
        file.write('{0} {1}{2}\n'.format(main_typed, random_state,question_mark))

file.close()

1 个答案:

答案 0 :(得分:1)

我删除了你的文件编写代码,看看标记的行如何从你的词典中得到3 +一个正确答案的样本:

import random

# testdata "Capitals" as states, "lowercase" as capital ;)
state_capitals = dict([(chr(b).upper(),chr(b)) for b in range(ord("a"),ord("z")+1)])

for x in range(10):
    random_state = random.choice(list(state_capitals.keys()))
    main_typed = "What is the capital of"
    question_mark = "?"

    choices = sorted( random.sample([state_capitals[x] for x in state_capitals if x != random_state],3) + [state_capitals[random_state]])
    # random.samples(list,n) gives you n unique random values from list
    # and I add in the "correct" one, by sorting them you have a uniform
    # a to z order that lets the correct one vanish into the others.

    print('{0} {1}{2}'.format(main_typed, random_state,question_mark))
    print('Choices: ' + ",".join(choices))

Michael Butchers出色的建议归结为:

for x in range(10):
    choices = random.sample(list(state_capitals),4) 
    random_state = random.choice(choices)
    main_typed = "What is the capital of"
    question_mark = "?"

    print('{0} {1}{2}'.format(main_typed, random_state,question_mark))
    print('Choices: ' + ",".join([state_capitals[x] for x in choices]))

输出:

What is the capital of F?
Choices: f,i,p,r
What is the capital of P?
Choices: h,j,p,w
What is the capital of J?
Choices: g,i,j,v
What is the capital of B?
Choices: b,n,s,w
What is the capital of C?
Choices: c,p,s,z
What is the capital of U?
Choices: g,l,u,w
What is the capital of C?
Choices: c,g,h,t
What is the capital of B?
Choices: b,o,y,z
What is the capital of R?
Choices: e,k,r,w
What is the capital of P?
Choices: b,p,x,z