Python Basics


Python Basics Interview with follow-up questions

1. What are the key features of Python?

Python is a high-level, general-purpose language whose appeal comes from a combination of design choices rather than any single feature. The points interviewers want to hear:

  1. Readable, indentation-based syntax: Whitespace is part of the grammar, which enforces a consistent visual structure and keeps code clean.

  2. Interpreted and dynamically typed: Code runs without a separate compile step, and types are checked at runtime. In professional 2026 code you still annotate with type hints (list[int], int | str) and run a static checker like mypy or pyright — Python stays dynamically typed at runtime but is statically checked in CI.

  3. "Batteries included" standard library plus PyPI: A large stdlib (pathlib, itertools, asyncio, dataclasses) backed by the huge PyPI ecosystem.

  4. Multi-paradigm: Supports procedural, object-oriented, and functional styles. Everything is an object, including functions and classes.

  5. Automatic memory management: Reference counting plus a cyclic garbage collector; no manual free.

  6. Portable and embeddable: The same code runs across platforms; CPython is the reference implementation (others include PyPy).

Common follow-up — "and the downsides?" Be ready: the GIL historically limited CPU-bound threading, though Python 3.14 now ships an officially supported free-threaded (no-GIL) build (PEP 779) and an experimental JIT (PEP 744); raw execution is slower than C/Rust; and dynamic typing pushes some errors to runtime, which is why type hints and CI matter.

↑ Back to top

Follow-up 1

How does Python's simplicity benefit developers?

Python's simplicity benefits developers in several ways:

  1. Easy to Learn: Python has a clean and straightforward syntax, making it easier for beginners to grasp the basics of programming.

  2. Rapid Development: Python's simplicity allows developers to write code quickly, reducing development time and increasing productivity.

  3. Readability: Python emphasizes code readability, making it easier for developers to understand and maintain their code.

  4. Reduced Debugging Time: Python's simplicity and readability help in identifying and fixing bugs more quickly, reducing the time spent on debugging.

  5. Code Reusability: Python's simplicity encourages modular programming and code reuse, allowing developers to write reusable code components and libraries.

Follow-up 2

Can you explain how Python is dynamically typed?

In Python, variables are not explicitly declared with a specific type. Instead, the type of a variable is determined at runtime based on the value assigned to it. This is known as dynamic typing.

For example, in Python, you can assign an integer value to a variable and later assign a string value to the same variable without any issues. The type of the variable changes dynamically based on the assigned value.

x = 10
print(type(x))  # Output: 

x = 'Hello'
print(type(x))  # Output: 

Follow-up 3

What is meant by Python being an interpreted language?

Python is an interpreted language, which means that the Python code is executed line by line, without the need for compilation into machine code.

When you run a Python program, the interpreter reads the code line by line, interprets each line, and executes it immediately. This allows for quick prototyping and debugging, as changes to the code can be tested immediately without the need for a separate compilation step.

However, this also means that Python programs can be slower compared to compiled languages like C or Java. To mitigate this, Python provides various optimization techniques and libraries that can be used to improve performance when needed.

2. What are the coding standards in Python?

Coding standards are the agreed conventions that keep a codebase consistent, readable, and reviewable across a team. In Python the baseline is PEP 8 (style), PEP 257 (docstrings), and PEP 484 (type hints). In 2026 interviewers expect you to know that these are enforced by tooling, not memorized by hand:

  • Ruff — a Rust-based linter and formatter that has replaced the old flake8 + black + isort + pyupgrade stack; runs in milliseconds and auto-fixes most issues (ruff check --fix, ruff format).
  • mypy or pyright/ty for static type checking.
  • uv for fast, reproducible environments and dependency locking (replacing pip/virtualenv/poetry for many teams).
  • pyproject.toml as the single config file where Ruff, mypy, pytest, and build settings all live.

Beyond tooling: meaningful names, small focused functions, docstrings on public APIs, type annotations, and these checks wired into pre-commit hooks and CI so nothing merges unformatted or untyped. The point of a standard is that style stops being a code-review topic — the tools settle it automatically.

