|
| 1 | +import requests |
| 2 | +from time import sleep |
| 3 | +import html |
| 4 | + |
| 5 | +def fetch_quiz_data(amount=4, quiz_type='boolean'): |
| 6 | + url = f"https://opentdb.com/api.php?amount={amount}&type={quiz_type}" |
| 7 | + response = requests.get(url) |
| 8 | + data_json = response.json() |
| 9 | + return data_json["results"] |
| 10 | + |
| 11 | +def check_answer(question, answer, score): |
| 12 | + correct_answer = html.unescape(question['correct_answer']).lower() |
| 13 | + answer = answer.lower() |
| 14 | + |
| 15 | + if answer == correct_answer: |
| 16 | + print("Correct Answer! \nYour score is", score + 1) |
| 17 | + return True |
| 18 | + else: |
| 19 | + print("Wrong Answer! \nYour score is", score - 1) |
| 20 | + print(f"The correct answer is {html.unescape(question['correct_answer'])}") |
| 21 | + return False |
| 22 | + |
| 23 | +def display_question(question, question_number, score): |
| 24 | + print("\n" * 10) |
| 25 | + print("=" * 50) |
| 26 | + print(f"\t\tQuestion number: {question_number}") |
| 27 | + print("=" * 50) |
| 28 | + print(f"\tDifficulty Level: {question['difficulty']}") |
| 29 | + print(f"\tCategory: {question['category']}") |
| 30 | + print("=" * 50) |
| 31 | + print() |
| 32 | + print("Question: ", html.unescape(question['question'])) |
| 33 | + print() |
| 34 | + |
| 35 | +def main(): |
| 36 | + quiz_data = fetch_quiz_data() |
| 37 | + score = 0 |
| 38 | + question_number = 0 |
| 39 | + |
| 40 | + for question in quiz_data: |
| 41 | + question_number += 1 |
| 42 | + |
| 43 | + display_question(question, question_number, score) |
| 44 | + |
| 45 | + answer = input("Enter Answer (To skip type 'skip'): ") |
| 46 | + print("\n" * 10) |
| 47 | + |
| 48 | + if answer == "skip": |
| 49 | + continue |
| 50 | + |
| 51 | + if check_answer(question, answer, score): |
| 52 | + score += 1 |
| 53 | + print("Wait moving to the next question...") |
| 54 | + sleep(6) |
| 55 | + else: |
| 56 | + score -= 1 |
| 57 | + print("Point deducted...") |
| 58 | + print("Wait moving to the next question...") |
| 59 | + sleep(6) |
| 60 | + |
| 61 | + print("\n" * 10) |
| 62 | + print("Your final score is", score, "!") |
| 63 | + print("Thanks for playing! 💜") |
| 64 | + |
| 65 | +if __name__ == "__main__": |
| 66 | + main() |
0 commit comments