Python Week – Day 3 – Quiz App

Blog Status: Draft (In the progress of adding more explanation at each step) but is 90% complete

On Day 2, we created a Coin Flip App to demonstrate Import, If-Else, For Loop, Red From User Input, Random Number, and Logging.

Today, let’s create a Python Quiz App that should be useful for studying for quizzes. This project demonstrates a few more core python concepts (Dictionary, Function, Read from a File).

Below are the steps to create the Python Quiz App:

  • Step 1: Create a words dictionary, and randomly select an item to ask a question
  • Step 2: Populate the words dictionary from a CSV file
  • Step 3: Ask the user to choose which quiz to take, then randomly select a question from that quiz
  • Step 4: Ask the user to select a quiz category, then ask randomly selected questions from a randomly selected quiz
  • Step 5: Further clean up code by creating a quiz_common module

Step 1: Create a words dictionary, and randomly select an item to ask a question

Create a dictionary (named “words”) whose key is an English word and the value is its matching Spanish word.

Create a function (named “random_key”) that does not take any parameter. The random_key function would randomly select a key from the words dictionary and returns the random key.  This key is used to select a word from words and create a question.

Once both words and random_key are set up, let’s use them to add code to randomly pick a question and ask the user for an answer. The question will be asked like “Word for rojo: ” and the user is supposed to type the English word “red”.

To ask the question, we will select a key (English word, such as “red”) which will be the answer, and then ask the question with its matching value (Spanish word, such as “rojo”).

File: pythonquiz/quiz_step1.py

import random

# function to randomly pick a "key" for picking a question 
def random_key():
    # find all the keys, 'keys' now in a SET data structure
    keys = words.keys()
    # convert 'keys' to LIST
    keys = list(keys)
    # randomly select a key from 'keys'
    random_key = random.choice(keys)
    return random_key

# word dictionary 
words = {
    "red" : "rojo",
    "blue" : "azul",
    "water" : "aqua",
    "sky" : "cielo",  
    "love" : "amor",  
}

random_answer = random_key()
random_question = words[random_answer]

# ask and read user input
user_answer = input("Word for " + random_question + ": ")
user_answer = user_answer.strip()
if (user_answer == random_answer):
    print("correct")
else:
    print ("incorrect")

 

Step 2: Populate the words dictionary from a CSV file

Create a folder called “spanish”, and in that folder, add several CSV files that look like

File: pythonquiz/spanish/quiz1.csv

"water","aqua"   
"sky","cielo"  
"love","amor"

File: pythonquiz/spanish/quiz2.csv

"red","rojo"
"white","blanco"
"yellow","amarillo"
"orange","anaranjado"
"blue","azul"
"teal","verde azulado"
"green","verde"
"black","negro"
"brown","marrón"
"pink","rosado"
"purple","morado"

File: pythonquiz/spanish/quiz3.csv

"water","aqua"
"ocean","oceano"
"fish","pez"
"squid","calamar"
"shrimp","camaron"
"sand","arena"
"island","isla"

Then add a function called “read_from_file” which also takes an input parameter called file_name.

import random
import csv

# function to read the questions from a file 
def read_data_from_file(file_name):
    with open(file_name) as csv_file:
        # csv_file is the file handler
        # lines are all the lines from file
        lines = csv.reader(csv_file)
        for data_list in lines:
            question = data_list[0]
            question = question.strip()
            answer = data_list[1]
            answer = answer.strip()
            words[question] = answer
# function to randomly select a key from words
def random_key():
    # find all the keys
    keys = words.keys()
    keys = list(keys)
    random_key = random.choice(keys)
    return random_key

words = { }
word_file = "spanish/quiz1.csv"
read_data_from_file(word_file)

random_answer = random_key()
random_question = words[random_answer]

user_answer = input("Word for " + random_question + ": ")
user_answer = user_answer.strip()
if (user_answer == random_answer):
    print("correct")
else:
    print ("incorrect")

 

Step 3: Ask the user to choose which quiz to take, then randomly select a question from that quiz

import random
import csv

# function to read the questions from a file 
def read_data_from_file(file_name):
    with open(file_name) as csv_file:
        # csv_file is the file handler
        # lines are all the lines from file
        lines = csv.reader(csv_file)
        for data_list in lines:
            question = data_list[0]
            answer = data_list[1]
            words[question] = answer

# function to randomly select a key from words
def random_key():
    # find all the keys
    keys = words.keys()
    keys = list(keys)
    random_key = random.choice(keys)
    return random_key
words = { }


data_files_path = "spanish/"

# ask the user for quiz name
# open the file with name <data_files_path><quiz_name>.csv
# example: spanish/quiz1.csv
quiz_name = input("Pick a Quiz [quiz1, quiz2, quiz3] ")
word_file = data_files_path + quiz_name + ".csv"
read_data_from_file(word_file)

random_answer = random_key()
random_question = words[random_answer]

user_answer = input("Word for " + random_question + ": ")
if (user_answer == random_answer):
    print("correct")
else:
    print ("incorrect")

 

Step 4: Ask the user to select a quiz category, then ask randomly selected questions from a randomly selected quiz

import random
import csv

# function to read the questions from a file 
def read_data_from_file(file_name):
    with open(file_name) as csv_file:
        # csv_file is the file handler
        # lines are all the lines from file
        lines = csv.reader(csv_file)
        for data_list in lines:
            question = data_list[0]
            answer = data_list[1]
            words[question] = answer
# function to randomly select a key from words
def random_key():
    # find all the keys
    keys = words.keys()
    keys = list(keys)
    random_key = random.choice(keys)
    return random_key
words = { }

# ask the user for quiz type
print("Quiz Types: sat, spanish")
quiz_type = input("Enter quiz type: ")
data_files_path = quiz_type + "/"

# randomly select a file
random_file_num = random.randrange(1,3)
random_file_num = str(random_file_num)
word_file = data_files_path + "quiz" + random_file_num + ".csv"
read_data_from_file(word_file)

random_answer = random_key()
random_question = words[random_answer]

user_answer = input("Word for " + random_question + ": ")
if (user_answer == random_answer):
    print("correct")
else:
    print ("incorrect")

 

Step 5: Add support for different types of quizzes

To support different types of quizzes, create another folder

File: quiz_common.py

import random
import csv

# function to read the questions from a file 
def read_data_from_file(words, file_name):
    with open(file_name) as csv_file:
        # csv_file is the file handler
        # lines are all the lines from file
        lines = csv.reader(csv_file)
        for data_list in lines:
            question = data_list[0]
            answer = data_list[1]
            words[question] = answer

# function to randomly select a key from words
def random_key(words):
    # find all the keys
    keys = words.keys()
    keys = list(keys)
    random_key = random.choice(keys)
    return random_key

 

File: quiz_step5.py

import random
import quiz_common

words = { }

# ask the user for quiz type
print("Quiz Types: sat, spanish")
quiz_type = input("Enter quiz type: ")
data_files_path = quiz_type + "/"

# randomly select a file
random_file_num = random.randrange(1,3)
random_file_num = str(random_file_num)
word_file = data_files_path + "quiz" + random_file_num + ".csv"
quiz_common.read_data_from_file(words, word_file)

random_answer = quiz_common.random_key(words)
random_question = words[random_answer]

user_answer = input("Word for " + random_question + ": ")
if (user_answer == random_answer):
    print("correct")
else:
    print ("incorrect")

 

Source Code

The source code for this blog is available at https://github.com/jess1sd/pythonquiz