↑ Back to top

Follow-up 1

What is PEP 8?

PEP 8 is the official style guide for Python code. PEP stands for Python Enhancement Proposal, and PEP 8 provides guidelines on how to format Python code to ensure consistency and readability. It covers topics such as indentation, line length, naming conventions, comments, and more.

Follow-up 2

Why is it important to follow coding standards?

Following coding standards is important for several reasons:

  1. Readability: Consistent code formatting and naming conventions make it easier for developers to read and understand the code.

  2. Maintainability: Well-structured and standardized code is easier to maintain and update, reducing the chances of introducing bugs or errors.

  3. Collaboration: When multiple developers work on a project, following coding standards ensures that everyone can understand and work with each other's code more effectively.

  4. Code Quality: Following coding standards helps improve the overall quality of the codebase, making it more robust, efficient, and reliable.

Follow-up 3

Can you give an example of a PEP 8 guideline?

Sure! One example of a PEP 8 guideline is the maximum line length. PEP 8 recommends limiting lines of code to a maximum of 79 characters. This guideline helps improve code readability by preventing excessively long lines that can be difficult to read and understand. Here's an example:

# Bad example (line exceeds maximum length)
long_variable_name = some_function_call_with_long_arguments(argument1, argument2, argument3, argument4, argument5, argument6, argument7, argument8, argument9, argument10)

# Good example (line within maximum length)
long_variable_name = some_function_call_with_long_arguments(
    argument1, argument2, argument3, argument4, argument5, argument6, argument7, argument8, argument9, argument10
)

3. What are the differences between Python 2 and Python 3?

This is now a historical question: Python 2 reached end of life on January 1, 2020 and receives no fixes or security patches. Python 3 (currently 3.14) is the only supported Python — frame any "Py2 vs Py3" answer as "why the migration happened," not as a live choice.

The key differences that drove the split:

  1. Print: print was a statement in Py2 (print x); in Py3 it's a function — print(x) — which composes properly with sep=, end=, and file=.

  2. Division: In Py2 5 / 2 did integer division (2); in Py3 / is always true division (2.5), and // is the explicit floor-division operator.

  3. Strings and Unicode: Py3 made str Unicode by default and split out bytes for raw binary, ending the Py2 str/unicode confusion. This is the change that broke the most code on migration.

  4. Iterators by default: range, dict.keys(), map, zip, etc. return lazy views/iterators in Py3 instead of building full lists.

  5. Exception syntax: except E as err: replaced Py2's except E, err:.

Common follow-up — "how would you handle a legacy Py2 codebase today?" You don't keep it on Py2: run a tool like pyupgrade/Ruff and 2to3-style fixes, get it onto a supported 3.x, then add type hints and tests. There is no supported path that leaves it on Python 2.

↑ Back to top

Follow-up 1

Why was Python 3 introduced?

Python 3 was introduced to address some of the limitations and design flaws of Python 2. The main goals of Python 3 were to improve the language's consistency, remove redundant features, and make it more efficient and easier to use. Some of the specific reasons for introducing Python 3 include:

  1. Unicode Support: Python 3 introduced better support for Unicode, making it easier to work with different character sets and languages.

  2. Improved Syntax: Python 3 introduced several syntax improvements, such as the use of parentheses for print statements, the use of 'as' keyword for exception handling, and the removal of the '<>=' comparison operator.

  3. Removal of Deprecated Features: Python 3 removed several deprecated features from Python 2, making the language cleaner and more streamlined.

Overall, Python 3 was introduced to modernize the language and provide a better foundation for future development.

Follow-up 2

Can Python 2 code run on Python 3 without modifications?

