🔨 LearnForge

How to Prepare for a Python Automation Interview: Questions, Projects & Tips

Complete guide to Python automation interview preparation with 30+ common questions, portfolio projects, coding challenges, and expert tips for landing automation jobs in Toronto, Vancouver, and Montreal.

📅 Updated January 15, 2026 ⏱️ 25 min read ✍️ LearnForge Team
Python Automation Interview Preparation Canada

Python Automation Interview: What to Expect in 2026

Python automation interviews in Canada have become increasingly rigorous as demand for automation engineers continues to grow. Whether you're applying for roles in Toronto, Vancouver, Montreal, Calgary, or Ottawa, understanding what employers expect is crucial for success.

This comprehensive guide covers everything you need to prepare for a Python automation interview: from fundamental Python questions to advanced automation frameworks, from coding challenges to behavioral interviews, and from portfolio projects to salary negotiations.

What This Guide Covers: 30+ interview questions with detailed answers, 5 portfolio projects to build, coding challenge examples with solutions, behavioral question strategies, and Canada-specific job market insights for 2026.

Typical Interview Structure

Most Python automation interviews follow a structured format:

Interview Preparation Timeline

A structured Python interview preparation plan will maximize your chances of success. Here's a proven timeline:

Week 1: Python Fundamentals Review

  • Data structures: lists, dictionaries, sets, tuples
  • OOP concepts: classes, inheritance, polymorphism
  • Exception handling and file operations
  • Decorators, generators, context managers

Week 2: Automation Frameworks Deep Dive

  • pytest: fixtures, markers, parametrization, plugins
  • Selenium/Playwright: locators, waits, POM pattern
  • requests/httpx: API testing, authentication
  • Reporting: pytest-html, Allure

Week 3: Build Portfolio Projects

  • Create web automation project with POM
  • Build API test suite with pytest
  • Document projects on GitHub with README
  • Add CI/CD pipeline (GitHub Actions)

Week 4: Practice & Mock Interviews

  • Solve coding challenges (LeetCode, HackerRank)
  • Practice explaining code out loud
  • Prepare behavioral stories (STAR method)
  • Do mock interviews with friends or online

Python Fundamentals Interview Questions

These Python interview questions test your core language knowledge. Expect these in the first technical round.

Q1: What's the difference between a list and a tuple?

Answer: Lists are mutable (can be modified after creation) and use square brackets []. Tuples are immutable (cannot be changed) and use parentheses (). Use tuples for fixed data like coordinates or database records. Lists are better for collections that will change.

# List - mutable
my_list = [1, 2, 3]
my_list[0] = 10  # OK

# Tuple - immutable
my_tuple = (1, 2, 3)
my_tuple[0] = 10  # TypeError!

Q2: Explain Python decorators and give an automation use case

Answer: Decorators are functions that modify the behavior of other functions without changing their code. In automation, they're used for logging, retry logic, timing, and authentication.

import time
from functools import wraps

def retry(max_attempts=3):
    """Decorator to retry failed tests"""
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            for attempt in range(max_attempts):
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    if attempt == max_attempts - 1:
                        raise
                    time.sleep(1)
        return wrapper
    return decorator

@retry(max_attempts=3)
def flaky_test():
    # Test that might fail intermittently
    pass

Q3: How do you handle exceptions in automation scripts?

Answer: Use try-except-finally blocks. In automation, handle specific exceptions (like TimeoutException, NoSuchElementException) rather than catching all exceptions. Log errors for debugging and use finally for cleanup.

from selenium.common.exceptions import TimeoutException, NoSuchElementException
import logging

def safe_click(driver, locator):
    try:
        element = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable(locator)
        )
        element.click()
        return True
    except TimeoutException:
        logging.error(f"Timeout waiting for {locator}")
        return False
    except NoSuchElementException:
        logging.error(f"Element not found: {locator}")
        return False
    finally:
        # Cleanup if needed
        pass

Q4: What is a virtual environment and why use it?

Answer: A virtual environment is an isolated Python environment with its own packages and dependencies. It prevents conflicts between projects that need different package versions. Essential for automation projects where you might need specific versions of Selenium, pytest, or other libraries.

