Fundamentals of Python — Interview Questions & Answers

50 essential Python interview questions covering basics, data types, control flow, OOP, file handling, and popular libraries.

Meritshot15 min read
PythonProgrammingInterview QuestionsOOPData Science
Back to Interview Guides

Python Basics & Data Types

1. What is Python?

Python is a high-level, general-purpose programming language known for its clean syntax and readability. It supports multiple programming paradigms including procedural, object-oriented, and functional programming, making it suitable for web development, data science, automation, and more.

2. Is Python an interpreted or compiled language?

Python is primarily an interpreted language, meaning its code is executed line by line at runtime by the Python interpreter rather than being compiled into machine code beforehand. Internally, Python source code is first compiled to bytecode (.pyc files), which is then executed by the Python Virtual Machine (PVM), but this compilation step is handled automatically and transparently.

3. What are the main data types in Python?

Python has several built-in data types including numeric types (int, float, complex), sequence types (str, list, tuple, range), mapping types (dict), set types (set, frozenset), and boolean (bool). Each type serves a specific purpose and has its own set of operations and methods.

4. What is the difference between a list and a tuple?

A list is a mutable, ordered collection of items defined using square brackets, while a tuple is an immutable, ordered collection defined using parentheses. Because tuples are immutable, they are faster than lists and can be used as dictionary keys, whereas lists cannot.

5. What is a dictionary in Python?

A dictionary is an unordered collection of key-value pairs defined using curly braces, where each key must be unique and immutable. Dictionaries provide fast O(1) average-time lookups by key and are commonly used to store related data, configuration settings, and mappings between values.

6. What is the difference between mutable and immutable objects?

Mutable objects can be modified after creation (e.g., lists, dictionaries, sets), while immutable objects cannot be changed once created (e.g., int, float, str, tuple, frozenset). When you modify a mutable object, it changes in place; when you perform an operation on an immutable object, a new object is created.

7. How does type conversion work in Python?

Type conversion in Python can be done explicitly using built-in functions like int(), float(), str(), list(), and tuple(). Python also performs implicit type conversion (coercion) in certain situations, such as automatically converting an int to a float during arithmetic operations involving both types.

8. How do you write comments in Python?

