0% found this document useful (0 votes)
6 views10 pages

Python Developer Interview QA

The document outlines a job description for a Python Developer, including 47 interview questions and answers covering fundamental Python concepts such as variables, data types, functions, object-oriented programming, and database connectivity. It also discusses advanced topics like REST APIs, HTTP methods, and JSON. The content serves as a comprehensive guide for assessing Python programming knowledge in interviews.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views10 pages

Python Developer Interview QA

The document outlines a job description for a Python Developer, including 47 interview questions and answers covering fundamental Python concepts such as variables, data types, functions, object-oriented programming, and database connectivity. It also discusses advanced topics like REST APIs, HTTP methods, and JSON. The content serves as a comprehensive guide for assessing Python programming knowledge in interviews.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JD for Python Developer

Interview Questions & Answers — All 47 Questions

1. Explain Python basic constructs such as variables, data types, and operators.
Variables are named containers that store data values. Python supports multiple data types including
integers (int), floating-point numbers (float), strings (str), booleans (bool), lists, tuples, sets, and
dictionaries. Variables are dynamically typed — no need to declare a type explicitly. Operators include
arithmetic (+, -, *, /, //, %, **), comparison (==, !=, >, <, >=, <=), logical (and, or, not), assignment (=, +=,
-=), and bitwise operators.

2. What is structural pattern matching in Python? Give an example.


Introduced in Python 3.10, structural pattern matching uses the match-case statement to compare a
value against a series of patterns. It is similar to switch-case in other languages but more powerful.
Example:
match command:
case 'quit': quit_game()
case 'go north': move('north')
case _: print('Unknown command')

3. How do you accept user input in Python? What is the role of the eval() function?
User input is accepted using the input() function, which always returns a string. To convert it to another
type, explicit casting is used (e.g., int(input())). The eval() function evaluates a string as a Python
expression and returns the result. For example, eval('2 + 3') returns 5. However, eval() is considered
unsafe when used with untrusted input, as it can execute arbitrary code.

4. Define user-defined functions in Python.


User-defined functions are blocks of reusable code created using the def keyword. They allow you to
structure programs and avoid repetition.
Syntax:
def function_name(parameters):
# body
return value
Functions can have default arguments, keyword arguments, *args (variable positional), and **kwargs
(variable keyword arguments). They can return single or multiple values.

5. Explain different types of function arguments in Python.


Python supports five types of function arguments:
1. Positional arguments — passed in order (def f(a, b)).
2. Keyword arguments — passed by name (f(a=1, b=2)).
3. Default arguments — have a preset value (def f(a, b=10)).
4. *args — accepts any number of positional arguments as a tuple.
5. **kwargs — accepts any number of keyword arguments as a dictionary.

6. What is the difference between local and global variables?


A local variable is declared inside a function and is accessible only within that function. It is created
when the function is called and destroyed when it returns. A global variable is declared outside all
functions and is accessible throughout the entire program. To modify a global variable inside a function,
the global keyword must be used.

7. Explain the use of the global and nonlocal keywords.


global: Used inside a function to indicate that a variable refers to the globally scoped variable, not a local
one. Without it, assigning to a variable inside a function creates a new local variable.
nonlocal: Used in nested functions to refer to a variable in the nearest enclosing (but non-global) scope.
This allows inner functions to modify variables defined in outer functions.

8. What are lambda functions? When would you use them?


Lambda functions are anonymous, single-expression functions defined using the lambda keyword.
Syntax: lambda arguments: expression. They are typically used for short, throwaway functions —
particularly as arguments to higher-order functions like map(), filter(), and sorted().
Example: square = lambda x: x ** 2
Use case: sorted(data, key=lambda x: x['age'])

9. List some commonly used built-in Python functions.


print(), input(), len(), range(), type(), int(), float(), str(), list(), tuple(), dict(), set(), sum(), min(), max(),
abs(), round(), sorted(), reversed(), enumerate(), zip(), map(), filter(), open(), isinstance(), id(), dir()

10. Explain Python modules and their advantages.


A module is a file containing Python code (functions, classes, variables) that can be imported into other
scripts using import. Advantages include code reusability (write once, use many times), better
organisation (split large programs into manageable files), namespace separation (avoids naming
conflicts), and access to the Python Standard Library and third-party packages.

11. Differentiate between list, tuple, and dictionary.


List: Ordered, mutable, allows duplicates. Defined with []. Example: [1, 2, 3].
Tuple: Ordered, immutable, allows duplicates. Defined with (). Example: (1, 2, 3).
Dictionary: Unordered (insertion-ordered from Python 3.7+), mutable, stores key-value pairs, keys must
be unique. Defined with {}. Example: {'name': 'Alice', 'age': 25}.