Q5: Explain the difference between *args and **kwargs

Answer: *args allows a function to accept any number of positional arguments (as a tuple). **kwargs allows any number of keyword arguments (as a dictionary). Useful for creating flexible automation functions.

def log_action(action, *args, **kwargs):
    """Flexible logging for automation"""
    print(f"Action: {action}")
    print(f"Args: {args}")
    print(f"Kwargs: {kwargs}")

log_action("click", "button", "submit", timeout=10, retry=True)
# Action: click
# Args: ('button', 'submit')
# Kwargs: {'timeout': 10, 'retry': True}

Automation Framework Interview Questions

Python automation frameworks like pytest are essential knowledge. These questions are commonly asked in Canadian tech interviews.

Q6: Explain pytest fixtures and their scope

Answer: Fixtures provide setup/teardown logic for tests. Scopes control how often fixtures run: function (each test), class, module, package, or session (once per test run). Use fixtures for browser setup, database connections, and test data.

import pytest
from selenium import webdriver

@pytest.fixture(scope="session")
def browser():
    """Browser fixture - runs once per session"""
    driver = webdriver.Chrome()
    driver.maximize_window()
    yield driver
    driver.quit()

@pytest.fixture(scope="function")
def logged_in_user(browser):
    """Login fixture - runs for each test"""
    browser.get("https://example.com/login")
    # Login logic here
    yield
    # Logout in teardown

Q7: What are pytest markers and how do you use them?

Answer: Markers are decorators that add metadata to tests. Use them to categorize tests (smoke, regression), skip tests conditionally, or mark expected failures. Run specific markers with pytest -m "smoke".

import pytest

@pytest.mark.smoke
def test_login():
    """Smoke test - runs in CI"""
    pass

@pytest.mark.regression
def test_complex_workflow():
    """Regression test - runs nightly"""
    pass

@pytest.mark.skip(reason="Bug #123 pending fix")
def test_broken_feature():
    pass

@pytest.mark.parametrize("username,password", [
    ("user1", "pass1"),
    ("user2", "pass2"),
])
def test_login_multiple_users(username, password):
    """Data-driven test"""
    pass

Q8: How do you run tests in parallel with pytest?

Answer: Use pytest-xdist plugin. Install with pip install pytest-xdist, then run pytest -n auto (auto-detect CPUs) or pytest -n 4 (4 workers). Ensure tests are independent and don't share state. Use fixtures with appropriate scope.

Q9: Compare pytest vs unittest

Answer: pytest has simpler syntax (plain assert), powerful fixtures, parametrization, and a rich plugin ecosystem. unittest is built-in, requires classes and setUp/tearDown methods, and has verbose assertions. pytest is the industry standard for automation; unittest is useful for understanding Python's testing foundation.

Selenium & Web Automation Interview Questions

Selenium interview questions are crucial for web automation roles. Canadian employers expect deep knowledge of browser automation.

Q10: How do you handle dynamic elements in Selenium?

Answer: Use explicit waits with WebDriverWait, relative locators, XPath functions like contains() and starts-with(), or CSS selectors with partial attribute matching. Avoid hardcoded sleeps.

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

# Explicit wait for dynamic element
wait = WebDriverWait(driver, 10)
element = wait.until(
    EC.presence_of_element_located((By.XPATH, "//button[contains(@id, 'submit')]"))
)

# XPath with contains() for dynamic IDs
driver.find_element(By.XPATH, "//div[contains(@class, 'loading')]")

# CSS selector with partial attribute
driver.find_element(By.CSS_SELECTOR, "[id^='user_']")  # starts with
driver.find_element(By.CSS_SELECTOR, "[id$='_btn']")   # ends with

Q11: Explain the Page Object Model (POM) pattern

Answer: POM separates page elements and actions from tests. Each page has a class with locators and methods. Benefits: reusability, maintainability, and cleaner tests. This is essential for scalable automation frameworks.

