Python Full Stack Web Developer Course

Week 3: Python Fundamentals (Part 2)

Friday Afternoon: Week 1-3 Cumulative Quiz

Consolidating Your Knowledge

Welcome to the Week 1-3 cumulative quiz! This assessment is designed to test your understanding of the key concepts we've covered in the first three weeks of our course. The quiz covers Python fundamentals, setup and containerization, version control, and the beginning of our journey into web development.

This isn't just a test—it's a learning opportunity. Each question is crafted to reinforce important concepts, and the explanations provided after each answer will help deepen your understanding.

Instructions: Select the best answer for each question. After completing the quiz, we'll review the answers together to ensure everyone has a solid foundation before we dive deeper into web development next week.

Part 1: Environment Setup and Tools

Question 1: Docker Containers

What is the main advantage of using Docker containers for development?

Answer: B

Docker containers create isolated environments with all the dependencies needed to run your application. This ensures consistency across different development, testing, and production environments, eliminating the "it works on my machine" problem. Containers package code, runtime, system tools, and libraries into standardized units, making applications more portable and easier to deploy.

Real-world application: In a web development team, some developers might use Windows machines, others Mac or Linux. Docker ensures that regardless of the local operating system, everyone's development environment behaves identically, reducing environment-specific bugs.

Question 2: Version Control

Which Git command would you use to download a remote repository to your local machine for the first time?

Answer: C

git clone creates a copy of a remote repository on your local machine. This command downloads all files, branches, and commits from the remote repository. In contrast:

  • git pull updates an existing local repository with changes from a remote repository
  • git checkout is used to switch between branches or restore files
  • git fetch downloads changes from a remote repository but doesn't merge them

Example usage: git clone https://github.com/username/repository.git

Question 3: Virtual Environments

Why should you use virtual environments for Python projects?

Answer: B

Virtual environments create isolated spaces for Python projects, each with its own dependencies, packages, and even Python versions. This isolation is crucial when working on multiple projects that might require different versions of the same library, preventing conflicts that would otherwise occur when installing packages globally.

Example: Project A might require Flask 1.0, while Project B needs Flask 2.0. Without virtual environments, you could only install one version system-wide, creating compatibility issues for one of your projects.

Part 2: Python Basics

Question 4: Data Types

Which of the following is not a mutable data type in Python?

Answer: D

Tuples are immutable, meaning once created, their elements cannot be changed. Lists, dictionaries, and sets are all mutable data types that can be modified after creation.

Example:

# Mutable types can be modified
my_list = [1, 2, 3]
my_list[0] = 10  # Works fine: [10, 2, 3]

my_dict = {'a': 1, 'b': 2}
my_dict['a'] = 10  # Works fine: {'a': 10, 'b': 2}

my_set = {1, 2, 3}
my_set.add(4)  # Works fine: {1, 2, 3, 4}

# Immutable types cannot be modified
my_tuple = (1, 2, 3)
my_tuple[0] = 10  # Error: 'tuple' object does not support item assignment

Understanding mutability is crucial for predicting how data will behave in your programs, especially when passing data to functions or storing it in data structures.

Question 5: Control Flow

What will the following code output?

x = 5
if x > 10:
    print("A")
elif x > 5:
    print("B")
elif x > 0:
    print("C")
else:
    print("D")

Answer: C

The code checks conditions in order:

  1. Is x > 10? No (x is 5), so it moves to the next condition.
  2. Is x > 5? No (x is 5), so it moves to the next condition.
  3. Is x > 0? Yes (5 > 0), so it prints "C" and exits the if-else block.

This demonstrates how conditional statements are evaluated sequentially, and once a condition is met, the associated code block executes and the rest of the if-else chain is skipped.

Question 6: Lists and Loops

What will the following code output?

numbers = [1, 2, 3, 4, 5]
result = []

for num in numbers:
    if num % 2 == 0:
        result.append(num * 2)

print(result)

Answer: B

