Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit a4cf8fb

Browse files
Merge pull request #6 from levoski1/levi
Add Trivia Quiz Functionality with Open Trivia Database API Integration
2 parents 945b6ed + a213269 commit a4cf8fb

File tree

2 files changed

+126
-0
lines changed

2 files changed

+126
-0
lines changed

β€Ž0x25-QuizMaster/README.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# Trivia Quiz Application
2+
3+
This is a Python application that retrieves trivia questions from the Open Trivia Database API and presents them to the user in a quiz format.
4+
5+
## Features
6+
7+
- Fetch trivia questions from the Open Trivia Database API.
8+
- Display questions and multiple-choice answers to the user.
9+
- Allow the user to input their answers and keep track of the score.
10+
11+
## Prerequisites
12+
13+
- Python 3.x installed on your system.
14+
- Install the `requests` library if not already installed:
15+
```bash
16+
pip install requests
17+

β€Ž0x25-QuizMaster/answer_quiz.py

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
import requests
2+
import random
3+
import html
4+
5+
def get_questions(amount: int, category: int) -> dict:
6+
"""
7+
Retrieves trivia questions from the Open Trivia Database API.
8+
9+
Args:
10+
amount (int): Number of questions to retrieve (maximum 50).
11+
category (int): Category ID of the questions.
12+
13+
Returns:
14+
dict: Dictionary containing the retrieved trivia questions.
15+
"""
16+
url = f'https://opentdb.com/api.php?amount={amount}&category={category}'
17+
response = requests.get(url).json()
18+
return response
19+
20+
def shuffle_choices(choices: list) -> list:
21+
"""
22+
Shuffles the order of choices for a trivia question.
23+
24+
Args:
25+
choices (list): List of choices for a trivia question.
26+
27+
Returns:
28+
list: Shuffled list of choices.
29+
"""
30+
random.shuffle(choices)
31+
return choices
32+
33+
def get_user_response(num_choices: int) -> int:
34+
while True:
35+
try:
36+
response = int(input('Enter your answer: '))
37+
if 1 <= response <= num_choices:
38+
return response
39+
else:
40+
print('Invalid input. Please enter a number between 1 and', num_choices)
41+
except ValueError:
42+
print('Invalid input. Please enter a valid integer.')
43+
44+
def display_choices(choices: list) -> None:
45+
"""
46+
Displays the choices for a trivia question with index numbers.
47+
48+
Args:
49+
choices (list): List of choices for a trivia question.
50+
51+
Returns:
52+
int: Index of the user's response.
53+
"""
54+
num_choices = len(choices)
55+
for index, choice in enumerate(choices, start=1):
56+
formatted_choice = f"{index}. {html.unescape(choice)}"
57+
print(formatted_choice)
58+
return get_user_response(num_choices)
59+
60+
def get_user_input() -> int:
61+
"""
62+
Gets the number of questions the user wants to attempt.
63+
64+
Returns:
65+
int: Number of questions chosen by the user.
66+
"""
67+
while True:
68+
try:
69+
user_input = int(input('How many questions would you like to attempt (1-50): '))
70+
if 1 <= user_input <= 50:
71+
return user_input
72+
else:
73+
print('Invalid input. Please enter a number between 1 and 50.')
74+
except ValueError:
75+
print('Invalid input. Please enter a valid integer.')
76+
77+
def main():
78+
"""
79+
Main function to run the trivia quiz application.
80+
"""
81+
score = 0 # Initialize score
82+
try:
83+
num_questions = get_user_input()
84+
trivia_data = get_questions(num_questions, 18) # Category ID 9 corresponds to General Knowledge
85+
questions = trivia_data.get('results')
86+
87+
for question_data in questions:
88+
question = html.unescape(question_data.get('question'))
89+
correct_answer = html.unescape(question_data.get('correct_answer'))
90+
incorrect_answers = [html.unescape(answer) for answer in question_data.get('incorrect_answers')]
91+
incorrect_answers.append(correct_answer)
92+
shuffled_choices = shuffle_choices(incorrect_answers)
93+
94+
print(question)
95+
user_response_index = display_choices(shuffled_choices) - 1 # Adjusting index to start from 0
96+
user_response = shuffled_choices[user_response_index]
97+
if user_response == correct_answer:
98+
score += 1 # Increment score for correct answer
99+
print('Congratulations! Your answer is correct.\n')
100+
else:
101+
print(f'Sorry, the correct answer is: {correct_answer}\n')
102+
103+
except requests.exceptions.RequestException as e:
104+
print(f"Error: {e}. Please check your internet connection.")
105+
finally:
106+
print(f'Your final score is: {score}/{num_questions}') # Display final score
107+
108+
if __name__ == "__main__":
109+
main()

0 commit comments

Comments
(0)

AltStyle γ«γ‚ˆγ£γ¦ε€‰ζ›γ•γ‚ŒγŸγƒšγƒΌγ‚Έ (->γ‚ͺγƒͺγ‚ΈγƒŠγƒ«) /