# pages/login_page.py
class LoginPage:
    URL = "https://example.com/login"

    # Locators
    USERNAME_INPUT = (By.ID, "username")
    PASSWORD_INPUT = (By.ID, "password")
    LOGIN_BUTTON = (By.CSS_SELECTOR, "button[type='submit']")

    def __init__(self, driver):
        self.driver = driver

    def navigate(self):
        self.driver.get(self.URL)

    def login(self, username, password):
        self.driver.find_element(*self.USERNAME_INPUT).send_keys(username)
        self.driver.find_element(*self.PASSWORD_INPUT).send_keys(password)
        self.driver.find_element(*self.LOGIN_BUTTON).click()

# tests/test_login.py
def test_successful_login(browser):
    login_page = LoginPage(browser)
    login_page.navigate()
    login_page.login("user@example.com", "password123")
    assert "dashboard" in browser.current_url

Q12: What's the difference between implicit and explicit waits?

Answer: Implicit wait sets a global timeout for all element searches. Explicit wait targets specific conditions for specific elements. Best practice: use explicit waits. Implicit waits can mask performance issues and make debugging harder. Never mix both as they can cause unexpected timeout behavior.

Q13: How do you handle alerts, frames, and windows in Selenium?

Answer: Use driver.switch_to for context switching. Always switch back after handling frames/windows.

# Handle alert
alert = driver.switch_to.alert
alert.accept()  # or alert.dismiss()

# Handle frame
driver.switch_to.frame("frame_name")  # by name/id
driver.switch_to.frame(0)  # by index
driver.switch_to.default_content()  # back to main

# Handle new window
original_window = driver.current_window_handle
driver.find_element(By.LINK_TEXT, "Open New Window").click()
for handle in driver.window_handles:
    if handle != original_window:
        driver.switch_to.window(handle)
        break
# Do something in new window
driver.close()
driver.switch_to.window(original_window)

API Testing Interview Questions

API testing with Python is increasingly important. Many automation roles require both UI and API testing skills.

Q14: How do you test REST APIs with Python?

Answer: Use the requests library for API calls, pytest for test structure, and validate responses with assertions. Check status codes, response time, JSON schema, and data accuracy.

import requests
import pytest

BASE_URL = "https://api.example.com"

def test_get_users():
    response = requests.get(f"{BASE_URL}/users")

    # Status code validation
    assert response.status_code == 200

    # Response time validation
    assert response.elapsed.total_seconds() < 2

    # JSON structure validation
    data = response.json()
    assert isinstance(data, list)
    assert len(data) > 0
    assert "id" in data[0]
    assert "email" in data[0]

def test_create_user():
    payload = {"name": "Test User", "email": "test@example.com"}
    headers = {"Authorization": "Bearer token123"}

    response = requests.post(
        f"{BASE_URL}/users",
        json=payload,
        headers=headers
    )

    assert response.status_code == 201
    assert response.json()["name"] == "Test User"

Q15: How do you handle authentication in API tests?

Answer: Depends on the auth type. Use fixtures for token management and session objects for cookies. Store credentials securely (environment variables, not in code).

import os

@pytest.fixture(scope="session")
def auth_token():
    """Get authentication token"""
    response = requests.post(
        f"{BASE_URL}/auth/login",
        json={
            "email": os.environ["TEST_USER"],
            "password": os.environ["TEST_PASSWORD"]
        }
    )
    return response.json()["token"]

@pytest.fixture
def auth_headers(auth_token):
    """Headers with auth token"""
    return {"Authorization": f"Bearer {auth_token}"}

def test_protected_endpoint(auth_headers):
    response = requests.get(
        f"{BASE_URL}/protected",
        headers=auth_headers
    )
    assert response.status_code == 200

Common Coding Challenges

Python coding challenges in automation interviews often involve data processing, string manipulation, and practical automation scenarios.

Challenge 1: Parse and validate test data from CSV

import csv

def parse_test_data(filename):
    """
    Parse test data from CSV, validate emails, return valid rows.
    CSV format: name,email,age
    """
    valid_rows = []

    with open(filename, 'r') as file:
        reader = csv.DictReader(file)
        for row in reader:
            # Validate email
            if '@' in row['email'] and '.' in row['email']:
                # Validate age
                try:
                    age = int(row['age'])
                    if 0 < age < 150:
                        valid_rows.append({
                            'name': row['name'].strip(),
                            'email': row['email'].lower(),
                            'age': age
                        })
                except ValueError:
                    continue

    return valid_rows