This code loops through the numbers list and, for each number that is even (divisible by 2 with no remainder), it appends twice that number to the result list.

Step by step:

  1. num = 1: Not even, so nothing is appended.
  2. num = 2: Even, so 2 * 2 = 4 is appended. result = [4]
  3. num = 3: Not even, so nothing is appended.
  4. num = 4: Even, so 4 * 2 = 8 is appended. result = [4, 8]
  5. num = 5: Not even, so nothing is appended.

This example combines several concepts: list iteration, conditional statements, and list manipulation—all common patterns in Python programming.

Part 3: Functions and Modules

Question 7: Function Parameters

What is the output of the following code?

def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

print(greet("Alice"))
print(greet("Bob", "Hi"))

Answer: B

This question tests understanding of default parameters in Python functions:

  • The greet function has two parameters: name and greeting.
  • greeting has a default value of "Hello", which is used when the parameter isn't specified.
  • In greet("Alice"), only the name is provided, so the default greeting "Hello" is used.
  • In greet("Bob", "Hi"), both the name and greeting are provided, so "Hi" overrides the default.

Default parameters are a powerful feature in Python, allowing functions to have optional arguments while maintaining backward compatibility.

Question 8: Importing Modules

What is the correct way to import and use the randint function from the random module?

Answer: B and C are both correct approaches

Python provides multiple ways to import modules and their contents:

  1. import random; x = random.randint(1, 10) - Import the entire module and access its functions using dot notation.
  2. from random import randint; x = randint(1, 10) - Import specific functions from a module, allowing you to use them directly without the module prefix.

Option A is incorrect because you can't import a function directly using dot notation. Option D has incorrect syntax—the import ... from ... syntax doesn't exist in Python.

For web development, both importing styles are common, but import module is often preferred for clarity and to avoid name conflicts.

Question 9: Scope

What will the following code output?

x = 10

def modify_value():
    x = 20
    print("Inside function:", x)

modify_value()
print("Outside function:", x)

Answer: B

This question tests understanding of variable scope in Python:

  • The global variable x is assigned the value 10.
  • Inside the function, a new local variable also named x is created and assigned the value 20.
  • This local x only exists within the function and does not affect the global x.
  • When the function prints the value of x, it refers to the local variable.
  • When the code outside the function prints the value of x, it refers to the global variable.

If the function wanted to modify the global variable, it would need to use the global keyword:

def modify_global():
    global x
    x = 20

Understanding scope is crucial in web development, where different functions and modules need to access and potentially modify shared data.

Part 4: Object-Oriented Programming

Question 10: Classes and Objects

What is the output of the following code?

class Dog:
    def __init__(self, name):
        self.name = name
        
    def bark(self):
        return f"{self.name} says woof!"

dog1 = Dog("Buddy")
print(dog1.bark())

Answer: C

This code demonstrates the basics of classes and objects in Python:

  • The Dog class has an __init__ method that initializes each dog with a name.
  • The bark method returns a string that includes the dog's name.
  • We create a Dog instance named "Buddy".
  • When we call dog1.bark(), it returns "Buddy says woof!"

Object-oriented programming is fundamental in web development frameworks like Django, where models, views, and controllers are implemented as classes. Understanding class instantiation and method calling is essential for working with these frameworks.

Question 11: Inheritance

What will the following code output?

class Animal:
    def speak(self):
        return "Some sound"
        
class Dog(Animal):
    def speak(self):
        return "Woof!"
        
class Cat(Animal):
    def speak(self):
        return "Meow!"

animals = [Dog(), Cat(), Animal()]
for animal in animals:
    print(animal.speak())

Answer: A

This code demonstrates inheritance and polymorphism:

  • Animal is the base class with a speak method.
  • Dog and Cat are derived classes that override the speak method.
  • We create a list containing one instance of each class.
  • When we loop through the list and call speak on each object, Python calls the appropriate method for each object's type.

