-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathquiz_game.py
More file actions
57 lines (41 loc) · 1.67 KB
/
quiz_game.py
File metadata and controls
57 lines (41 loc) · 1.67 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
import requests
import json
import pprint
import random
import html
url = "https://opentdb.com/api.php?amount=1"
endGame = ""
while endGame != "quit":
r = requests.get(url)
if (r.status_code != 200):
endGame = input("Sorry, there was a problem retrieving the question. Press enter to try again or type 'quit' to quit the game.")
else:
valid_answer = False
answer_number = 1
data = json.loads(r.text)
question = data['results'][0]['question']
answers = data['results'][0]['incorrect_answers']
correct_answer = data['results'][0]['correct_answer']
answers.append(correct_answer)
random.shuffle(answers)
print(html.unescape(question) + "\n")
for answer in answers:
print(str(answer_number) + "- " + html.unescape(answer))
answer_number += 1
while valid_answer == False:
user_answer = input("\nType the number of the correct answer: ")
try:
user_answer = int(user_answer)
if user_answer > len(answers) or user_answer <= 0:
print("Invalid Answer")
else:
valid_answer = True
except:
print("Invalid answer. Please use only numbers.")
user_answer = answers[int(user_answer)-1]
if user_answer == correct_answer:
print("\nCorrect answer!")
else:
print("Sorry, incorrect answer.The correct answer is: " + html.unescape(correct_answer))
endGame = input("\nPress enter to play again or type 'quit' to quit the game.").lower()
print("\nThanks for playing")