12. How are lists mutable but tuples immutable?


Lists are mutable because their elements can be changed, added, or removed after creation (e.g., list[0]
= 10). Tuples are immutable because once created, their elements cannot be modified. This makes
tuples faster and suitable for use as dictionary keys or in situations where data should not change.
Internally, Python stores tuple data in a fixed-size block, whereas lists use a dynamic array.

13. Explain dictionary keys and values with an example.


In a dictionary, each entry is a key-value pair. Keys must be unique and immutable (strings, numbers,
tuples), while values can be of any type.
Example:
student = {'name': 'Ravi', 'age': 21, 'grade': 'A'}
student['name'] # Returns 'Ravi'
[Link]() # Returns dict_keys(['name', 'age', 'grade'])
[Link]() # Returns dict_values(['Ravi', 21, 'A'])

14. What are core object-oriented concepts in Python?


The four core OOP concepts are:
1. Encapsulation — bundling data and methods together, restricting direct access.
2. Inheritance — a class inheriting attributes and methods from a parent class.
3. Polymorphism — the same method name behaving differently in different classes.
4. Abstraction — hiding implementation details and exposing only necessary interfaces. Python also
supports multiple inheritance.

15. Explain public, protected, and private attributes in Python.


Public attributes: Accessible from anywhere. No underscore prefix. Example: [Link].
Protected attributes: Indicated by a single underscore (_). Accessible within the class and subclasses by
convention, but not strictly enforced.
Private attributes: Indicated by double underscore (__). Name-mangled to _ClassName__attr, making
them harder (but not impossible) to access from outside the class.

16. What is the difference between class variables and instance variables?
Class variables are shared across all instances of a class. They are defined inside the class body but
outside any method. Instance variables are unique to each object and are typically defined inside
__init__ using self. Changing a class variable affects all instances (unless overridden), while changing
an instance variable only affects that specific object.

17. Explain the constructor and destructor in Python.


__init__() is the constructor — it is automatically called when a new object is created. It initialises the
object's attributes.
__del__() is the destructor — it is called when the object is about to be destroyed (garbage collected). It
can be used to release resources, though relying on it is not recommended due to Python's garbage
collection behaviour.

18. What is inheritance? Explain its types.


Inheritance allows a child class to acquire properties and methods of a parent class, promoting reuse.
Types:
1. Single — one child, one parent.
2. Multiple — one child, multiple parents.
3. Multilevel — chain: A → B → C.
4. Hierarchical — one parent, multiple children.
5. Hybrid — combination of multiple types.
Python uses the Method Resolution Order (MRO) to resolve method lookup in complex hierarchies.

19. What is Method Resolution Order (MRO)?


MRO defines the order in which Python searches for a method or attribute in a class hierarchy. Python
uses the C3 Linearisation algorithm to compute MRO. You can view the MRO of a class using
ClassName.__mro__ or [Link](). This is especially relevant in multiple inheritance to avoid the
diamond problem and ensure predictable method lookup.

20. Differentiate between method overloading and method overriding.


Method Overloading: Defining multiple methods with the same name but different parameters. Python
does not support true overloading natively — the last definition replaces earlier ones. It can be simulated
using default arguments or *args.
Method Overriding: A child class redefines a method from the parent class with the same name and
signature, replacing the parent's implementation. Used in polymorphism.

21. Explain getter and setter methods in Python.


Getters and setters are used to access and modify private attributes in a controlled way.
In Python, this is best achieved using the @property decorator:
@property
def name(self): return self._name
@[Link]
def name(self, value): self._name = value
This keeps the interface clean while allowing validation or logic inside the setter.

22. How do you use collections within object-oriented programming?


Collections (lists, dicts, sets) are commonly used as instance or class attributes in OOP. For example, a
class School might store a list of Student objects. You can iterate over them, pass them between
methods, or use them to model one-to-many relationships. Python's collections module also provides
specialised types like defaultdict, OrderedDict, Counter, deque, and namedtuple.

23. What are advanced collections in Python?


The collections module provides:
- namedtuple: Tuple subclass with named fields.
- deque: Double-ended queue, efficient for appends/pops at both ends.
- Counter: Counts hashable objects; ideal for frequency analysis.
- defaultdict: Dictionary with a default value for missing keys.
- OrderedDict: Maintains insertion order (less critical in Python 3.7+ but still useful for explicit ordering or
move_to_end()).
- ChainMap: Groups multiple dicts into one view.
24. Name some important Python modules and libraries.
Standard Library: os, sys, math, datetime, re, json, csv, collections, itertools, functools, threading,
subprocess.
Data Science: numpy, pandas, matplotlib, scipy.
Web: requests, flask, django, fastapi.
Database: sqlite3, sqlalchemy.
Testing: unittest, pytest.
Machine Learning: scikit-learn, tensorflow, pytorch.

