-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
103 lines (78 loc) · 2.99 KB
/
app.py
File metadata and controls
103 lines (78 loc) · 2.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import requests
import random
import html
import sys
def ask_yes_no(prompt: str) -> bool:
"""Return True if user says yes, False if no. Keeps asking until valid."""
while True:
choice = input(prompt).strip().lower()
if choice in ("y", "yes"):
return True
if choice in ("n", "no"):
return False
print("Please enter Y or N.")
def get_quiz_questions(amount=10):
url = "https://opentdb.com/api.php"
params = {
"amount": amount,
"category": 21, # Sports
"difficulty": "hard",
"type": "multiple"
}
response = requests.get(url, params=params, timeout=15)
response.raise_for_status()
data = response.json()
if data.get("response_code") != 0 or "results" not in data:
raise ValueError("Failed to fetch quiz questions from the API.")
return data["results"]
def run_quiz():
try:
questions = get_quiz_questions(amount=10)
except Exception as e:
print(f"\nCould not load quiz questions. Error: {e}")
print("Please check your internet connection and try again.")
return
score = 0
total = len(questions)
print("\nType 'Q' anytime to quit.\n")
for i, q in enumerate(questions, start=1):
question = html.unescape(q["question"])
correct_answer = html.unescape(q["correct_answer"])
incorrect_answers = [html.unescape(a) for a in q["incorrect_answers"]]
options = incorrect_answers + [correct_answer]
random.shuffle(options)
print(f"Question {i}/{total}: {question}")
for idx, opt in enumerate(options, start=1):
print(f" {idx}. {opt}")
# Read answer with quit support + validation
while True:
user_input = input("Your answer (1-4 or Q to quit): ").strip().lower()
# Feature #2: quit anytime
if user_input in ("q", "quit", "exit"):
print("\nYou ended the game.")
print(f"Your score: {score}/{i-1} (answered {i-1} questions)")
print("Thanks for playing! 👋")
return
if user_input.isdigit():
choice = int(user_input)
if 1 <= choice <= len(options):
selected = options[choice - 1]
if selected == correct_answer:
score += 1
print("✅ Correct!\n")
else:
print(f"❌ Wrong! Correct answer: {correct_answer}\n")
break
print("Invalid input. Enter 1-4, or Q to quit.\n")
print("🎉 Quiz complete!")
print(f"Final score: {score}/{total}")
print("Thanks for playing! 👋")
def main():
print("Welcome to the Quiz App 🎯\n")
# Feature #1: ask before starting
if not ask_yes_no("Do you want to play now? (Y/N): "):
print("\nNo problem — thanks for stopping by! 👋")
sys.exit(0)
run_quiz()
if __name__ == "__main__":
main()