如何从代码中随机选择一行而不重复

时间:2014-03-28 01:04:55

标签: python python-2.6

我对python非常陌生,我需要做到这一点,所以我的程序从琐事游戏中随机选择一个问题,但之后不再重复。 游戏的基础是我收到的一本关于python的书的问题。

print "trivia game"
begin = raw_input("Would you like to begin?: ")
if begin == "Yes":
    print "A) Getting your computer to do stuff"
    print "B) A form of watching television"
    print "C) Building a computer"
    print "D) Assembling a computer with your bare hands"
    q1 = raw_input("What is programming?: ")
    if q1 == "A" or q1 == "a":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) African Standard Code For Information Interchange"
    print "B) American Standard Code For Information Interchange"
    print "C) American Subtle Codes For Information Interchange"
    print "D) African Subtle Codes For Inside Interchange"
    print " "
    q2 = raw_input("What does ASCII stand for?: ")
    if q2 == "b" or q2 == "B":
        print "Well done! You got it right! "
        print " "
    else:
        print "no, you're wrong! +0"
    print "A) A hidden group of words"
    print "B) A group of random letters"
    print "C) The generation of random numbers by a definite computational process. "
    print "D) The way to write code"
    q3 = raw_input("What is pseudorandom?: ")
    if q3 == "C" or q3 == "c":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) Only strings and loops"
    print "B) Only loops"
    print "C) Only strings"
    print "D) Any type"
    q4 = raw_input("What kinds of elements can you store with a tuple?: ")
    if q4 == "D" or q4 == "d":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) Yes"
    print "B) No"
    print "C) Only if they are loops"
    print "D) Only if they are strings"
    q5 = raw_input("Do variables store the values you assign to them?: ")
    if q5 == "A" or q5 == "a":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) One"
    print "B) There is no limit"
    print "C) 158,240"
    print "D) 1000"
    q6 = raw_input("How many paramters can a function have?: ")
    if q6 == "B" or q6 == "b":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) Lists of numbers"
    print "B) Complex information"
    print "C) Simple information"
    print "D) Loops"
    q7 = raw_input("What type of information wold be best stored in a text file?: ")
    if q7 == "C" or q7 == "c":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) To write a program with over 1000 lines of code"
    print "B) To create a program that write programs"
    print "C) To create program after program"
    print "D) To create an instance of an object in an object-oriented programming (OOP) language."
    q8 = raw_input("What does instantiate mean?: ")
    if q8 == "D" or q8 == "d":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) It allows you to send the same message to objects of different classes related by inheritance and achieve different and appropriate results"
    print "B) It lets you combine two programs"
    print "C) It creates polygons"
    print "D) It allows you to repeat a loop an infinite amount of times"
    q9 = raw_input("How can polymorphism help a programmer?: ")
    if q9 == "A" or q9 == "a":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) grid()"
    print "B) create_widgets()"
    print "C) root.title"
    print "D) root.mainloop()"
    q10 = raw_input("What widget method sets a widget's options?: ")
    if q10 == "B" or q10 == "b":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) A compass"
    print "B) A graph"
    print "C) A grid"
    print "D) A virtual loop system"
    q11 = raw_input("What is a graphics coordinate system?: ")
    if q11 == "C" or q11 == "c":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) A file with text about sound"
    print "B) A looping sound"
    print "C) A radio channel"
    print "D) Where a sound is stored"
    q12 = raw_input("What's a sound channel?: ")
    if q12 == "D" or q12 == "d":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) True"
    print "B) False"
    q13 = raw_input("Can Python increase programmer productivity?: ")
    if q13 == "a" or q13 == "A":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) True"
    print "B) False"
    q14 = raw_input("It's not important to use the right types in your programs.: ")
    if q14 == "b" or q14 == "B":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) True"
    print "B) False"
    q15 = raw_input("You should plan your programs.: ")
    if q15 == "A" or q15 == "a":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) True"
    print "B) False"
    q16 = raw_input("Constants aren't helpful.: ")
    if q16 == "b" or q16 == "B":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) True"
    print "B) False"
    q17 = raw_input("Dictionary keys must be unique.: ")
    if q17 == "a" or q17 == "A":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) True"
    print "B) False"
    q18 = raw_input("You should never use docstrings.: ")
    if q18 == "b" or q18 == "B":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) True"
    print "B) False"
    q19 = raw_input("You should avoid a catch-all exception handling.: ")
    if q19 == "a" or q19 == "A":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) True"
    print "B) False"
    q20 = raw_input("An object should never update its private attributes.: ")
    if q20 == "b" or q20 == "B":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) True"
    print "B) False"
    q21 = raw_input("You should include only related programming elements in a single module.: ")
    if q21 == "a" or q21 == "A":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) True"
    print "B) False"
    q22 = raw_input("You can't test which radio button in a group is selected.: ")
    if q22 == "b" or q22 == "B":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) True"
    print "B) False"
    q23 = raw_input("You should create a batch file to run your graphics programs.: ")
    if q23 == "a" or q23 == "A":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) True"
    print "B) False"
    q24 = raw_input("There is no such thing as a sound channel.: ")
    if q24 == "b" or q24 == "B":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