Single-line comments in Python start with the hash symbol (#), and everything after it on that line is ignored by the interpreter. Multi-line comments can be written using triple-quoted strings (''' or """), which are technically string literals but are commonly used as block comments or docstrings.

9. Why is indentation important in Python?

Indentation in Python is not optional; it is used to define the structure and scope of code blocks such as loops, functions, and conditionals. Unlike many other languages that use braces or keywords to delimit blocks, Python relies on consistent indentation (typically four spaces), and incorrect indentation will raise an IndentationError.

10. How do variables work in Python, and what are the naming conventions?

In Python, variables are created the moment you assign a value to a name; there is no need for explicit type declarations because Python is dynamically typed. Variable names should follow snake_case convention, must start with a letter or underscore, and are case-sensitive. Constants are conventionally written in ALL_CAPS.

Control Flow & Functions

11. How do if/elif/else statements work in Python?

The if statement evaluates a condition and executes its block if the condition is True. You can chain multiple conditions using elif (else if) and provide a fallback block with else, which executes when none of the preceding conditions are True.

12. What is the difference between a for loop and a while loop?

A for loop iterates over a sequence (such as a list, string, or range) and executes its block once for each item in that sequence. A while loop repeatedly executes its block as long as a given condition remains True, making it more suitable when the number of iterations is not known in advance.

13. What do break, continue, and pass do?

The break statement immediately exits the innermost loop, the continue statement skips the rest of the current iteration and moves to the next one, and the pass statement does nothing and acts as a placeholder. Pass is often used when a statement is syntactically required but no action is needed, such as in empty function or class definitions.

14. What is the range() function and how is it used?

The range() function generates a sequence of integers and is commonly used in for loops. It accepts up to three arguments — start, stop, and step — and returns a range object that produces numbers lazily, meaning it does not store all values in memory at once.

15. What are list comprehensions?

A list comprehension is a concise way to create a new list by applying an expression to each item in an iterable, optionally filtering items with a condition. For example, [x**2 for x in range(10) if x % 2 == 0] creates a list of squares of even numbers from 0 to 9. They are generally faster and more readable than equivalent for-loop constructions.

16. How do you define a function in Python?

A function is defined using the def keyword, followed by the function name, parentheses with optional parameters, and a colon. The function body is indented below the definition, and the return statement is used to send a value back to the caller; if no return is specified, the function returns None by default.

17. What are *args and **kwargs?

*args allows a function to accept any number of positional arguments, which are collected into a tuple. **kwargs allows a function to accept any number of keyword arguments, which are collected into a dictionary. Together, they make functions flexible enough to handle a variable number of inputs.

18. What is a lambda function?

A lambda function is a small anonymous function defined using the lambda keyword, which can take any number of arguments but can only contain a single expression. For example, square = lambda x: x**2 creates a function that returns the square of its input. Lambda functions are often used as arguments to higher-order functions like map(), filter(), and sorted().

19. What is the difference between return and print in a function?

The return statement sends a value back to the caller and terminates the function, allowing the result to be stored or used in further computations. The print() function outputs text to the console for display purposes only and does not produce a value that can be captured by the calling code (it returns None).

20. What is variable scope in Python, and what are local and global variables?

Scope determines where a variable can be accessed. A local variable is defined inside a function and is accessible only within that function, while a global variable is defined outside all functions and can be accessed throughout the module. To modify a global variable inside a function, you must declare it with the global keyword.

Object-Oriented Programming

21. What are classes and objects in Python?

A class is a blueprint or template that defines the attributes and methods that its objects will have. An object is a specific instance of a class, created by calling the class as if it were a function, and it holds its own data in the attributes defined by the class.

22. What is the init method?

The init method is a special constructor method that is automatically called when a new instance of a class is created. It is used to initialize the object's attributes with the values passed during instantiation, allowing each object to start with its own state.

23. What is the purpose of self in Python classes?

The self parameter refers to the current instance of the class and is used to access instance attributes and methods from within the class. It must be the first parameter of every instance method, though Python passes it automatically when you call the method on an object.

24. What is inheritance in Python?

Inheritance allows a child class to derive attributes and methods from a parent class, promoting code reuse and establishing a hierarchical relationship. Python supports both single and multiple inheritance, where a child class can inherit from one or more parent classes.

25. What is polymorphism?

Polymorphism means the ability of different classes to provide their own implementation of methods that share the same name. In Python, this is achieved through method overriding in subclasses and duck typing, where the type of an object matters less than whether it supports the required methods and behaviors.

26. What is encapsulation?

Encapsulation is the practice of bundling data and the methods that operate on that data within a single class, and restricting direct access to some of the object's components. In Python, this is achieved by convention using a single underscore prefix (_attribute) for protected members and a double underscore prefix (__attribute) for name-mangled private members.

27. What is abstraction in Python?

Abstraction is the concept of hiding complex implementation details and exposing only the essential features of an object. In Python, abstract classes can be created using the abc module, where the ABC base class and the @abstractmethod decorator ensure that subclasses provide implementations for specified methods.

28. What is method overriding?

Method overriding occurs when a child class provides its own implementation of a method that is already defined in its parent class. When the method is called on an instance of the child class, Python uses the child's version instead of the parent's, enabling specialized behavior.

29. What is the super() function?

The super() function returns a proxy object that allows you to call methods from a parent class within a child class. It is commonly used inside init to call the parent's constructor, ensuring that the parent class is properly initialized before adding child-specific attributes.

30. What is the difference between class variables and instance variables?

Class variables are shared among all instances of a class and are defined directly within the class body, while instance variables are unique to each instance and are typically assigned within init using self. Modifying a class variable affects all instances unless an instance has overridden it with its own attribute of the same name.

File Handling & Error Handling

31. How do you open and read a file in Python?

You open a file using the built-in open() function, which returns a file object. You can then read its contents using methods like read() (entire file as a string), readline() (one line at a time), or readlines() (all lines as a list), and you should always close the file afterward using close() or by using a with statement.

32. What are the different file modes in Python?

Common file modes include 'r' (read, default), 'w' (write, overwrites existing content), 'a' (append to end of file), and 'x' (exclusive creation, fails if file exists). Adding 'b' to any mode (e.g., 'rb', 'wb') opens the file in binary mode, which is used for non-text files like images or PDFs.

33. What is the with statement and why is it used for file handling?

The with statement is a context manager that automatically handles resource cleanup, such as closing a file, even if an exception occurs. Using with open('file.txt', 'r') as f: is preferred over manually calling open() and close() because it guarantees the file is properly closed when the block exits.

34. How does try/except/finally work?

The try block contains code that might raise an exception, the except block handles specific exceptions if they occur, and the finally block executes regardless of whether an exception was raised. You can also use an else block after except, which runs only if no exception was raised in the try block.

35. How do you raise an exception in Python?

You raise an exception using the raise keyword followed by an exception instance or class, such as raise ValueError("Invalid input"). This is useful for enforcing preconditions, validating inputs, or signaling error conditions in your own code.

36. How do you create a custom exception?

Custom exceptions are created by defining a new class that inherits from the built-in Exception class or one of its subclasses. For example, class InsufficientFundsError(Exception): pass creates a custom exception that can be raised and caught like any built-in exception, improving code clarity and error categorization.

37. What are some common built-in exceptions in Python?

Common built-in exceptions include ValueError (invalid value for an operation), TypeError (wrong type), KeyError (missing dictionary key), IndexError (index out of range), FileNotFoundError (file does not exist), ZeroDivisionError (division by zero), and AttributeError (missing attribute). Each exception indicates a specific kind of error, making debugging easier.

38. How can you use the os module for file operations?

The os module provides functions like os.path.exists() to check if a file exists, os.remove() to delete a file, os.rename() to rename a file, and os.listdir() to list directory contents. The os.path submodule offers utilities like os.path.join() for building paths and os.path.getsize() for getting file sizes in a platform-independent way.

39. What is the difference between read() and readlines()?

The read() method returns the entire file content as a single string, while readlines() returns a list where each element is a line from the file, including the newline character at the end. For large files, iterating over the file object directly with a for loop is more memory-efficient than either method.

40. What happens if you write to a file opened in 'w' mode that already has content?

Opening a file in 'w' (write) mode truncates the file, meaning all existing content is erased before any new data is written. If you want to add content without erasing what is already there, you should use 'a' (append) mode instead, which positions the write cursor at the end of the file.

Libraries & Modules

41. How do you import modules in Python?

You can import an entire module using import module_name, import specific items using from module_name import item, or import with an alias using import module_name as alias. The import system searches for modules in the directories listed in sys.path, which includes the current directory, installed packages, and standard library paths.

42. What is pip?

pip is the standard package manager for Python, used to install, upgrade, and remove third-party packages from the Python Package Index (PyPI). Common commands include pip install package_name to install a package, pip list to see installed packages, and pip freeze > requirements.txt to export a list of dependencies.

43. What is a virtual environment and why should you use one?

A virtual environment is an isolated Python environment that has its own set of installed packages, separate from the system-wide installation. It is created using python -m venv env_name and helps avoid dependency conflicts between projects by ensuring each project can have its own specific package versions.

44. What is NumPy and what are NumPy arrays?

NumPy is a fundamental library for numerical computing in Python that provides support for large, multi-dimensional arrays and matrices. A NumPy array (ndarray) is a grid of values of the same data type, and it is significantly faster than Python lists for mathematical operations because it uses optimized C code and supports vectorized operations.

45. What are some common NumPy array operations?

Common operations include element-wise arithmetic (addition, multiplication), statistical functions (np.mean(), np.std(), np.sum()), array reshaping (reshape()), slicing and indexing, and linear algebra operations (np.dot(), np.linalg.inv()). NumPy also provides broadcasting, which allows operations between arrays of different shapes under certain rules.

46. What is Pandas, and what are DataFrames and Series?

Pandas is a powerful data manipulation and analysis library built on top of NumPy. A Series is a one-dimensional labeled array that can hold any data type, while a DataFrame is a two-dimensional labeled table made up of multiple Series columns, similar to a spreadsheet or SQL table.

47. What is the difference between a Python list and a NumPy array?

A Python list can hold elements of different data types and supports general-purpose operations, while a NumPy array requires all elements to be of the same type and is optimized for numerical computation. NumPy arrays consume less memory, support vectorized operations without explicit loops, and are typically 10 to 100 times faster than lists for numerical tasks.

Key libraries include NumPy for numerical computation, Pandas for data manipulation, Matplotlib and Seaborn for data visualization, Scikit-learn for machine learning, TensorFlow and PyTorch for deep learning, and SciPy for scientific computing. Together, these libraries form a comprehensive ecosystem for data analysis and modeling.

49. What does if name == "main" do?

This conditional checks whether the Python file is being run directly as the main program or being imported as a module. When a file is executed directly, name is set to "main", so code inside this block only runs in that case, allowing the same file to serve as both a reusable module and a standalone script.

50. What is the difference between a package and a module?

A module is a single Python file (.py) containing definitions and statements, while a package is a directory containing multiple modules along with an init.py file (which can be empty in Python 3.3+). Packages provide a way to organize related modules into a hierarchical namespace, making large codebases more maintainable.