25. Explain regular expressions and their use cases.


Regular expressions (regex) are patterns used to match, search, and manipulate strings. Python's re
module provides functions like [Link](), [Link](), [Link](), [Link](), and [Link]().
Common patterns: \d (digit), \w (word char), \s (whitespace), . (any char), * (0+), + (1+), ? (0 or 1), ^
(start), $ (end).
Use cases: input validation (email, phone), text extraction, find-and-replace, log parsing.

26. How do you perform file handling in Python?


Files are opened using open(filename, mode). Modes include 'r' (read), 'w' (write, overwrites), 'a'
(append), 'b' (binary), 'x' (create).
Best practice uses a context manager:
with open('[Link]', 'r') as f:
content = [Link]()
Other methods: readline(), readlines(), write(), writelines(). Always use with to ensure the file is properly
closed, even if an error occurs.

27. What are generators? How are they different from functions?
Generators are functions that yield values one at a time using the yield keyword instead of returning all
at once. They are lazy — they produce values on demand, saving memory.
Differences from regular functions:
- Regular functions return once and terminate; generators can pause and resume.
- Generators produce an iterator automatically.
- Memory-efficient for large sequences.
Example: def count_up(n): for i in range(n): yield i

28. Explain list, dictionary, and set comprehensions.


Comprehensions provide a concise way to create collections.
List: [x*2 for x in range(5)] → [0, 2, 4, 6, 8]
Dict: {k: v for k, v in zip('abc', [1,2,3])} → {'a':1,'b':2,'c':3}
Set: {x**2 for x in range(5)} → {0, 1, 4, 9, 16}
Generator: (x**2 for x in range(5)) — produces values lazily.
All support optional if conditions for filtering.
29. What is Python database connectivity?
Python can connect to databases using DB-API 2.0 compliant modules. For SQLite, Python's built-in
sqlite3 module is used. For MySQL, use mysql-connector-python or PyMySQL. For PostgreSQL, use
psycopg2. The general workflow is: connect → create cursor → execute SQL → commit/fetch → close.
SQLAlchemy provides a higher-level ORM layer abstracting raw SQL.

30. How do you insert and update records using Python database connectivity?
Insert:
[Link]('INSERT INTO users (name, age) VALUES (?, ?)', ('Alice', 30))
[Link]()
Update:
[Link]('UPDATE users SET age = ? WHERE name = ?', (31, 'Alice'))
[Link]()
Always use parameterised queries (? placeholders) to prevent SQL injection. [Link]() saves
changes permanently.

31. How do you retrieve data using SELECT queries?


[Link]('SELECT * FROM users')
rows = [Link]() # All rows as list of tuples
row = [Link]() # Single row
Iterate results:
for row in [Link]():
print(row)
You can also use [Link] to get column names. Parameterised queries:
[Link]('SELECT * FROM users WHERE age > ?', (25,))

32. Explain exception handling during database operations.


Database operations should be wrapped in try-except-finally blocks:
try:
conn = [Link]('[Link]')
cursor = [Link]()
[Link](...)
[Link]()
except [Link] as e:
print('Error:', e)
[Link]()
finally:
[Link]()
rollback() undoes uncommitted changes. The finally block ensures the connection is always closed.
33. What is a REST API?
REST (Representational State Transfer) is an architectural style for designing networked APIs. A REST
API allows communication between a client and server over HTTP using standard methods. Key
principles: stateless communication, resource-based URLs, use of standard HTTP methods (GET,
POST, PUT, DELETE, PATCH), and responses typically in JSON or XML format. REST APIs are widely
used for web and mobile application backends.

34. Explain the client-server model.


In the client-server model, the client (e.g., a web browser or mobile app) sends requests to a server,
which processes them and returns responses. The client and server are separate entities
communicating over a network (usually HTTP/HTTPS). The server hosts resources and business logic;
the client handles presentation. This separation allows independent scaling, development, and
deployment of both sides.

35. What is an HTTP request and an HTTP response?


An HTTP request is sent by the client to request a resource or action. It consists of a method (GET,
POST, etc.), a URL, headers (metadata like Content-Type, Authorization), and optionally a body (for
POST/PUT).
An HTTP response is the server's reply. It includes a status code (200 OK, 404 Not Found, 500 Internal
Server Error), headers, and a response body (usually JSON or HTML).

36. Name common HTTP methods and explain GET vs POST.