This is an example of polymorphism, where objects of different classes can be treated through a common interface (the speak method). This is particularly useful in web frameworks where similar components (like different types of form fields or database models) share a common interface but have specialized behaviors.

Question 12: Special Methods

What will the following code output?

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        
    def __str__(self):
        return f"Point({self.x}, {self.y})"
    
    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)

p1 = Point(1, 2)
p2 = Point(3, 4)
p3 = p1 + p2
print(p3)

Answer: C

This code demonstrates special (magic) methods in Python:

  • __init__ is the constructor that initializes the object.
  • __str__ defines how the object is converted to a string (used by print and str).
  • __add__ defines the behavior of the + operator for this class.

When p1 + p2 is evaluated, Python calls p1.__add__(p2), which returns a new Point with coordinates (4, 6). When this point is printed, the __str__ method is called, resulting in the string "Point(4, 6)".

Special methods allow you to make your custom classes work with Python's built-in operators and functions, leading to more intuitive and readable code. In web development, frameworks often use special methods to implement features like serialization, rendering, and form validation.

Part 5: Error Handling and File Operations

Question 13: Exception Handling

What will the following code output if the file "data.txt" doesn't exist?

try:
    with open("data.txt", "r") as file:
        content = file.read()
    print("File read successfully")
except FileNotFoundError:
    print("File not found")
finally:
    print("Operation completed")

Answer: B

This code demonstrates Python's exception handling:

  • The code attempts to open and read a file.
  • If the file doesn't exist, a FileNotFoundError is raised.
  • The except block catches this specific error and prints "File not found".
  • The finally block always executes, regardless of whether an exception occurred, and prints "Operation completed".

Proper exception handling is crucial in web development to gracefully handle errors like missing files, database connection failures, or API timeouts. Without it, errors could crash your application or expose sensitive information to users.

Question 14: File Operations

What does the "w" mode do when opening a file in Python?

Answer: B

File modes in Python determine how a file is opened:

  • 'r' - Read (default): Open for reading only.
  • 'w' - Write: Open for writing, truncating the file first (erasing existing content). Creates the file if it doesn't exist.
  • 'a' - Append: Open for writing, appending to the end of the file. Creates the file if it doesn't exist.
  • 'x' - Exclusive creation: Create a new file, failing if it already exists.
  • 'b' - Binary mode (can be combined with other modes)
  • 't' - Text mode (default, can be combined with other modes)
  • '+' - Update (reading and writing, can be combined with other modes)

In web development, file operations are common for tasks like processing uploaded files, generating reports, reading configuration files, or managing logs.

Question 15: Context Managers

What is the primary advantage of using the with statement when working with files?

Answer: C

The with statement in Python is used for context management:

  • It ensures proper acquisition and release of resources.
  • For files, it automatically calls close() when the block is exited, even if exceptions occur.
  • This prevents resource leaks and makes the code more robust.

Example usage:

# Using with (recommended)
with open("file.txt", "r") as file:
    content = file.read()
# File is automatically closed here

# Without with (prone to resource leaks)
file = open("file.txt", "r")
try:
    content = file.read()
finally:
    file.close()  # Must manually close

In web development, context managers are valuable for managing database connections, network resources, and temporary files, ensuring they're properly cleaned up regardless of any errors.

Part 6: Web Development Concepts

Question 16: HTTP Basics

Which HTTP method should be used to retrieve data from a server without modifying any resources?

Answer: A

HTTP methods define the type of operation to be performed on a resource:

  • GET - Retrieve data without modifying resources (safe, idempotent)
  • POST - Submit data to create a new resource (not idempotent)
  • PUT - Update a resource with new data (idempotent)
  • DELETE - Remove a resource (idempotent)
  • PATCH - Partially update a resource (not necessarily idempotent)
  • HEAD - Like GET but without the response body (safe, idempotent)
  • OPTIONS - Get information about available communication options (safe)

In RESTful web development, using the correct HTTP methods for appropriate operations is a key principle for creating clear, consistent APIs.

