Let’s create a Python trivia quiz game with Python. The user will have 1 minute time to answer as many questions as he can. The questions will be about Pythons libraries, classes, functions, loops, etc.. This will be a fun way to practice your python knowledge as well.
First, import the time module, so we can track the time. Then we are going to import the random module, so we can randomly choose a question from our questions dictionary (questions.py) and lastly import the ‘colorama’ library. We will make correct answers to be green and wrong to be red. So first, let’s install the library:
pip install colorama
The question should not repeat itself, so we will store it into asked_questions list (line 42).
The ‘remaining_questions’ is another list where we will store all questions from questions, but not including the asked_questions (line 8)
import time
import random
from questions import questions
from colorama import Fore, Back, Style
def ask_question(asked_questions):
remaining_questions = [q for q in questions if q not in asked_questions]
if not remaining_questions:
print('All questions have been asked.')
return False, None
question = random.choice(remaining_questions)
print(question['q'])
for answer, text in question['answers'].items():
print(f'{answer}: {text}')
player_answer = input('Answer (A/B/C/D): ')
if player_answer.upper() == question['correct']:
print(Fore.GREEN + f'Correct! Score: {score}')
if 60 - (time.time() - int(start_time)) > 0:
print(round(60 - (time.time() - start_time)), 'seconds left!')
print(Style.RESET_ALL)
print('-'*50)
return True, question
else:
print(Fore.RED + 'Incorrect.')
if 60 - (time.time() - int(start_time)) > 0:
print(round(60 - (time.time() - start_time)), 'seconds left!')
print(Style.RESET_ALL)
print('-'*50)
return False, question
def run_game():
global score
score = 1
asked_questions = []
global start_time
start_time = time.time()
while time.time() - start_time < 60:
is_correct, question = ask_question(asked_questions)
if is_correct:
score += 1
asked_questions.append(question)
print('Time\'s up!')
print(Fore.BLUE + f'You answered {score - 1} correct.')
run_game()
questions.py
questions = [
{'q': 'What library is used for scientific computing in Python?', 'answers': {'A': 'Pandas', 'B': 'NumPy', 'C': 'SciPy', 'D': 'Matplotlib'}, 'correct': 'B'},
{'q': 'What is the difference between a list and a tuple in Python?', 'answers': {'A': 'Lists are mutable and tuples are immutable', 'B': 'Lists can contain different data types and tuples cannot', 'C': 'Tuples are ordered and lists are not', 'D': 'Lists are faster than tuples'},
'correct': 'A'},
{'q': 'What is the purpose of the "zip" function in Python?', 'answers': {'A': 'To compress a file', 'B': 'To combine two or more lists into a list of tuples', 'C': 'To unzip a file', 'D': 'To remove duplicates from a list'}, 'correct': 'B'},
{'q': 'What is the purpose of the "range" function in Python?', 'answers': {'A': 'To generate a sequence of numbers', 'B': 'To create a list of strings', 'C': 'To calculate the length of a list', 'D': 'To sort a list of numbers'}, 'correct': 'A'},
{'q': 'What is the purpose of the "map" function in Python?', 'answers': {'A': 'To create a new list by applying a function to each element of an existing list', 'B': 'To remove elements from a list', 'C': 'To sort a list', 'D': 'To find the maximum value in a list'}, 'correct': 'A'},
{'q': 'What is the purpose of the "reduce" function in Python?', 'answers': {'A': 'To create a new list by applying a function to each element of an existing list', 'B': 'To remove elements from a list', 'C': 'To combine elements of a list into a single value', 'D': 'To find the maximum value in a list'}, 'correct': 'C'},
{'q': 'What is the difference between "append" and "extend" in Python?', 'answers': {'A': '"append" adds a single element to a list, while "extend" adds multiple elements', 'B': '"append" adds multiple elements to a list, while "extend" adds a single element', 'C': '"append" adds an element to the beginning of a list, while "extend" adds it to the end', 'D': 'There is no difference, they are synonyms'}, 'correct': 'A'},
{'q': 'What is the difference between "sort" and "sorted" in Python?', 'answers': {'A': '"sort" sorts a list in place, while "sorted" returns a new sorted list', 'B': '"sorted" sorts a list in place, while "sort" returns a new sorted list', 'C': '"sort" and "sorted" are synonyms', 'D': 'Neither "sort" nor "sorted" can be used to sort lists'}, 'correct': 'A'},
{'q': 'What is the difference between "keys" and "values" in a Python dictionary?', 'answers': {'A': '"keys" returns a list of keys, while "values" returns a list of values', 'B': '"keys" returns a list of values, while "values" returns a list of keys', 'C': '"keys" and "values" are synonyms', 'D': 'A dictionary does not have "keys" or "values"'}, 'correct': 'A'},
{'q': 'What is the purpose of a lambda function in Python?', 'answers': {'A': 'To create a new class', 'B': 'To create a new module', 'C': 'To create a new function', 'D': 'To create a small anonymous function'}, 'correct': 'D'},
{'q': 'What is the difference between "==" and "is" in Python?', 'answers': {'A': '"==" compares the values of two objects, while "is" checks if they are the same object in memory', 'B': '"is" compares the values of two objects, while "==" checks if they are the same object in memory', 'C': '"==" and "is" are synonyms', 'D': 'Neither "==" nor "is" can be used to compare objects'}, 'correct': 'A'},
{'q': 'What is the purpose of the "enumerate" function in Python?', 'answers': {'A': 'To create a new list by applying a function to each element of an existing list', 'B': 'To remove elements from a list', 'C': 'To loop over a list and keep track of the index of each element', 'D': 'To find the maximum value in a list'}, 'correct': 'C'},
{'q': 'What is the purpose of the "filter" function in Python?', 'answers': {'A': 'To create a new list by applying a function to each element of an existing list', 'B': 'To remove elements from a list based on a condition', 'C': 'To sort a list', 'D': 'To find the maximum value in a list'}, 'correct': 'B'},
{'q': 'What is the purpose of the "any" function in Python?', 'answers': {'A': 'To check if all elements of a list are equal to a given value', 'B': 'To check if any element of a list is equal to a given value', 'C': 'To check if all elements of a list are True', 'D': 'To check if any element of a list is True'}, 'correct': 'D'},
{'q': 'What is the purpose of the "all" function in Python?', 'answers': {'A': 'To check if all elements of a list are equal to a given value', 'B': 'To check if any element of a list is equal to a given value', 'C': 'To check if all elements of a list are True', 'D': 'To check if any element of a list is True'}, 'correct': 'C'},
{'q': 'What is the purpose of the "try" and "except" statements in Python?', 'answers': {'A': 'To handle errors and exceptions', 'B': 'To create a loop', 'C': 'To define a function', 'D': 'To import a module'}, 'correct': 'A'},
{'q': 'What is the purpose of the "finally" clause in a try-except statement?', 'answers': {'A': 'To handle errors and exceptions', 'B': 'To define a function', 'C': 'To create a loop', 'D': 'To specify code that will always execute, whether an exception was raised or not'}, 'correct': 'D'},
{'q': 'What is the purpose of the "pass" statement in Python?', 'answers': {'A': 'To define a function', 'B': 'To create a loop', 'C': 'To do nothing and avoid a syntax error', 'D': 'To exit a function'}, 'correct': 'C'},
{'q': 'What is the purpose of the "delattr" function in Python?', 'answers': {'A': 'To set an attribute of an object', 'B': 'To get the value of an attribute of an object', 'C': 'To check if an object has a certain attribute', 'D': 'To delete an attribute of an object'}, 'correct': 'D'},
{'q': 'What is the purpose of the "reduce" function in Python?', 'answers': {'A': 'To create a new list by applying a function to each element of an existing list', 'B': 'To remove elements from a list', 'C': 'To find the maximum value in a list', 'D': 'To repeatedly apply a function to the elements of a list, reducing it to a single value'}, 'correct': 'D'},
{'q': 'What is the purpose of the "sorted" function in Python?', 'answers': {'A': 'To sort a list in descending order', 'B': 'To sort a list in ascending order', 'C': 'To reverse the order of a list', 'D': 'To shuffle the elements of a list'}, 'correct': 'B'},
{'q': 'What is the purpose of the "split" method in Python?', 'answers': {'A': 'To concatenate two strings', 'B': 'To split a string into a list', 'C': 'To replace a substring in a string', 'D': 'To join the elements of a list into a string'}, 'correct': 'B'},
{'q': 'What is the purpose of the "strip" method in Python?', 'answers': {'A': 'To concatenate two strings', 'B': 'To split a string into a list', 'C': 'To remove whitespace from the beginning and end of a string', 'D': 'To replace a substring in a string'}, 'correct': 'C'},
{'q': 'What is the purpose of the "isinstance" function in Python?', 'answers': {'A': 'To check if two objects are equal', 'B': 'To check if an object is of a certain class or type', 'C': 'To check if an object has a certain attribute', 'D': 'To check if an object is iterable'}, 'correct': 'B'},
{'q': 'What is the purpose of the "issubclass" function in Python?', 'answers': {'A': 'To check if two objects are equal', 'B': 'To check if an object is of a certain class or type', 'C': 'To check if a class is a subclass of another class', 'D': 'To check if an object has a certain attribute'}, 'correct': 'C'},
{'q': 'What is the purpose of the "enumerate" function in Python?', 'answers': {'A': 'To loop over a list and keep track of the index of each element', 'B': 'To create a new list by applying a function to each element of an existing list', 'C': 'To find the maximum value in a list', 'D': 'To combine two lists into a list of tuples'}, 'correct': 'A'},
{'q': 'What is the purpose of the "lambda" keyword in Python?', 'answers': {'A': 'To define a new class', 'B': 'To define a new function', 'C': 'To create a new list', 'D': 'To define an anonymous function'}, 'correct': 'D'},
{'q': 'What is the difference between a tuple and a list in Python?', 'answers': {'A': 'Tuples are immutable while lists are mutable', 'B': 'Lists are immutable while tuples are mutable', 'C': 'Tuples can be sorted while lists cannot', 'D': 'Lists can be sorted while tuples cannot'}, 'correct': 'A'},
{'q': 'What is the difference between "range" and "xrange" in Python 2?', 'answers': {'A': '"range" returns a list while "xrange" returns an iterator', 'B': '"xrange" returns a list while "range" returns an iterator', 'C': 'There is no difference', 'D': 'The "xrange" function does not exist in Python 2'}, 'correct': 'A'},
{'q': 'What is the purpose of the "try" and "except" keywords in Python?', 'answers': {'A': 'To define a new class', 'B': 'To define a new function', 'C': 'To handle exceptions and errors in code', 'D': 'To define a conditional statement'}, 'correct': 'C'},
{'q': 'What is the purpose of the "finally" keyword in Python?', 'answers': {'A': 'To define a new class', 'B': 'To define a new function', 'C': 'To handle exceptions and errors in code', 'D': 'To define a block of code that will be executed regardless of whether or not an exception is raised'}, 'correct': 'D'},
{'q': 'What is the purpose of the "with" keyword in Python?', 'answers': {'A': 'To define a new class', 'B': 'To define a new function', 'C': 'To handle exceptions and errors in code', 'D': 'To define a block of code that will be executed within a context, with some setup and teardown actions automatically performed before and after the block'}, 'correct': 'D'},
{'q': 'What is the purpose of the "filter" function in Python?', 'answers': {'A': 'To create a new list by applying a function to each element of an existing list', 'B': 'To find the maximum value in a list', 'C': 'To remove elements from a list that do not meet a certain condition', 'D': 'To sort a list in ascending order'}, 'correct': 'C'},
{'q': 'What is the purpose of the "map" function in Python?', 'answers': {'A': 'To create a new list by applying a function to each element of an existing list', 'B': 'To find the maximum value in a list', 'C': 'To remove elements from a list that do not meet a certain condition', 'D': 'To sort a list in ascending order'}, 'correct': 'A'},
{'q': 'What is the purpose of the "reduce" function in Python?', 'answers': {'A': 'To create a new list by applying a function to each element of an existing list', 'B': 'To find the maximum value in a list', 'C': 'To combine the elements of a list into a single value using a specified function', 'D': 'To sort a list in ascending order'}, 'correct': 'C'},
{'q': 'What is the purpose of the "assert" keyword in Python?', 'answers': {'A': 'To define a new class', 'B': 'To define a new function', 'C': 'To check if a condition is true and raise an exception if it is not', 'D': 'To define a conditional statement'}, 'correct': 'C'},
{'q': 'What is the purpose of the "format" method in Python?', 'answers': {'A': 'To create a new list by applying a function to each element of an existing list', 'B': 'To remove whitespace from the beginning and end of a string', 'C': 'To replace placeholders in a string with values', 'D': 'To convert a string to uppercase'}, 'correct': 'C'},
{'q': 'What is the purpose of the "classmethod" decorator in Python?', 'answers': {'A': 'To define a new class', 'B': 'To define a new instance method', 'C': 'To define a new class method', 'D': 'To define a new static method'}, 'correct': 'C'},
{'q': 'What is the purpose of the "staticmethod" decorator in Python?', 'answers': {'A': 'To define a new class', 'B': 'To define a new instance method', 'C': 'To define a new class method', 'D': 'To define a new static method'}, 'correct': 'D'},
{'q': 'What is the purpose of the "super" function in Python?', 'answers': {'A': 'To call a method of the superclass in a subclass', 'B': 'To define a new class', 'C': 'To define a new instance method', 'D': 'To define a new class method'}, 'correct': 'A'},
{'q': 'What is the purpose of the "scikit-learn" library in Python?', 'answers': {'A': 'To work with scientific computing and numerical analysis', 'B': 'To work with data visualization', 'C': 'To work with machine learning', 'D': 'To work with regular expressions'}, 'correct': 'C'},
{'q': 'What is the purpose of the "tensorflow" library in Python?', 'answers': {'A': 'To work with scientific computing and numerical analysis', 'B': 'To work with data visualization', 'C': 'To work with machine learning', 'D': 'To work with regular expressions'}, 'correct': 'C'}
]