Common methods: GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS.
GET: Retrieves data from the server. Parameters are passed in the URL query string. It is idempotent
(repeated calls give same result) and should not modify server state.
POST: Sends data to the server (e.g., form submission, creating a resource). Data is in the request
body, not the URL. Not idempotent — each call may create a new resource.

37. What is an endpoint in a REST API?


An endpoint is a specific URL path where a REST API resource is accessible. It combines a base URL
with a resource path and defines what action is performed based on the HTTP method.
Example:
GET /api/users → List all users
POST /api/users → Create a new user
GET /api/users/1 → Get user with ID 1
PUT /api/users/1 → Update user with ID 1
DELETE /api/users/1 → Delete user with ID 1

38. What is JSON and why is it used in REST APIs?


JSON (JavaScript Object Notation) is a lightweight, human-readable data interchange format. It
represents data as key-value pairs (objects) and ordered lists (arrays). It is used in REST APIs because
it is language-agnostic, easy to parse and generate in almost every programming language, compact
compared to XML, natively supported in JavaScript, and easily readable by both humans and machines.
39. Explain the structure of a JSON object.
A JSON object is enclosed in curly braces {} and contains key-value pairs separated by commas. Keys
must be strings in double quotes; values can be strings, numbers, booleans, null, arrays, or nested
objects.
Example:
{
"name": "Alice",
"age": 25,
"skills": ["Python", "SQL"],
"active": true
}

40. What is the difference between JSON and a Dictionary in Python?


Both represent key-value pairs, but they differ:
- JSON is a text-based data format (a string); a Python dict is an in-memory data structure.
- JSON keys must be strings; Python dict keys can be any hashable type.
- JSON has limited types (string, number, bool, null, object, array); Python dicts can hold any object.
- Conversion: [Link](dict) → JSON string; [Link](json_string) → Python dict.

41. How do you read JSON data in Python?


Using the built-in json module:
From a string:
import json
data = [Link]('{"name": "Alice"}')
print(data['name']) # Alice
From a file:
with open('[Link]') as f:
data = [Link](f)
To write JSON:
[Link](data) # To string
[Link](data, file) # To file
dumps() supports indent parameter for pretty-printing.

42. What are the advantages of JSON over XML?


1. More concise and readable — less verbose than XML tags.
2. Faster to parse — JSON parsers are generally quicker.
3. Native support in JavaScript — no extra parsing needed in browsers.
4. Simpler data types — maps naturally to Python dicts and lists.
5. Smaller payload size — reduces bandwidth usage.
6. Easier to work with in most modern programming languages.
7. Better suited for REST APIs and web services.

43. What is XML?


XML (eXtensible Markup Language) is a markup language designed to store and transport data in a
structured, human-readable format. It uses custom tags to define elements and their hierarchy. Unlike
HTML (which defines how data is displayed), XML focuses on describing what the data is. XML
documents have a tree structure and can be validated against a schema (DTD or XSD). It is still widely
used in enterprise systems, SOAP APIs, and configuration files.

44. Explain basic XML elements, tags, and attributes.


Element: The basic unit of XML, consisting of an opening tag, content, and closing tag. Example:
<name>Alice</name>
Tag: The labels wrapping content. Opening: <tag>, Closing: </tag>, Self-closing: <tag/>
Attribute: Additional info inside the opening tag. Example: <user id='1' role='admin'>
Root element: Every XML document must have a single root element enclosing all others.
Nesting: Elements can be nested to represent hierarchical data.

45. What is the difference between XML and JSON?


XML: Tag-based, verbose, supports attributes and namespaces, better for document-oriented data, has
schema validation (XSD), supports comments.
JSON: Key-value pairs, concise, no attributes, better for data exchange in APIs, no native schema
(though JSON Schema exists), no comments.
XML is heavier but more expressive; JSON is lighter and preferred for modern web APIs. XML is
favoured in SOAP, config files, and legacy enterprise systems.

46. How do you parse XML data in Python?


Python's [Link] module is used:
import [Link] as ET
tree = [Link]('[Link]')
root = [Link]()
for child in root:
print([Link], [Link], [Link])
From a string:
root = [Link](xml_string)
For complex XML, lxml library offers more features including XPath support and better performance.

47. In what situations would XML still be used?


1. SOAP-based web services — many enterprise and banking APIs still use SOAP/XML.
2. Configuration files — e.g., Maven ([Link]), Android layouts, Spring Framework.
3. Document formats — Microsoft Office formats (DOCX, XLSX) use XML internally.
4. RSS/Atom feeds — web syndication formats.
5. Legacy systems — older enterprise integrations.
6. Data with complex metadata, namespaces, or mixed content models.
7. Situations requiring strict schema validation via XSD.

You might also like