Question 17: Client-Server Model

In the context of web architecture, what is the role of a web server?

Answer: C

The client-server model is fundamental to web architecture:

  • Web Server: Receives HTTP requests from clients, processes them (possibly by running server-side code or retrieving static files), and sends back HTTP responses.
  • Web Client (Browser): Sends HTTP requests to servers and renders the received HTML, CSS, JavaScript, and other assets into a visual interface for the user.
  • Database Server: Stores and retrieves structured data (separate from the web server in larger applications).

Common web servers include Apache, Nginx, and Microsoft IIS. In Python web development, your application typically runs within a WSGI or ASGI server (like Gunicorn, uWSGI, or Uvicorn) that interfaces with a front-end web server.

Question 18: JSON

Which Python module would you use to convert a Python dictionary to a JSON string?

Answer: A

Python's json module provides methods for working with JSON data:

  • json.dumps() - Convert Python objects to JSON strings
  • json.loads() - Parse JSON strings to Python objects
  • json.dump() - Write Python objects as JSON to a file
  • json.load() - Read JSON from a file into Python objects

Example:

import json

# Python dictionary
user = {
    "name": "John Doe",
    "age": 30,
    "email": "john@example.com",
    "is_active": True,
    "tags": ["user", "customer"]
}

# Convert to JSON string
json_string = json.dumps(user, indent=2)
print(json_string)

# Parse JSON string back to Python
parsed_data = json.loads(json_string)
print(parsed_data["name"])  # John Doe

JSON (JavaScript Object Notation) is the primary data interchange format for web APIs. In Python web development, you'll frequently serialize data to JSON for API responses and deserialize JSON from API requests.

Question 19: Package Management

Which command would you use to install a Python package from PyPI?

Answer: B

pip is Python's package installer. It allows you to install and manage packages from the Python Package Index (PyPI) and other sources.

Common pip commands:

  • pip install package_name - Install a package
  • pip install package_name==1.2.3 - Install a specific version
  • pip install -r requirements.txt - Install packages listed in a requirements file
  • pip uninstall package_name - Remove a package
  • pip list - List installed packages
  • pip freeze - Output installed packages in requirements format
  • pip show package_name - Show information about a package

In web development, dependency management is crucial for ensuring consistent environments across development, testing, and production. Tools like pip, along with virtual environments and requirements files, help maintain these consistent environments.

Question 20: Web Security

Which of the following is a common web security vulnerability that occurs when untrusted data is sent to a web browser without proper validation or escaping?

Answer: B

Cross-Site Scripting (XSS) occurs when an attacker injects malicious scripts into web pages viewed by other users. This happens when applications take untrusted data (like user input) and send it to a web browser without proper validation or escaping.

To prevent XSS in Python web applications:

  • Always escape user-generated content before rendering it in HTML
  • Use template systems that automatically escape variables (like Jinja2)
  • Implement Content Security Policy (CSP) headers
  • Validate and sanitize user input

Example of vulnerable code:

# Vulnerable Flask route
@app.route('/search')
def search():
    query = request.args.get('q', '')
    return f"<h1>Search results for: {query}</h1>"  # Unsafe!

If a user submits q=<script>alert('XSS')</script>, the script would execute in other users' browsers.

Secure version:

# Secure Flask route using template with automatic escaping
@app.route('/search')
def search():
    query = request.args.get('q', '')
    return render_template('search.html', query=query)  # Safe

Web security vulnerabilities can have severe consequences, from data theft to account hijacking. Understanding these vulnerabilities and how to prevent them is essential for building secure web applications.

Congratulations on Completing the Quiz!

Now that you've completed the Week 1-3 cumulative quiz, you should have a good understanding of your strengths and areas for improvement. Here's what to focus on next:

Remember, mastering these fundamentals is crucial for success in web development. The time you invest now in solidifying these concepts will pay dividends throughout your career as a Python developer.

Additional Resources