No, Python 2 code cannot run on Python 3 without modifications. Python 3 introduced several backward-incompatible changes, which means that code written for Python 2 may not work correctly in Python 3 without making some modifications. Some of the key differences that can cause compatibility issues include:

  1. Print Statement: In Python 2, the print statement is used as 'print '. In Python 3, print is a function and is used as 'print()'.

  2. Division Operator: In Python 2, the division operator (/) performs integer division if both operands are integers. In Python 3, the division operator always performs floating-point division.

  3. Unicode Support: Python 2 uses ASCII by default, while Python 3 uses Unicode by default. This means that Python 3 can handle a wider range of characters and may require changes in string handling.

To run Python 2 code on Python 3, it is recommended to use a tool like '2to3' to automatically convert the code to Python 3 syntax.

Follow-up 3

What are some key features introduced in Python 3?

Python 3 introduced several key features and improvements over Python 2. Some of the notable features introduced in Python 3 include:

  1. Print Function: In Python 3, the print statement was replaced with a print function, which provides more flexibility and consistency.

  2. Unicode Support: Python 3 uses Unicode by default, making it easier to work with different character sets and languages.

  3. Improved Division Operator: In Python 3, the division operator (/) always performs floating-point division, making it more intuitive and consistent.

  4. Syntax Improvements: Python 3 introduced several syntax improvements, such as the use of parentheses for print statements, the use of 'as' keyword for exception handling, and the removal of the '<>=' comparison operator.

  5. Extended Iterable Unpacking: Python 3 introduced the ability to unpack iterables with a variable number of elements, making it easier to work with data structures.

These are just a few of the key features introduced in Python 3. There are many more improvements and additions in the language.

4. What are Python data types?

Python's built-in types, grouped the way interviewers expect:

  • Numbers: int (arbitrary precision — no overflow), float (double-precision), complex, and bool (a subclass of int).
  • Sequences: str (immutable Unicode text), list (mutable, ordered), tuple (immutable, ordered), range (lazy integer sequence), and bytes/bytearray for raw binary.
  • Mappings: dict — key/value pairs, insertion-ordered since 3.7.
  • Sets: set (mutable) and frozenset (immutable), both holding unique, hashable items.
  • NoneType: the single value None.
count: int = 42
price: float = 9.99
name: str = "Ada"
items: list[int] = [1, 2, 3]
point: tuple[int, int] = (3, 4)
config: dict[str, int] = {"port": 8080}

The follow-up that matters: mutability. list, dict, set, and bytearray are mutable; int, float, str, tuple, frozenset, and bytes are immutable. Everything is an object, and a variable is just a name bound to one — so b = a makes b point at the same object, not a copy. Only hashable (typically immutable) objects can be dict keys or set members. Use type(x) or isinstance(x, ...) to check a type at runtime.

↑ Back to top

Follow-up 1

What is the difference between a list and a tuple?

The main difference between a list and a tuple in Python is that a list is mutable, meaning its elements can be modified, added, or removed, while a tuple is immutable, meaning its elements cannot be modified after creation. Here is an example:

# List example
my_list = [1, 2, 3]
my_list.append(4)
print(my_list)  # Output: [1, 2, 3, 4]

# Tuple example
my_tuple = (1, 2, 3)
# my_tuple.append(4)  # This will raise an error
print(my_tuple)  # Output: (1, 2, 3)

Follow-up 2

How do you use dictionaries in Python?

In Python, dictionaries are used to store key-value pairs. You can create a dictionary using curly braces {} or the dict() constructor. Here is an example:

# Dictionary example
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}

# Accessing values
print(my_dict['name'])  # Output: 'John'

# Modifying values
my_dict['age'] = 26
print(my_dict)  # Output: {'name': 'John', 'age': 26, 'city': 'New York'}

# Adding new key-value pairs
my_dict['occupation'] = 'Engineer'
print(my_dict)  # Output: {'name': 'John', 'age': 26, 'city': 'New York', 'occupation': 'Engineer'}

# Removing key-value pairs
del my_dict['city']
print(my_dict)  # Output: {'name': 'John', 'age': 26, 'occupation': 'Engineer'}

Follow-up 3

Can you give an example of using a set in Python?

