-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
274 lines (232 loc) · 8.42 KB
/
Copy pathmain.py
File metadata and controls
274 lines (232 loc) · 8.42 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
"""
General Knowledge Quiz - Python CLI Application
DecodeLabs Python Programming Internship - Project 4
A menu-driven console quiz game built using Core Python only.
No external libraries, GUI frameworks, databases, or classes are used.
"""
import random
# ---------------------------------------------------------------------------
# Question Bank
# ---------------------------------------------------------------------------
# Each question is a dictionary with a category, the question text, and the
# correct answer. At least 10 questions are provided, covering Geography,
# Science, Technology, History, and General Awareness. Five questions are
# randomly selected from this pool for every quiz session.
QUESTIONS = [
{
"category": "Geography",
"question": "Which is the largest continent by land area?",
"answer": "Asia",
},
{
"category": "Geography",
"question": "Which river is known as the longest river in the world?",
"answer": "Nile",
},
{
"category": "Geography",
"question": "What is the capital city of Australia?",
"answer": "Canberra",
},
{
"category": "Science",
"question": "What is the chemical symbol for water?",
"answer": "H2O",
},
{
"category": "Science",
"question": "Which planet is known as the Red Planet?",
"answer": "Mars",
},
{
"category": "Science",
"question": (
"What gas do plants absorb from the atmosphere for "
"photosynthesis?"
),
"answer": "Carbon Dioxide",
},
{
"category": "Technology",
"question": "What does 'CPU' stand for?",
"answer": "Central Processing Unit",
},
{
"category": "Technology",
"question": "Which programming language is named after a snake?",
"answer": "Python",
},
{
"category": "Technology",
"question": "What does 'HTML' stand for?",
"answer": "Hypertext Markup Language",
},
{
"category": "History",
"question": "In which year did India gain independence?",
"answer": "1947",
},
{
"category": "History",
"question": "Who was the first President of the United States?",
"answer": "George Washington",
},
{
"category": "History",
"question": "Which ancient civilization built the pyramids of Giza?",
"answer": "Egyptians",
},
{
"category": "General Awareness",
"question": "How many continents are there on Earth?",
"answer": "7",
},
{
"category": "General Awareness",
"question": "What is the national sport of Japan?",
"answer": "Sumo Wrestling",
},
{
"category": "General Awareness",
"question": (
"Which organization is the world's largest international "
"body for peace and security?"
),
"answer": "United Nations",
},
]
QUESTIONS_PER_QUIZ = 5
MENU_CHOICES = ("1", "2", "3", "4", "5")
# ---------------------------------------------------------------------------
# Display Functions
# ---------------------------------------------------------------------------
def display_menu():
"""Display the main menu options to the user."""
print("\n" + "=" * 45)
print(" PYTHON GENERAL KNOWLEDGE QUIZ")
print("=" * 45)
print("1. Start Quiz")
print("2. View Quiz Rules")
print("3. View Score Summary")
print("4. Play Again")
print("5. Exit")
print("=" * 45)
def display_rules():
"""Display the rules of the quiz."""
print("\n--- QUIZ RULES ---")
print("1. Each quiz session contains 5 randomly selected questions.")
print("2. Questions cover Geography, Science, Technology, History,")
print(" and General Awareness.")
print("3. Answers are not case-sensitive (e.g. 'mars' = 'Mars').")
print("4. Extra spaces before or after your answer are ignored.")
print("5. Empty answers are not accepted; you will be asked again.")
print("6. Your score is displayed after each question and at the end.")
print("-------------------")
def display_score_summary(history):
"""Display a summary of all quiz sessions played so far.
Args:
history: A list of (score, total) tuples, one for each completed
quiz session.
"""
print("\n--- SCORE SUMMARY ---")
if not history:
print("No quiz has been played yet. Choose 'Start Quiz' first.")
print("---------------------")
return
total_score = 0
total_questions = 0
for session_number, (score, total) in enumerate(history, start=1):
percentage = (score / total) * 100 if total else 0
print(f"Session {session_number}: {score}/{total} "
f"({percentage:.1f}%)")
total_score += score
total_questions += total
overall_percentage = (
(total_score / total_questions) * 100 if total_questions else 0
)
print("-" * 21)
print(f"Sessions Played : {len(history)}")
print(f"Overall Score : {total_score}/{total_questions} "
f"({overall_percentage:.1f}%)")
print("---------------------")
# ---------------------------------------------------------------------------
# Core Quiz Logic
# ---------------------------------------------------------------------------
def get_user_answer():
"""Prompt the user for an answer, rejecting empty input.
Returns:
The user's answer, stripped of surrounding whitespace and
lower-cased for comparison.
"""
while True:
raw_answer = input("Your answer: ").strip()
if raw_answer == "":
print("Answer cannot be empty. Please enter your answer.")
continue
return raw_answer.lower()
def ask_question(question_data, question_number, total_questions):
"""Ask a single question and check whether the user's answer is correct.
Args:
question_data: Dictionary containing 'category', 'question',
and 'answer'.
question_number: The current question index (1-based).
total_questions: Total number of questions in this quiz session.
Returns:
True if the user answered correctly, False otherwise.
"""
print(f"\nQuestion {question_number} of {total_questions} "
f"[{question_data['category']}]")
print(question_data["question"])
user_answer = get_user_answer()
correct_answer = question_data["answer"].strip().lower()
if user_answer == correct_answer:
print("Correct!")
return True
print(f"Incorrect. The correct answer is: {question_data['answer']}")
return False
def start_quiz(question_pool):
"""Run a full quiz session of randomly selected questions.
Args:
question_pool: The full list of available questions.
Returns:
A (score, total) tuple summarizing the session.
"""
sample_size = min(QUESTIONS_PER_QUIZ, len(question_pool))
selected_questions = random.sample(question_pool, sample_size)
print("\nStarting a new quiz. Good luck!")
score = 0
total = len(selected_questions)
for index, question_data in enumerate(selected_questions, start=1):
if ask_question(question_data, index, total):
score += 1
print(f"\nQuiz complete! Your final score: {score}/{total}")
return score, total
# ---------------------------------------------------------------------------
# Main Program Loop
# ---------------------------------------------------------------------------
def main():
"""Run the main menu loop until the user exits the program."""
history = []
while True:
try:
display_menu()
choice = input("Enter your choice (1-5): ").strip()
if choice not in MENU_CHOICES:
print("Invalid choice. Please enter a number between 1 "
"and 5.")
continue
if choice in ("1", "4"):
score, total = start_quiz(QUESTIONS)
history.append((score, total))
elif choice == "2":
display_rules()
elif choice == "3":
display_score_summary(history)
elif choice == "5":
print("Thank you for playing. Goodbye!")
break
except (KeyboardInterrupt, EOFError):
print("\n\nQuiz interrupted. Exiting gracefully. Goodbye!")
break
if __name__ == "__main__":
main()