Challenge 2: Implement a retry decorator with exponential backoff

import time
from functools import wraps

def retry_with_backoff(max_attempts=3, base_delay=1):
    """
    Retry decorator with exponential backoff.
    Delay doubles after each failed attempt.
    """
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            delay = base_delay
            last_exception = None

            for attempt in range(max_attempts):
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    last_exception = e
                    if attempt < max_attempts - 1:
                        print(f"Attempt {attempt + 1} failed. Retrying in {delay}s...")
                        time.sleep(delay)
                        delay *= 2  # Exponential backoff

            raise last_exception
        return wrapper
    return decorator

@retry_with_backoff(max_attempts=3, base_delay=1)
def unreliable_api_call():
    # Simulates flaky API
    pass

Challenge 3: Find duplicate test case names in a list

def find_duplicate_tests(test_names):
    """
    Find and return duplicate test case names.
    Input: ["test_login", "test_signup", "test_login", "test_checkout"]
    Output: ["test_login"]
    """
    seen = set()
    duplicates = set()

    for name in test_names:
        if name in seen:
            duplicates.add(name)
        seen.add(name)

    return list(duplicates)

# Alternative using Counter
from collections import Counter

def find_duplicate_tests_v2(test_names):
    counts = Counter(test_names)
    return [name for name, count in counts.items() if count > 1]

Portfolio Projects to Build

Python automation projects demonstrate practical skills to employers. Build these projects and host them on GitHub with clear documentation.

Project 1: E-Commerce Web Automation Framework

Build a complete test automation framework for an e-commerce site using Page Object Model.

  • Selenium/Playwright with Python
  • pytest with fixtures and markers
  • Page Object Model pattern
  • Test data from JSON/CSV
  • HTML reports with screenshots
  • GitHub Actions CI/CD pipeline

Project 2: REST API Test Suite

Comprehensive API testing suite for a public API (like JSONPlaceholder or ReqRes).

  • requests library with pytest
  • CRUD operations testing
  • Authentication testing
  • Response schema validation
  • Performance assertions
  • Environment-based configuration

Project 3: Data Processing Automation

Automated data pipeline for processing and reporting.

  • pandas for data manipulation
  • Excel report generation with openpyxl
  • Email automation for report delivery
  • Scheduled execution with cron/Task Scheduler
  • Error handling and logging

Project 4: Web Scraping with Data Analysis

Scrape data from websites and perform analysis.

  • BeautifulSoup or Scrapy for scraping
  • Data cleaning with pandas
  • Visualization with matplotlib
  • Database storage (SQLite/PostgreSQL)
  • Respect robots.txt and rate limiting

GitHub Tips: Write clear README files with setup instructions, include requirements.txt, add badges for test status, and include sample output screenshots. Canadian employers often review GitHub profiles before interviews.

Behavioral Interview Questions

Behavioral questions assess your soft skills and team fit. Use the STAR method (Situation, Task, Action, Result) to structure answers.

"Describe a challenging automation project you worked on."

How to answer: Describe the technical challenge (flaky tests, complex locators, legacy system). Explain your approach (research, proof of concept, implementation). Quantify the result ("reduced test execution time by 40%", "increased test coverage from 30% to 80%").

"How do you handle flaky tests?"

How to answer: First, identify the root cause (timing issues, test data, environment). Solutions include: explicit waits, test isolation, retry mechanisms, better locators. Mention monitoring and reporting flaky tests to track improvement.

"How do you prioritize what to automate?"

How to answer: Prioritize based on: frequency of execution, business criticality, stability of feature, time savings vs automation effort. Start with smoke tests and high-value regression tests. Avoid automating constantly changing features or one-time tests.

"Tell me about a time you disagreed with a team member."

How to answer: Focus on professional disagreement (technical approach, tool selection). Show you listened to their perspective, presented data/evidence for your view, and reached a collaborative solution. Emphasize the positive outcome and what you learned.

Canada Job Market Tips for 2026

The Python automation job market in Canada is strong, with particular demand in Toronto, Vancouver, and Montreal. Here's what you need to know:

Salary Expectations by City