In Python, a set is an unordered collection of unique elements. You can create a set using curly braces {} or the set() constructor. Here is an example:

# Set example
my_set = {1, 2, 3, 3, 4, 5}
print(my_set)  # Output: {1, 2, 3, 4, 5}

# Adding elements
my_set.add(6)
print(my_set)  # Output: {1, 2, 3, 4, 5, 6}

# Removing elements
my_set.remove(3)
print(my_set)  # Output: {1, 2, 4, 5, 6}

# Set operations
set1 = {1, 2, 3}
set2 = {3, 4, 5}

print(set1.union(set2))  # Output: {1, 2, 3, 4, 5}
print(set1.intersection(set2))  # Output: {3}
print(set1.difference(set2))  # Output: {1, 2}

5. How do you define and use functions in Python?

Functions are defined with def, followed by the name, a parameter list, and an indented body. In professional 2026 code you annotate parameters and the return type, and you call the function by name with arguments in parentheses:

def add_numbers(a: int, b: int) -&gt; int:
    """Return the sum of two integers."""
    return a + b

result = add_numbers(3, 5)
print(result)  # 8

Things an interviewer will probe:

  • Arguments: positional or keyword (add_numbers(b=5, a=3)), with defaults (def f(x, y=0)), variadic *args/**kwargs, and / or * markers to force positional-only or keyword-only parameters.
  • The mutable-default gotcha: def f(items=[]) reuses one shared list across calls. Use None as the sentinel and create the value inside:
def append_to(item: int, items: list[int] | None = None) -&gt; list[int]:
    if items is None:
        items = []
    items.append(item)
    return items
  • Functions are first-class objects: they can be passed around, returned, nested, and stored in data structures — the basis for closures and decorators.

A function with no explicit return returns None.

↑ Back to top

Follow-up 1

What is a lambda function?

A lambda function, also known as an anonymous function, is a small, single-expression function that doesn't require a name. It is defined using the lambda keyword followed by a set of parameters and a colon, followed by the expression to be evaluated. Lambda functions are often used when a small function is needed for a short period of time and it doesn't make sense to define a separate named function. Here is an example of a lambda function that adds two numbers:

add_numbers = lambda a, b: a + b
result = add_numbers(3, 5)
print(result)  # Output: 8

Lambda functions can be used wherever function objects are required.

Follow-up 2

Can you give an example of a generator function?

A generator function is a special type of function that returns an iterator, which can be used to iterate over a sequence of values. Generator functions are defined using the def keyword followed by the function name and a set of parentheses containing any parameters. The function body uses the yield keyword to yield a value, which can be accessed using the next() function or a for loop. Here is an example of a generator function that generates the Fibonacci sequence:

# Generator function

def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

# Using the generator function

fib = fibonacci()

print(next(fib))  # Output: 0
print(next(fib))  # Output: 1
print(next(fib))  # Output: 1
print(next(fib))  # Output: 2

for num in fib:
    if num &gt; 100:
        break
    print(num)

Generator functions are memory efficient as they generate values on the fly instead of storing them in memory.

Follow-up 3

What is a decorator and how is it used in Python?

In Python, a decorator is a design pattern that allows you to modify the behavior of a function or class without directly modifying its source code. Decorators are defined using the @ symbol followed by the decorator function name, which is placed above the function or class definition. When the decorated function or class is called, the decorator function is executed first, allowing you to perform additional actions or modify the behavior of the decorated function or class. Here is an example of a decorator that logs the execution time of a function:

import time

# Decorator function

def log_execution_time(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        execution_time = end_time - start_time
        print(f"Execution time: {execution_time} seconds")
        return result
    return wrapper

# Using the decorator

@log_execution_time

def calculate_sum(a, b):
    time.sleep(1)
    return a + b

result = calculate_sum(3, 5)
print(result)  # Output: 8

Decorators are a powerful feature in Python that allow you to add functionality to existing functions or classes without modifying their source code.

Live mock interview

Mock interview: Python Basics

Intermediate ~5 min Your own free AI key

Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.