Python- How can I randomise questions that have an A,B,C,D

后端 未结 4 605
旧时难觅i
旧时难觅i 2020-12-22 13:40

My aim is to have it so it can randomise questions.

For example, the test starts and the first question could be question 8. The word Question is only

4条回答
  •  青春惊慌失措
    2020-12-22 14:11

    Name QuestionX. Then choose one from or shuffle these QuestionX randomly.

    For example:

    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()
    

    If you want to shuffle choices in the question. You can do same above.

    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()
    

    Output:

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

    As you can see in the output, it seems you shouldn't hard-code the name of choices. You should add A,B,C,D after shuffling.

提交回复
热议问题