This is about a quiz application

import openai
import random

Set your OpenAI API key

openai.api_key = “your-openai-api-key”

Function to generate a question

def generate_question(topic):
messages = [
{“role”: “system”, “content”: “You are a quiz master who generates multiple-choice questions.”},
{“role”: “user”, “content”: f"Generate a multiple-choice question on the topic ‘{topic}’. Include 4 options. "
f"Mark the correct option clearly by prefixing it with ‘(Correct)’. Example:\n"
f"Question: What is the capital of France?\n"
f"A) Berlin\n"
f"(Correct) B) Paris\n"
f"C) Madrid\n"
f"D) Rome"}
]
try:
response = openai.ChatCompletion.create(
model=“gpt-3.5-turbo”, # Use “gpt-4” if you have access for better performance
messages=messages,
max_tokens=150,
temperature=0.7
)
return response[‘choices’][0][‘message’][‘content’].strip()
except Exception as e:
print(f"Error generating question: {e}")
return None

Function to parse the question

def parse_question(question_text):
try:
lines = question_text.split(“\n”)
question = lines[0]
options = lines[1:]
correct_option = None

    for i, option in enumerate(options):
        if "(Correct)" in option:
            correct_option = i
            options[i] = option.replace("(Correct)", "").strip()

    if correct_option is None:
        raise ValueError("No correct option found in the generated question.")

    return question, options, correct_option
except Exception as e:
    print(f"Error parsing question: {e}")
    return None, None, None

Quiz game logic

def play_quiz(topic, num_questions=5):
score = 0
print(f"Welcome to the AI Quiz Game! Topic: {topic}\n")

for i in range(num_questions):
    print(f"Question {i + 1}:")
    question_text = generate_question(topic)
    if not question_text:
        print("Skipping this question due to an error.\n")
        continue

    question, options, correct_option = parse_question(question_text)
    if not question or not options or correct_option is None:
        print("Skipping this question due to an error.\n")
        continue

    print(question)
    for j, option in enumerate(options):
        print(f"{chr(65 + j)}) {option}")

    answer = input("Your answer (A/B/C/D): ").upper()
    if len(answer) == 1 and answer in "ABCD":
        selected_option = ord(answer) - 65
        if selected_option == correct_option:
            print("Correct!\n")
            score += 1
        else:
            print(f"Wrong! The correct answer was {chr(65 + correct_option)}) {options[correct_option]}.\n")
    else:
        print("Invalid input. Please answer with A, B, C, or D.\n")

print(f"Your final score: {score}/{num_questions}")
if score == num_questions:
    print("Excellent work!")
elif score > num_questions / 2:
    print("Good job!")
else:
    print("Better luck next time!")

Main execution

if name == “main”:
topic = input("Enter a topic for the quiz: ").strip()
if topic:
play_quiz(topic)
else:
print(“Please enter a valid topic to start the quiz.”)

Welcome to the community!

What exactly is your issue?

Also, you can use Preformatted Text (CTRL + E) while typing a message on this forum to paste code and make it easier on the eyes for anyone trying to help. :hugs:

@gunav1906

Welcome to the forum!

I think you want https://chatgpt.com/


@j.wischnat

This looks like a case where the user believes this forum is ChatGPT. There is a triage bot that is suppose to check these post and respond with a message directing the user to https://chatgpt.com/

1 Like