Cracking Python Interview Questions On Programming

Why take this course?
- Concatenate and print the below lists with out using tempervory list or a variable:
print(''.join(map(str, list1 + list2)))
- Write a single line of code to print the square of all the numbers for a range of 10 numbers:
for i in range(1, 11): print(i ** 2)
- Write a single line of code to multiply every element of a list by three and assign it to a new list:
new_list = [x * 3 for x in list]
- Write a single line of code to make a new list by taking the first letter of each word from the given list:
new_list = [s[0] for s in list]
- Write a single line of code to extract all the numbers from a string:
numbers = [int(x) for x in re.findall(r'\d+', 'String with 123 numbers: 456, 789')]
-
Explain the use of ‘pass’ in python: The
pass
statement in Python is a null operation. It serves as a placeholder that does nothing—it allows you to write code where some code is required but you have not yet written (or will never write) the code that needs to go there. It's commonly used as a spaceholder in classes and loops until the implementation is ready. -
Write a program which will open the file, write the contents but will not explicitly close the file.
with open('file.txt', 'w') as f:
f.write('Hello, World!')
In Python 3, files are context managers and are automatically closed after their block is executed when using the with
statement.
- Write a program which will open the file, write the contents but will not explicitly close the file (using context manager):
The code for 126 also applies here. The with
statement ensures that the file is closed after its block is executed.
-
What is inheritance: Inheritance in object-oriented programming (OOP) is a mechanism where a new class is derived from an existing class. The new class, called a subclass or derived class, inherits attributes and methods from the existing class, which is called a superclass or base class. This allows for code reuse and the creation of a hierarchical class structure.
-
What is encapsulation: Encapsulation is one of the fundamental concepts in OOP that involves bundling the data (attributes) and methods that operate on the data into a single unit or class. It restricts external access to some of an object's components, or encourages it by providing a public interface. The main goal of encapsulation is to prevent outside interference and misuse of the data.
-
What is polymorphism: Polymorphism in OOP allows objects to be treated as instances of their parent class rather than their actual class. It allows for the use of a single interface to represent different underlying forms (data structures). Polymorphism can be achieved through method overriding, where a subclass provides a specific implementation of a method already defined in its parent class.
-
What is abstraction: Abstraction involves hiding the complex reality while exposing only the necessary parts. In OOP, it means creating simple models that represent more complex underlying realities. It helps in reducing programming complexity and effort by allowing us to focus on relevant aspects of a problem without getting distracted by irrelevant details.
-
What is an abstract class: An abstract class in OOP cannot be instantiated directly and is intended to be subclassed. It may contain abstract methods that must be implemented by its subclasses. Abstract classes are used as a base for other classes to follow a common interface while being able to define behavior that distinguishes them from each other.
-
What is a decorator in Python: A decorator in Python is a design pattern that allows a function to be wrapped by another function, effectively modifying the original function's behavior without permanently altering its code. Decorators are often used for logging, caching, or altering function behavior based on certain conditions or arguments passed to the decorated function.
-
What is a generator in Python: A generator in Python is a special type of iterator that generates values dynamically when needed and can be iterated over like a list. Generators are defined using the
yield
keyword and are memory efficient because they don't need to store all values at once. They are useful for handling large datasets or producing an infinite sequence of values. -
What is PEP 8: PEP 8 is the style guide for Python code. It provides a set of recommendations and conventions for writing readable Python source code. PEP 8 covers aspects such as naming conventions, indentation, whitespace, comments, and more, to make Python programs consistent and maintainable.
-
What is type hinting in Python: Type hinting in Python uses Python's typing module to indicate the expected types of function arguments, return values, and variables. It helps with code readability and can be used by static type checkers like
mypy
to validate that the types are being used correctly. Type hinting is optional in Python but recommended for large codebases or when working with other developers to ensure consistency and correctness of the code. -
What is a linter: A linter is a static code analysis tool that checks source code for potential problems, enforces a coding standard, and often helps detect code smells and enforce best practices. Linters can be configured to suit specific coding styles and are useful for maintaining code quality and consistency across large projects and teams.
-
How to run unit tests in Python: To run unit tests in Python, you use the
unittest
module, which is included as a standard library. You write your test cases within subclasses ofunittest.TestCase
and then execute them using a test runner likeunittest.main()
. For more complex or distributed testing, you can usepytest
ornose2
. -
What is code coverage: Code coverage measures the proportion of your source code that is executed while tests are running. It's a metric used to indicate the extent to which the source code of a program is executed when a particular software tool is applied. A high level of coverage indicates well-tested code and may correlate with fewer bugs, but it doesn't guarantee code quality or freedom from bugs.
-
How to use
assert
statements in Python: Theassert
statement in Python is used for debugging purposes during development. It can be used to verify that a condition holds true, and if it does not, anAssertionError
is raised. In unit testing, theunittest.TestCase
class provides a more robust form of assertions with methods likeassertEqual
,assertTrue
, etc. -
What is the difference between
assert
in Python andunittest.TestCase
: Theassert
statement in Python is a simple debugging aid that stops execution when an assertion fails, which makes it unsuitable for production code because it can lead to runtime errors if assertions fail unexpectedly (e.g., in a deployment environment).unittest.TestCase
, on the other hand, is designed for unit testing and provides a set of assert methods to check conditions without causing the program to stop if an assertion fails, making it suitable for production use. -
What is Test-Driven Development (TDD): Test-Driven Development (TDD) is a software development approach where tests are written before the actual code. The process follows the Red-Green-Refactor cycle: first, write a test that defines a desired improvement or new function (Red), then implement the minimal code to pass the test (Green), and finally refactor the code while ensuring the test remains passed (Refactor). TDD promotes reliable, high-quality code by ensuring tests are always up-to-date with the implementation.
-
What is Behavior-Driven Development (BDD): Behavior-Driven Development (BDD) extends TDD to focus on the behavior of the software from the perspective of the user. It encourages collaboration between developers, QA, and non-technical or business participants by writing tests in a human-readable domain-specific language that describes how the application should behave. Tools like Cucumber (for Ruby) and Behave (for Python) support BDD by allowing the definition of executable specifications.
-
What are integration tests: Integration tests verify the interactions between different parts or modules of an application, such as interfaces between classes, components, services, or external systems. Unlike unit tests, which test small pieces of code in isolation, integration tests ensure that these components work together as expected and communicate correctly with each other.
-
What is Continuous Integration (CI) and Continuous Deployment (CD): Continuous Integration (CI) is a development practice where developers frequently merge their changes into a shared main branch, automatically building the software to identify problems early. Continuous Deployment (CD) extends CI by automatically deploying the software to production or a staging environment whenever changes are made. Both practices aim to improve software quality and reduce the time it takes to release new features or fixes.
-
What is a mock object: A mock object is a placeholder for a real object that is used during testing. Mock objects simulate the behavior of the actual object and allow developers to verify interactions between the system under test and the object's methods, as well as to assert the expected input/output parameters. Libraries like
unittest.mock
in Python or JMockit in Java are commonly used to create mock objects. -
What is a stub: A stub is similar to a mock object but is typically used for providing canned responses. Unlike mocks, which enforce certain method calls and check that they happen with specific arguments, stubs are used when you want to return a fixed response from the system under test without simulating complex interactions or side effects.
-
What is dependency injection: Dependency injection is a design pattern that allows a class to receive its dependencies from an external source rather than creating them internally. This leads to more modular code, easier testing (since dependencies can be replaced with mocks or stubs), and a clearer separation of concerns. Popular frameworks like Spring in Java or Django in Python support dependency injection through their DI containers.
-
What is the Law of Demeter (LofD): The Law of Demeter, also known as the Principle of Least Knowledge, states that a given object should not make calls on other objects different from its immediate friends (these being the objects passed as arguments to its methods). This principle aims to reduce interdependence between classes and modules, leading to code that is more modular, reusable, and easier to understand.
-
What is Single Responsibility Principle (SRP): The Single Responsibility Principle states that a class should have only one reason to change, meaning that it should only have one job or responsibility. This means that if a class has more than one responsibility, it should be refactored into multiple classes, each handling one aspect of the original class's duties. SRP contributes to better maintainability and understandability of the codebase.
-
What is an Integration Framework: An Integration Framework provides a standardized way of connecting disparate systems or components and ensuring that they work together as expected. These frameworks handle cross-cutting concerns like data formats, message serialization/deserialization, error handling, and security. Examples include Apache Camel, MuleSoft Anypoint, and Talend.
-
What is the Open/Closed Principle (OCP): The Open/Closed Principle dictates that software entities (classes, modules, functions) should be open to extension but closed for modification. This means that you can extend the behavior of existing code without modifying its source code, which leads to more robust and maintainable codebases.
-
What is an ORM (Object-Relational Mapping): An ORM is a tool or framework that allows developers to work with a database using objects instead of SQL queries. An ORM maps classes and their instances to database tables and rows, providing methods for data persistence without the need for writing raw SQL code. Popular ORMs include Hibernate for Java, Django's ORM for Python, and Entity Framework for .NET.
-
What is a DAO (Data Access Object): A DAO is an abstraction which can be used to access persistence mechanisms (like databases or file systems) and return data to the more complex business objects (which are likely to be classes in your application). It's a form of separation of concerns, as it keeps all the logic required to retrieve, update, insert or delete data in a single place.
-
What is a Service Layer: A Service Layer is a design pattern where business logic is separated from data access and presentation layers. This layer encapsulates the core functionalities of the application, performs complex tasks, delegates database operations to DAOs, and acts as an intermediary between the application's UI and data persistence layers. It enhances the separation of concerns and makes the code more maintainable.
-
What is a Facade Pattern: The Facade pattern provides a simplified interface to a complex subsystem. It defines a higher-level interface that makes the subsystem easier to use and understand. A facade acts as a single entry point for clients; it doesn't encapsulate or modify the subsystem, just provides a uniform and simplified way of interacting with it.
-
What is a Factory Method Pattern: The Factory Method pattern defines an interface for creating an object but lets subclasses decide which class to instantiate. It promotes flexibility in the face of variability in object creation, without exposing the underlying instantiation logic to the client code (which is akin to the Decorator and Prototype patterns).
-
What is a Singleton Pattern: The Singleton pattern ensures that a class has only one instance and provides a global point of access to it. This is often used when exactly one object is needed to coordinate actions across the system or to manage a shared resource. However, it's important to use this pattern judiciously as it can create hidden dependencies between classes and make testing more difficult.
-
What is the Command Pattern: The Command pattern encapsulates a request as an object, thereby allowing for parameterization of methods with different requests, queueing of operations, and supporting undoable operations. Each command knows how to execute itself, possibly through one or more receivers; commands can also be queued and stored, passed as parameters, and so forth.
-
What is the Adapter Pattern: The Adapter pattern allows objects with different interfaces to work together. It presents a unified interface to its clients while simultaneously converting (or adapting) the interface of an object into another interface that clients expect. This is particularly useful when you need to integrate with legacy systems or third-party libraries that have incompatible interfaces.
-
What is the Strategy Pattern: The Strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. The strategy pattern lets the algorithm vary independently from clients that use it. This means that algorithms can be selected at runtime, which allows for more flexible and extensible code.
-
What is the Decorator Pattern: The Decorator pattern attaches additional responsibilities to objects dynamically. Decorators provide a flexible alternative to subclassing for extending functionality. This technique is particularly useful when designing flexible systems that need to evolve over time, as it allows new features to be added without altering the existing codebase (as opposed to using inheritance for the same purpose).
-
What is the Composite Pattern: The Composite pattern is a part-whole hierarchy where "leaves" and "composites" of the hierarchy may be treated uniformly. It's used to represent whole-part hierarchies to treat individual objects and compositions of objects uniformly. This simplifies client use of complex tree structures.
-
What is the Decorator Pattern vs. Composite Pattern: The key difference between the Decorator and Composite patterns lies in their purpose. The Decorator pattern is used to dynamically add or override behavior of an object, whereas the Composite pattern is used to treat individual objects and compositions of objects uniformly. Decorator can be considered a way to extend functionality, while Composite is focused on representing hierarchical structures.
-
What are Design Patterns: Design patterns are typical solutions to common problems in software design. They are like templates or blueprints that provide a reusable and adaptable solution to a specific design challenge. Patterns describe not just the patterns of elements, their relationships, and responsibilities but also precisely which elements behave in which manner. They help developers write code that is understandable, maintainable, and can be applied to many different systems without being bound to one particular framework or language.
-
What are the three main categories of Design Patterns: The three main categories of design patterns are Creational, Structural, and Behavioral. Creational patterns (such as Singleton, Factory Method, Abstract Factory, Builder, and Prototype) are focused on the creation of objects. Structural patterns (like Adapter, Composite, Facade, Flyweight, and Proxy) deal with how classes and objects are composed to form larger structures. Behavioral patterns (including Observer, Strategy, Command, Iterator, and State) concern themselves with communication between objects, particularly with respect to their responsibilities and duties.
-
What are Creational Design Patterns: Creational design patterns provide ways to create and instantiate single or multiple objects in a way that keeps the system flexible and manageable. They abstract the details of object creation and provide a way to create complex objects by using simpler objects. This means the system can be independent of how its objects are created, composed, and represented.
-
What is the Factory Method pattern (Creational): The Factory Method pattern is a creational pattern that provides an interface for creating an object but allows subclasses to alter the type of instances thereby produced by subclass-specific methods. It's particularly useful when a class cannot anticipate the classes of objects it will need to create in the future.
-
What are Structural Design Patterns: Structural design patterns are concerned with how classes and objects are composed to form larger structures. They explicitly represent hierarchical or many-one relationship using inheritance and composition. These patterns help designers manage common object-oriented constructs like class hierarchies and relationships between objects, which can become unwieldy and unmanageable as systems grow.
-
What is the Facade Pattern (Structural): The Facade pattern provides a simplified interface to a complex subsystem. It defines a high-level interface that makes the subsystem easier to use, which means clients interact with this facade without needing an intricate understanding of the subsystem's architecture.
-
What is the Proxy Pattern (Structural): The Proxy pattern provides a surrogate or placeholder for another object to control access to it. This is used for lazy loading, access control, caching, and more. The proxy can be selective in what operations it allows to be performed on the original object, referenced by a proxy object.
-
What are Behavioral Design Patterns: Behavioral design patterns are concerned with algorithms and the assignment of responsibilities between objects. They typically involve the dynamics between objects or classes as they interact with one another to fulfill a request or achievement of some functional aspect of a system. These patterns deal directly with communication between objects and are generally more difficult to implement than Creational and Structural patterns, but they are very powerful in organizing system behaviors.
-
What is the Singleton Pattern vs. Proxy Pattern: The Singleton pattern ensures that only one instance of a class can exist at any time (the instance is stored on demand), while the Proxy pattern provides a placeholder for another object that defers or controls the access to the original object. The Singleton is about managing a single point of access to shared state, whereas the Proxy is about controlling access and possibly augmenting the behavior of the real subject (target) it represents.
-
What are the benefits and drawbacks of using Design Patterns: Benefits:
- Improved code modularity by separating concerns.
- Facilitate communication among developers as patterns have established names and standard traits.
- Code reusability through the implementation of common solutions to common problems.
- Better design quality due to well-tried and -proven concepts.
- Reduced effort in dealing with evolving systems.
Drawbacks:
- Overuse of design patterns can lead to overcomplicated solutions, often referred to as "pattern vomiting."
- Patterns can be misapplied leading to a solution that doesn't fit the problem.
- They require familiarity and understanding; otherwise, they can become a source of confusion.
- Can introduce unnecessary complexity, especially in smaller applications where patterns might not be necessary.
- What is the Observer Pattern (Behavioral): The Observer pattern defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. It's used to manage subscriptions and dependence between objects, which allows for flexible and dynamic communication between them. The pattern is particularly useful in implementing event handling systems and in scenarios where data dependencies need to be cumbersome or expensive to establish or maintain.
Course Gallery




Loading charts...