City Junior (0-2 yrs) Mid (2-5 yrs) Senior (5+ yrs)
Toronto $65-80K $80-110K $110-140K
Vancouver $60-75K $75-105K $105-135K
Montreal $55-70K $70-95K $95-120K
Calgary/Ottawa $55-70K $70-100K $100-130K

Top Hiring Industries in Canada

Job Search Strategy

Interview Day Checklist

Be prepared on interview day with this checklist:

Before the Interview

  • Review the job description and company's tech stack
  • Prepare your development environment (IDE, Python, packages)
  • Test your camera, microphone, and internet (for virtual interviews)
  • Have your portfolio projects ready to demonstrate
  • Prepare 3-5 questions to ask the interviewer

During the Interview

  • Think out loud when solving problems—interviewers want to see your thought process
  • Ask clarifying questions before diving into code
  • Start with a simple solution, then optimize
  • Test your code with edge cases
  • Be honest if you don't know something—show how you'd find the answer

Questions to Ask

  • "What does the current test automation coverage look like?"
  • "What automation tools and frameworks does the team use?"
  • "How does QA collaborate with development teams?"
  • "What are the biggest automation challenges you're facing?"
  • "What does career growth look like for this role?"

Frequently Asked Questions

What are the most common Python automation interview questions?

The most common Python automation interview questions include: explaining the difference between lists and tuples, how to handle exceptions in automation scripts, explaining pytest fixtures and markers, how to locate dynamic elements in Selenium, difference between explicit and implicit waits, how to implement Page Object Model (POM), explaining Python decorators, and how to handle API testing with requests library. Interviewers also ask about virtual environments, data structures, and real-world automation scenarios.

How long should I prepare for a Python automation interview?

For a Python automation interview, plan 2-4 weeks of focused preparation. Spend the first week reviewing Python fundamentals and data structures. The second week should focus on automation frameworks (pytest, Selenium). The third week, build 2-3 portfolio projects. The final week, practice coding challenges and mock interviews. If you're a beginner, allow 6-8 weeks for comprehensive preparation.

What projects should I build for a Python automation interview portfolio?

For a strong Python automation portfolio, build: 1) A web automation project using Selenium/Playwright with Page Object Model, 2) An API testing suite using pytest and requests library, 3) A data automation project with pandas for Excel/CSV processing, 4) A file automation script for batch processing. Host all projects on GitHub with clear README files, documentation, and test coverage. Canadian employers in Toronto, Vancouver, and Montreal value practical, well-documented projects.

What Python automation frameworks should I know for interviews?

For Python automation interviews, you should know: pytest (most popular testing framework with fixtures, markers, and plugins), Selenium WebDriver (browser automation), Playwright (modern alternative to Selenium), requests/httpx (API testing), unittest (built-in Python testing), Robot Framework (keyword-driven testing), and BeautifulSoup (web scraping). Also know supporting tools like pytest-html for reporting, pytest-xdist for parallel execution, and Docker for containerized testing.

What is the average salary for Python automation engineers in Canada?

Python automation engineer salaries in Canada vary by city and experience. In Toronto, salaries range from $75,000-$130,000 CAD. Vancouver offers $70,000-$125,000 CAD. Montreal ranges from $65,000-$110,000 CAD. Senior roles and those with DevOps or ML skills can earn $140,000+ CAD. Contract rates typically range from $50-$85/hour CAD depending on experience and specialization.

How do I answer behavioral questions in a Python automation interview?

Use the STAR method (Situation, Task, Action, Result) for behavioral questions. Common questions include: describing a challenging automation project, how you handled flaky tests, how you prioritized test coverage, and how you collaborated with developers. Prepare specific examples from past projects, quantify your impact (e.g., "reduced test execution time by 40%"), and demonstrate problem-solving and communication skills.

Ready to Ace Your Python Automation Interview?

Build the skills employers are looking for with hands-on Python automation training. Practice with real projects and get job-ready.

Start Learning Now - $99 CAD Try Free Lesson

Related Articles

Python Career Paths in Canada

Explore automation, data science, and web dev careers

Python Automation Projects

15+ real-world projects for your portfolio

Selenium Python Tutorial

Complete web automation guide for 2026