else:
    print "Invalid answer."

2 个答案:

答案 0 :(得分:3)

您可以按照以下方式执行此操作:

from random import shuffle
list_of_questions = ['A', 'B', 'C', 'D', 'E', and so on]

shuffle(list_of_questions)

question = list_of_questions.pop()

.pop()方法从列表中删除最后一个问题并将其返回。在这种情况下,它将始终是随机的,因为这是shuffle所做的,因此它始终是最后一个并不重要。

例如:

>>> some_list = [1,2,3,4,5]
>>> shuffle(some_list)
>>> some_list
[4,2,5,1,3]
>>> some_list.pop()
3
>>> some_list
[4,2,5,1]

[注]

我还建议您创建一个包含所有问题的单独文本文件(每行1个问题)。使用python,您可以轻松阅读这些问题,在未来的日期,您也可以轻松删除或添加新问题。

示例:

#questions.txt         Remember, your questions file will need to be in the same directory as your python script
What is ..?
Who is ..?
Where is ..?
Why is ...?


#Start of your python code
questions = [line.strip() for line in open('questions.txt'. 'r')]


>>> print questions
['What is ...?', 'Who is ...?', 'Where is ...?', 'Why is ...?']

>>> from random import shuffle
>>> shuffle(questions)
>>> print questions.pop()
Where is ...?
>>> print questions
['What is ...?', 'Who is ...?', 'Why is ...?'] #Note the question that was taken is gone from the list. Thanks to the .pop() method

答案 1 :(得分:0)

尝试使用csv模块和一些自定义语法的组合。

以下是csv文件的示例:

"What is programming?","*Getting your computer to do stuff","A form of watching television","Building a computer","Assembling a computer with your bare hands"
"What does ASCII stand for?","African Standard Code For Information Interchange","*American Standard Code For Information Interchange","American Subtle Codes For Information Interchange","African Subtle Codes For Inside Interchange"
"What is pseudorandom?","A hidden group of words","A group of random letters","*The generation of random numbers by a definite computational process","The way to write code"
"What kinds of elements can you store with a tuple?","Only strings and loops","Only loops","Only strings","*Any type"
...

请注意,每行中的第一项是问题,其余的是答案。 “正确”答案由开头的*表示。该程序将能够轻松地解析此文件,任何人工编辑器都可以轻松地添加或编辑问题。

这是一个将游戏封装在一个函数中的程序,使用csv模块从文件中读取问题和答案,跟踪变量中的得分,并自动解析哪个答案是“正确的”文件中正确答案开头的*

import csv

def play_trivia(questions_path):
    # start the game
    print 'Trivia game:'
    if raw_input("Would you like to begin? (Y/N): ").lower() != 'y':
        print "Goodby."
        return
    print
    score = 0
    # set choice letters (and order)
    letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
    # loop through each row in the file
    for row in csv.reader(open(questions_path, 'r')):
        # print the question
        print row[0]
        correct_choice = 'A' # just in case csv is missing the *
        # loop through answers
        # (Start with element 1, since element 0 was the question.)
        for i, choice in enumerate(row[1:]):
            if choice.startswith("*"):
                correct_choice = letters[i]
                print letters[i] + ") " + choice[1:]
            else:
                print letters[i] + ") " + choice
        # ask for the correct answer
        if raw_input("Enter answer: ").upper() == correct_choice:
            score += 1
            print "Well done you got it right! +1 (Score is now " + str(score) + ")"
        else:
            score -= 1
            print "No, you're wrong! -1 (Score is now " + str(score) + ")"
        # separate questions with a line for readability
        print
    # and now we're done
    print "Final score: " + str(score)

值得注意的是,letters[i]表示i字母的字母。

这在我的python解释器中运行得很好。