python-knowledge-test / index.html
dwellnick's picture
Update index.html
c91594a verified
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Python Knowledge Test</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
:root {
--primary-color: #3776ab;
--secondary-color: #ffd43b;
--dark-color: #306998;
--light-color: #f8f9fa;
--success-color: #28a745;
--danger-color: #dc3545;
--warning-color: #ffc107;
--info-color: #17a2b8;
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
body {
background-color: #f5f5f5;
color: #333;
line-height: 1.6;
}
.container {
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
header {
background-color: var(--primary-color);
color: white;
padding: 20px 0;
text-align: center;
border-radius: 8px 8px 0 0;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
margin-bottom: 2rem;
}
header h1 {
font-size: 2.5rem;
margin-bottom: 10px;
}
header p {
font-size: 1.1rem;
opacity: 0.9;
}
.python-icon {
font-size: 3rem;
margin-bottom: 10px;
color: var(--secondary-color);
}
.quiz-container {
background-color: white;
border-radius: 8px;
padding: 30px;
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
margin-bottom: 2rem;
}
.question-counter {
font-size: 1.1rem;
font-weight: bold;
color: var(--primary-color);
margin-bottom: 20px;
display: flex;
justify-content: space-between;
align-items: center;
}
.progress-bar {
height: 8px;
background-color: #e9ecef;
border-radius: 4px;
overflow: hidden;
flex-grow: 1;
margin-left: 20px;
}
.progress {
height: 100%;
background-color: var(--primary-color);
width: 0%;
transition: width 0.3s ease;
}
.question {
font-size: 1.2rem;
font-weight: 500;
margin-bottom: 1.5rem;
}
.options {
display: grid;
grid-template-columns: 1fr;
gap: 12px;
margin-bottom: 1.5rem;
}
.option {
background-color: var(--light-color);
padding: 15px;
border-radius: 6px;
cursor: pointer;
transition: all 0.3s ease;
border: 2px solid transparent;
display: flex;
align-items: center;
}
.option:hover {
background-color: #e2e6ea;
transform: translateY(-2px);
}
.option.selected {
background-color: #e3f2fd;
border-color: var(--primary-color);
}
.option.correct {
background-color: #d4edda;
border-color: var(--success-color);
}
.option.incorrect {
background-color: #f8d7da;
border-color: var(--danger-color);
}
.option input {
margin-right: 10px;
cursor: pointer;
}
.option-label {
font-weight: 500;
flex-grow: 1;
}
.navigation {
display: flex;
justify-content: space-between;
margin-top: 2rem;
}
.btn {
padding: 12px 24px;
border: none;
border-radius: 6px;
cursor: pointer;
font-weight: 600;
transition: all 0.3s ease;
display: inline-flex;
align-items: center;
justify-content: center;
}
.btn-primary {
background-color: var(--primary-color);
color: white;
}
.btn-primary:hover {
background-color: var(--dark-color);
transform: translateY(-2px);
}
.btn-secondary {
background-color: #6c757d;
color: white;
}
.btn-secondary:hover {
background-color: #5a6268;
transform: translateY(-2px);
}
.btn:disabled {
opacity: 0.5;
cursor: not-allowed;
transform: none !important;
}
.result-container {
display: none;
background-color: white;
border-radius: 8px;
padding: 30px;
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
text-align: center;
}
.result-icon {
font-size: 5rem;
margin-bottom: 20px;
}
.excellent {
color: var(--success-color);
}
.good {
color: var(--primary-color);
}
.average {
color: var(--warning-color);
}
.poor {
color: var(--danger-color);
}
h2 {
margin-bottom: 20px;
color: var(--primary-color);
}
.score {
font-size: 3rem;
font-weight: bold;
margin-bottom: 20px;
}
.assessment {
font-size: 1.2rem;
margin-bottom: 25px;
max-width: 600px;
margin-left: auto;
margin-right: auto;
}
.restart-btn {
background-color: var(--primary-color);
color: white;
padding: 12px 30px;
border-radius: 6px;
border: none;
font-weight: 600;
cursor: pointer;
transition: all 0.3s ease;
display: inline-flex;
align-items: center;
}
.restart-btn i {
margin-right: 8px;
}
.restart-btn:hover {
background-color: var(--dark-color);
transform: translateY(-2px);
}
.explanation {
background-color: #f8f9fa;
border-left: 4px solid var(--primary-color);
padding: 15px;
margin-top: 20px;
border-radius: 0 6px 6px 0;
display: none;
}
.explanation-title {
font-weight: bold;
margin-bottom: 8px;
color: var(--primary-color);
}
.wrong-answers {
margin-top: 20px;
text-align: left;
max-width: 600px;
margin-left: auto;
margin-right: auto;
}
.wrong-answers-title {
font-weight: bold;
margin-bottom: 10px;
color: var(--danger-color);
}
.wrong-answer-item {
margin-bottom: 8px;
padding: 8px;
background-color: #f8f9fa;
border-radius: 4px;
}
@media (max-width: 768px) {
.container {
padding: 10px;
}
header h1 {
font-size: 2rem;
}
.quiz-container, .result-container {
padding: 20px;
}
.question {
font-size: 1.1rem;
}
}
</style>
</head>
<body>
<div class="container">
<header>
<div class="python-icon">
<i class="fab fa-python"></i>
</div>
<h1>Python Knowledge Test</h1>
<p>Test your Python programming skills with this 20-question quiz</p>
</header>
<div class="quiz-container" id="quiz">
<div class="question-counter">
<span>Question <span id="current-question">1</span> of 20</span>
<div class="progress-bar">
<div class="progress" id="progress"></div>
</div>
</div>
<div class="question" id="question"></div>
<div class="options" id="options"></div>
<div class="explanation" id="explanation">
<div class="explanation-title">
<i class="fas fa-info-circle"></i> Explanation
</div>
<div id="explanation-text"></div>
</div>
<div class="navigation">
<button class="btn btn-secondary" id="prev-btn" disabled>
<i class="fas fa-arrow-left"></i> Previous
</button>
<button class="btn btn-primary" id="next-btn">
Next <i class="fas fa-arrow-right"></i>
</button>
<button class="btn btn-primary" id="submit-btn" style="display: none;">
Submit <i class="fas fa-paper-plane"></i>
</button>
</div>
</div>
<div class="result-container" id="result-container">
<div class="result-icon" id="result-icon">
<i class="fas fa-trophy"></i>
</div>
<h2>Your Results</h2>
<div class="score" id="score"></div>
<div class="assessment" id="assessment"></div>
<div class="wrong-answers" id="wrong-answers">
<div class="wrong-answers-title">
<i class="fas fa-times-circle"></i> Incorrect Answers
</div>
<div id="wrong-answers-list"></div>
</div>
<button class="restart-btn" id="restart-btn">
<i class="fas fa-redo"></i> Take Again
</button>
</div>
</div>
<script>
// Questions array with options, correct answer, and explanations
const questions = [
{
question: "Which of the following is the correct way to declare a variable in Python?",
options: [
"var name = 'John'",
"name := 'John'",
"name = 'John'",
"let name = 'John'"
],
correct: 2,
explanation: "In Python, variables are declared by simply assigning a value to a name using the equals sign (=). The other syntax shown is used in other languages like JavaScript or more recent Python versions for different purposes."
},
{
question: "What does the 'range()' function return in Python 3?",
options: [
"A list of numbers",
"A tuple of numbers",
"A range object",
"A set of numbers"
],
correct: 2,
explanation: "In Python 3, range() returns an immutable sequence type (range object), not a list. This is more memory efficient as it generates numbers on demand rather than storing them all in memory."
},
{
question: "Which of these collection types in Python is immutable?",
options: [
"List",
"Dictionary",
"Set",
"Tuple"
],
correct: 3,
explanation: "Tuples are immutable in Python, meaning they cannot be changed after creation. Lists, dictionaries, and sets are all mutable types."
},
{
question: "What is the output of '3 * 'ab' + 'ba' in Python?",
options: [
"'abababba'",
"'3abba'",
"'abababa'",
"Error"
],
correct: 0,
explanation: "In Python, multiplying a string by an integer n concatenates the string with itself n times. So 3 * 'ab' becomes 'ababab', then adding 'ba' gives 'abababba'."
},
{
question: "What is the purpose of the '__init__' method in Python classes?",
options: [
"To destroy an object",
"To initialize the object's attributes",
"To create a new class",
"To import modules"
],
correct: 1,
explanation: "The __init__ method is the constructor in Python classes. It's automatically called when an object is created and is used to initialize the object's state (attributes)."
},
{
question: "Which statement is used for exception handling in Python?",
options: [
"try-catch",
"try-except",
"try-exception",
"try-handle"
],
correct: 1,
explanation: "Python uses try-except blocks for exception handling, unlike some other languages that use try-catch. The except block captures and handles exceptions that occur in the try block."
},
{
question: "What is the output of 'bool('False')' in Python?",
options: [
"False",
"True",
"Error",
"None"
],
correct: 1,
explanation: "The bool() function converts values to boolean. Any non-empty string evaluates to True in Python, even if the string is 'False'. Only empty strings evaluate to False."
},
{
question: "Which method would you use to remove an item from a list and return it?",
options: [
"remove()",
"delete()",
"pop()",
"discard()"
],
correct: 2,
explanation: "The pop() method removes and returns an item at the given index (or the last item if no index is specified). remove() deletes the first matching value, delete is a keyword, and discard() is a set method."
},
{
question: "What does the 'pass' statement do in Python?",
options: [
"Throws an error",
"Exits the program",
"Does nothing, acts as a placeholder",
"Continues to the next iteration in a loop"
],
correct: 2,
explanation: "The pass statement is a null operation in Python - it does nothing. It's used when syntax requires a statement but no action is needed, often as a placeholder in empty functions, classes, or conditionals."
},
{
question: "How do you open a file for both reading and writing in Python?",
options: [
"open('file.txt', 'r')",
"open('file.txt', 'w')",
"open('file.txt', 'rw')",
"open('file.txt', 'r+')"
],
correct: 3,
explanation: "The 'r+' mode opens a file for both reading and writing. 'r' is read-only, 'w' is write-only (overwrites file), and 'rw' is not a valid mode."
},
{
question: "What is the output of '[n**2 for n in range(5)]'?",
options: [
"[0, 1, 4, 9, 16]",
"[1, 2, 3, 4, 5]",
"[0, 1, 4, 9, 16, 25]",
"[1, 4, 9, 16, 25]"
],
correct: 0,
explanation: "This is a list comprehension that squares each number in range(5), which produces numbers 0 to 4. The result is [0, 1, 4, 9, 16]."
},
{
question: "Which decorator is commonly used to define a method as a class method?",
options: [
"@staticmethod",
"@classmethod",
"@method",
"@property"
],
correct: 1,
explanation: "The @classmethod decorator is used to define a method as a class method. It receives the class as the first argument (cls) rather than the instance (self)."
},
{
question: "What does the 'yield' keyword do in Python?",
options: [
"Returns a value from a function",
"Pauses function execution and returns a value",
"Terminates a function",
"Raises an exception"
],
correct: 1,
explanation: "The yield keyword pauses function execution and returns a value to the caller, but retains enough state to resume where it left off. Functions containing yield are generator functions."
},
{
question: "How do you create a virtual environment in Python?",
options: [
"python -m venv myenv",
"python create virtualenv myenv",
"python -m virtualenv create myenv",
"python environment myenv"
],
correct: 0,
explanation: "The standard way to create a virtual environment in Python is using 'python -m venv myenv'. This creates a new virtual environment in the 'myenv' directory."
},
{
question: "What is the purpose of the '__name__' variable in Python?",
options: [
"Stores the name of the current user",
"Holds the name of the current function",
"Contains the name of the module being executed",
"Is always '__main__'"
],
correct: 2,
explanation: "The __name__ variable holds the name of the current module. When a module is run directly (not imported), __name__ is set to '__main__', which is a common pattern for code that should only run when the script is executed directly."
},
{
question: "Which of these is NOT a valid dictionary key in Python?",
options: [
"Integer",
"String",
"Tuple",
"List"
],
correct: 3,
explanation: "In Python, dictionary keys must be immutable types. Lists are mutable and cannot be used as dictionary keys. Integers, strings, and tuples (if they contain only immutable elements) can be dictionary keys."
},
{
question: "What does the '//' operator do in Python?",
options: [
"Performs integer (floor) division",
"Is used for comments",
"Performs floating point division",
"Is the exponentiation operator"
],
correct: 0,
explanation: "The // operator performs floor division, returning the largest integer less than or equal to the division result. For example, 5 // 2 returns 2, not 2.5."
},
{
question: "How do you check if an object is an instance of a particular class?",
options: [
"isinstance()",
"type()",
"classof()",
"Both isinstance() and type()"
],
correct: 0,
explanation: "The isinstance() function checks if an object is an instance of a class or its subclasses, which is the preferred way to check types in Python. type() returns the exact type but doesn't account for inheritance."
},
{
question: "What is the output of 'print('Hello, World!'[::-1])'?",
options: [
"'Hello, World!'",
"'!dlroW ,olleH'",
"Error",
"'Hello, World!' printed multiple times"
],
correct: 1,
explanation: "The [::-1] slicing creates a reversed copy of the string by stepping backward through the string. So 'Hello, World!' reversed is '!dlroW ,olleH'."
},
{
question: "Which module would you use for working with dates and times in Python?",
options: [
"datetime",
"time",
"cal",
"All of the above"
],
correct: 0,
explanation: "The datetime module is the primary module for working with dates and times in Python. While the time module exists, it's lower-level, and there is no standard 'cal' module."
}
];
// Quiz state
let currentQuestion = 0;
let score = 0;
let selectedOption = null;
let userAnswers = Array(questions.length).fill(null);
// DOM elements
const quizContainer = document.getElementById('quiz');
const resultContainer = document.getElementById('result-container');
const questionElement = document.getElementById('question');
const optionsElement = document.getElementById('options');
const currentQuestionElement = document.getElementById('current-question');
const progressElement = document.getElementById('progress');
const prevBtn = document.getElementById('prev-btn');
const nextBtn = document.getElementById('next-btn');
const submitBtn = document.getElementById('submit-btn');
const explanationElement = document.getElementById('explanation');
const explanationTextElement = document.getElementById('explanation-text');
const scoreElement = document.getElementById('score');
const assessmentElement = document.getElementById('assessment');
const resultIconElement = document.getElementById('result-icon');
const restartBtn = document.getElementById('restart-btn');
const wrongAnswersList = document.getElementById('wrong-answers-list');
// Initialize the quiz
function initQuiz() {
showQuestion();
updateNavigationButtons();
}
// Display the current question
function showQuestion() {
const question = questions[currentQuestion];
questionElement.textContent = question.question;
optionsElement.innerHTML = '';
currentQuestionElement.textContent = currentQuestion + 1;
progressElement.style.width = `${((currentQuestion + 1) / questions.length) * 100}%`;
// Create options
question.options.forEach((option, index) => {
const optionElement = document.createElement('div');
optionElement.className = 'option';
if (userAnswers[currentQuestion] === index) {
optionElement.classList.add('selected');
selectedOption = index;
}
const input = document.createElement('input');
input.type = 'radio';
input.name = 'option';
input.id = `option-${index}`;
input.value = index;
input.checked = userAnswers[currentQuestion] === index;
input.addEventListener('change', () => selectOption(index));
const label = document.createElement('label');
label.className = 'option-label';
label.htmlFor = `option-${index}`;
label.textContent = option;
optionElement.appendChild(input);
optionElement.appendChild(label);
optionsElement.appendChild(optionElement);
});
// Show explanation if this question was already answered
if (userAnswers[currentQuestion] !== null) {
showExplanation();
} else {
hideExplanation();
}
}
// Handle option selection
function selectOption(index) {
// Remove selected class from all options
document.querySelectorAll('.option').forEach(option => {
option.classList.remove('selected');
});
// Add selected class to clicked option
const selectedOptionElement = document.querySelector(`.option input[value="${index}"]`).parentNode;
selectedOptionElement.classList.add('selected');
selectedOption = index;
userAnswers[currentQuestion] = index;
// If it's the last question, show the submit button
if (currentQuestion === questions.length - 1 && userAnswers[currentQuestion] !== null) {
nextBtn.style.display = 'none';
submitBtn.style.display = 'inline-block';
} else {
nextBtn.style.display = 'inline-block';
submitBtn.style.display = 'none';
}
showExplanation();
}
// Show explanation for the current question
function showExplanation() {
if (userAnswers[currentQuestion] !== null) {
explanationTextElement.textContent = questions[currentQuestion].explanation;
explanationElement.style.display = 'block';
}
}
// Hide the explanation
function hideExplanation() {
explanationElement.style.display = 'none';
}
// Update navigation buttons state
function updateNavigationButtons() {
prevBtn.disabled = currentQuestion === 0;
// For the last question, show submit button if answered
if (currentQuestion === questions.length - 1) {
nextBtn.style.display = userAnswers[currentQuestion] === null ? 'inline-block' : 'none';
submitBtn.style.display = userAnswers[currentQuestion] !== null ? 'inline-block' : 'none';
} else {
nextBtn.style.display = 'inline-block';
submitBtn.style.display = 'none';
}
}
// Go to the next question
function nextQuestion() {
if (currentQuestion < questions.length - 1) {
currentQuestion++;
selectedOption = null;
showQuestion();
updateNavigationButtons();
}
}
// Go to the previous question
function prevQuestion() {
if (currentQuestion > 0) {
currentQuestion--;
selectedOption = userAnswers[currentQuestion];
showQuestion();
updateNavigationButtons();
}
}
// Submit the quiz and show results
function submitQuiz() {
// Calculate score and collect wrong answers
score = 0;
const wrongAnswers = [];
questions.forEach((question, index) => {
if (userAnswers[index] === question.correct) {
score++;
} else if (userAnswers[index] !== null) {
wrongAnswers.push({
questionNumber: index + 1,
question: question.question,
yourAnswer: question.options[userAnswers[index]],
correctAnswer: question.options[question.correct]
});
}
});
// Display results
quizContainer.style.display = 'none';
resultContainer.style.display = 'block';
scoreElement.textContent = `${score}/${questions.length}`;
// Calculate percentage
const percentage = (score / questions.length) * 100;
// Determine assessment
let assessment, iconClass, feedback;
if (percentage >= 90) {
assessment = "Python Expert!";
iconClass = "excellent";
feedback = "Outstanding! Your Python knowledge is comprehensive and detailed. You've demonstrated a deep understanding of Python concepts and syntax. Consider sharing your expertise with others!";
} else if (percentage >= 75) {
assessment = "Advanced Python User";
iconClass = "good";
feedback = "Great job! You have strong Python knowledge with just a few gaps. With a bit more practice, you'll master all the advanced concepts. Consider working on more complex projects to refine your skills.";
} else if (percentage >= 50) {
assessment = "Intermediate Python Programmer";
iconClass = "average";
feedback = "Good effort! You understand the basics and some intermediate concepts of Python. Focus on learning about functions, classes, and Python's standard library to improve your skills.";
} else {
assessment = "Python Beginner";
iconClass = "poor";
feedback = "You're just starting your Python journey! Focus on the fundamentals first - variables, data types, loops, and functions. Practice writing simple programs and gradually increase complexity.";
}
assessmentElement.textContent = feedback;
document.querySelector('#assessment').previousElementSibling.textContent = assessment;
document.querySelector('.result-icon i').className = `fas ${percentage >= 90 ? 'fa-trophy' : percentage >= 75 ? 'fa-award' : percentage >= 50 ? 'fa-star' : 'fa-book'}`;
resultIconElement.className = `result-icon ${iconClass}`;
// Display wrong answers if any
if (wrongAnswers.length > 0) {
wrongAnswersList.innerHTML = '';
wrongAnswers.forEach(item => {
const wrongAnswerElement = document.createElement('div');
wrongAnswerElement.className = 'wrong-answer-item';
wrongAnswerElement.innerHTML = `
<strong>Question ${item.questionNumber}:</strong> ${item.question}<br>
<span style="color: var(--danger-color);">Your answer: ${item.yourAnswer}</span><br>
<span style="color: var(--success-color);">Correct answer: ${item.correctAnswer}</span>
`;
wrongAnswersList.appendChild(wrongAnswerElement);
});
document.getElementById('wrong-answers').style.display = 'block';
} else {
document.getElementById('wrong-answers').style.display = 'none';
}
}
// Restart the quiz
function restartQuiz() {
currentQuestion = 0;
score = 0;
selectedOption = null;
userAnswers = Array(questions.length).fill(null);
quizContainer.style.display = 'block';
resultContainer.style.display = 'none';
showQuestion();
updateNavigationButtons();
}
// Event listeners
nextBtn.addEventListener('click', nextQuestion);
prevBtn.addEventListener('click', prevQuestion);
submitBtn.addEventListener('click', submitQuiz);
restartBtn.addEventListener('click', restartQuiz);
// Initialize the quiz when the page loads
window.addEventListener('DOMContentLoaded', initQuiz);
</script>
</body>
</html>