lundi 18 novembre 2019

How to Import Random Questions from a .txt file

import random
print('                                                      Welcome to Py Quiz\nRules:\n'
      '1. Each Question Carries 5 points.Totally 10 questions\n'
      '2. Two lifelines are allotted for the entire quiz.Lifelines and be used by entering L or l\n'
      '   a) 50-50 [ Eliminates 2 options ]\n'
      '   b) Multi Choice [ Player will be given a second chance for answering ]\n'
      '3. Incorrect answer in any question will lead to losing the entire game\n'
      '4. Enjoy The Game\n')
name=input("Enter your name\n")
print(f"\n\n{name}\n\n")
d={}
points=0
quiz = [
    {
        "question": "What's 4-2?",
        "options": ["2", "1", "3", "4"],
    },
    {
        "question": "What's 6-3?",
        "options": ["3", "1", "2", "4"],
    }
]
print("Enter 1 to Start the quiz")
start=input()
Wrong=False
while start!='1':
    print(f"Invalid input: {start}")
    print("Enter 1 to Start the quiz")
    start = input()
if start=='1':
    for question_number, d in enumerate(quiz,1):
        question = d["question"]
        options = sorted(d["options"])
        print(f"\n#{question_number}: {question}")
        for option_no, o in enumerate(options,1):
            print(f"{option_no}: {o}")
        while True:
            user_input = input("Enter the option\n> ")
            # Valid input
            if user_input.isdecimal() and int(user_input) in list(range(1, len(options) + 1)):
                # Check answer
                if options[int(user_input) - 1] == d["options"][0]:
                    # Answer is correct
                    points += 5
                    print(f"Correct\nYou have scored: {points} points")
                    break
                else:
                    # Answer is incorrect
                    print(f"Wrong\nYou have scored: {points} points")
                    Wrong=True
                    break
            else:
                print(f"Invalid input: {user_input}\nYou have scored: {points} points")
                Wrong=True
                break
        # Breaking loop if answer is incorrect
        if Wrong:
            break

So this is a program for a quiz for some repeated questions but how can you get random questions from a series of .txt files which contains series of questions with answers Example: What is the capital of Japan? A:Tokyo B:Beijing C:Osaka D:Hong Kong

Answer:A




Aucun commentaire:

Enregistrer un commentaire