DEV Community

Arhan Khan
Arhan Khan

Posted on

Build a Python Quiz App with JavaScript

Python is the first language for millions of new programmers, and a quiz app is a perfect way to practise both Python and JavaScript at once: you write the quiz in JavaScript, and the questions test Python. In this project you will build a ten-question Python quiz with instant feedback, a final score, and a review of every answer.

If you are learning Python yourself and want books to go with the quiz, these best Python books for beginners cover the language from zero — variables, loops, functions, and object-oriented programming — in the same order the quiz follows.

Build the quiz around a data array so adding questions is trivial. Each question has the question text, four options, the index of the right answer, and a one-line explanation.

<div id="quiz"></div>
<button id="next">Next question</button>
<div id="result"></div>
Enter fullscreen mode Exit fullscreen mode
const questions = [
  {
    q: 'What does print(type([])) output in Python?',
    options: ["<class 'list'>", "<class 'array'>", "<class 'tuple'>", '[]'],
    answer: 0,
    why: '[] creates a list, and type() returns its class.'
  },
  {
    q: 'Which keyword defines a function in Python?',
    options: ['func', 'def', 'function', 'define'],
    answer: 1,
    why: 'Functions are defined with def, followed by the name and parameters.'
  },
  {
    q: 'What is the output of len("Python")?',
    options: ['5', '6', '7', 'Error'],
    answer: 1,
    why: 'The string "Python" has 6 characters.'
  }
];

let current = 0, score = 0;
const quizEl = document.getElementById('quiz');

function render() {
  const item = questions[current];
  quizEl.innerHTML = `<h3>Q${current + 1}. ${item.q}</h3>` +
    item.options.map((opt, i) => `<button data-i="${i}">${opt}</button>`).join('');
  quizEl.querySelectorAll('button').forEach(btn => btn.onclick = () => {
    const picked = +btn.dataset.i;
    if (picked === item.answer) score++;
    quizEl.innerHTML += `<p>${picked === item.answer ? 'Correct!' : 'Wrong.'} ${item.why}</p>`;
  });
}

document.getElementById('next').onclick = () => {
  current++;
  if (current < questions.length) render();
  else document.getElementById('result').textContent =
    `You scored ${score} out of ${questions.length}. Review the questions above and try again!`;
};

render();
Enter fullscreen mode Exit fullscreen mode

Good quiz design matters as much as code: shuffle the options, vary the difficulty, and keep explanations to one sentence. A quiz that teaches is better than a quiz that only tests.

Extend it next: add a 30-second timer per question, track the best score in localStorage, and add a "hard mode" with ten more questions on list comprehensions and dictionaries. You will have a small app you can genuinely show to other learners.

Top comments (0)