Sunday, 3 October 2010

LaTeX Quiz

I wanted to create a quiz for a Canadian Thanksgiving party and I decided to use Latex and the Beamer Presentation package to create a PDF slide show of questions. This worked pretty well, but I wanted to create a second PDF file with the answers shown next to each question to aid with marking. Rather than copying all the files and risk the question PDF becoming out of date with the answer PDF, I decided to create some new Latex commands to dynamically insert the answers depending on presence of command line compile option.

The following code...

%Question/Answer Commands
\newcommand{\question}[1]{Question \arabic{q_num}: #1\stepcounter{q_num}}
{%: Show the answers
\newcommand{\answer}[1]{\textcolor{red}{Answer: #1}}
{%: Don't show the answers

...defines the following latex commands:

  1. \question{<question-text>} - This appends a question number to the start of each question. The question number is incremented automatically.

  2. \answer{<answer-text>} - The answer text is only visible when \showanswers is defined as true.

An example Question/Answer slide would look like:

\question{What is brown and sticky?}
\answer{A stick}

If \showanswers is defined as false, the output would be:

Question 1: What is brown and sticky?

If \showanswers is defined as true, the output would be:

Question 1: What is brown and sticky? Answer: A stick

There are many ways to go about defining \showanswers. For example you could just define it in your main .tex file:


Or you could pass it as a command line argument which is what I chose to do using a makefile:

pdflatex --jobname=questions '\newcommand{\showanswers}{false}\input{quiz.tex}'
pdflatex --jobname=answers '\newcommand{\showanswers}{true}\input{quiz.tex}'
#where quiz.tex is the latex file containing quiz questions

This will produce two PDFs one called questions.pdf and one called answers.pdf. Only the second one will have the answers visible