- What is Python?
Python is a high-level, interpreted, and dynamically-typed programming language known for its simplicity and readability.
- What are the key features of Python?
Key features of Python include readability, simplicity, extensibility, object-oriented programming, and a large standard library.
- What is PEP 8?
PEP 8 is the official style guide for Python, providing guidelines on how to format Python code for improved readability and consistency.
- How do you comment in Python?
You can use the ‘#’ symbol to add single-line comments and triple quotes (”’ ”’) for multi-line comments.
# This is a single-line comment
'''
This is a multi-line comment
Line 1
Line 2
'''
- What is the difference between lists and tuples? Lists are mutable, while tuples are immutable. Lists use square brackets ([ ]) and allow modifications, while tuples use parentheses (()) and cannot be changed after creation.
my_list = [1, 2, 3]
my_tuple = (4, 5, 6)
my_list[0] = 10 # Valid, modifies the list
# my_tuple[0] = 10 # Invalid, will raise an error
- What are Python decorators?
Decorators are a powerful feature in Python that allow you to modify the behavior of functions or methods without changing their code directly.
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
A decorator is a function that takes another function as its input and returns a new function. The new function is a wrapper around the original function.
def debug(func):
def wrapper(*args, **kwargs):
print('Calling {}'.format(func.__name__))
return func(*args, **kwargs)
return wrapper
@debug
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
print(factorial(5))
- Explain the difference between ‘is’ and ‘==’ in Python. ‘is’ checks if two variables refer to the same object in memory, while ‘==’ checks if the values of the two variables are equal.
x = [1, 2, 3]
y = x
print(x is y) # True
print(x == y) # True
z = [1, 2, 3]
print(x is z) # False
print(x == z) # True
- What are lambda functions? Lambda functions are anonymous functions defined using the
lambda
keyword. They are typically used for short, simple tasks.
add = lambda x, y: x + y
print(add(2, 3)) # Output: 5
- Explain list comprehension.
List comprehension is a concise way to create lists in Python. It allows you to create a new list by applying an expression to each item in an existing iterable.
squares = [x ** 2 for x in range(1, 6)]
print(squares) # Output: [1, 4, 9, 16, 25]
A comprehension is a concise way to create a list, set, or dictionary. Comprehensions are often used to filter or transform a sequence of values.
even_numbers = [i for i in range(10) if i % 2 == 0]
squares = {i ** 2 for i in range(10)}
names_and_ages = {name: age for name, age in zip(['John', 'Jane', 'Mary'], [30, 25, 40])}
- How can you handle exceptions in Python? Exception handling in Python is done using try, except, else, and finally blocks. The
try
block contains the code that may raise an exception, and the except
block handles the exception if it occurs.
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
except ValueError:
print("Error: Invalid input. Please enter a number.")
else:
print("Result:", result)
finally:
print("Execution completed.")
- Explain the concept of generators in Python.
Generators are functions that use the yield
keyword to return an iterator, allowing you to iterate over a sequence of values without generating the entire sequence at once.
def countdown(n):
while n > 0:
yield n
n -= 1
for i in countdown(5):
print(i)
5
4
3
2
1
A generator is a function that can be used to iterate over a sequence of values. Generators are often used to create iterators, which are objects that can be used to iterate over a sequence of values.
def fibonacci(n):
a, b = 0, 1
for i in range(n):
yield a
a, b = b, a + b
for i in fibonacci(10):
print(i)
- What is the difference between
__str__
and __repr__
?
__str__
is used to provide a user-friendly string representation of an object, while __repr__
is used to provide a developer-friendly string representation, often used for debugging.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name}, {self.age} years old."
def __repr__(self):
return f"Person('{self.name}', {self.age})"
person = Person("Alice", 30)
print(str(person)) # Output: Alice, 30 years old.
print(repr(person)) # Output: Person('Alice', 30)
- Explain the Global Interpreter Lock (GIL) in Python.
The GIL is a mutex used in CPython (the reference implementation of Python) to ensure that only one thread executes Python bytecode at a time. This can impact multi-threaded performance in CPU-bound applications.
- What is the use of the ‘pass’ statement in Python?
The ‘pass’ statement is a no-op and is used as a placeholder when a statement is syntactically required but you don’t want to execute any code.
if x < 0:
pass # Placeholder for handling negative numbers
else:
print("Positive number")
- What is the difference between a class and an object?
A class is a blueprint for creating objects. An object is an instance of a class.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def say_hello(self):
print('Hello, my name is {}'.format(self.name))
person = Person('John Doe', 30)
person.say_hello()
- What are the different types of inheritance in Python?
There are three types of inheritance in Python:
- Single inheritance: A class inherits from a single parent class.
- Multilevel inheritance: A class inherits from multiple parent classes.
- Hierarchical inheritance: A class inherits from a parent class, which inherits from another parent class, and so on.
class Animal:
def __init__(self, name):
self.name = name
def make_sound(self):
print('I am an animal!')
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed
def bark(self):
print('Woof!')
class Cat(Animal):
def __init__(self, name, fur_color):
super().__init__(name)
self.fur_color = fur_color
def meow(self):
print('Meow!')
dog = Dog('Sparky', 'Golden Retriever')
dog.bark()
cat = Cat('Mittens', 'Black')
cat.meow()
- What is the purpose of the ‘with’ statement in Python? The ‘with’ statement is used to ensure that certain operations are performed safely and automatically, such as file handling or acquiring/releasing locks.
with open("example.txt", "r") as file:
data = file.read()
# The file is automatically closed after exiting the 'with' block
- How can you copy an object in Python?
You can copy objects using the copy
module or using the slice operator.
import copy
# Shallow copy using copy module
original_list = [1, 2, 3]
copied_list = copy.copy(original_list)
# Deep copy using copy module
original_list = [1, [2, 3], 4]
copied_list = copy.deepcopy(original_list)
# Shallow copy using slice operator
original_list = [1, 2, 3]
copied_list = original_list[:]
- What are the main differences between Python 2 and Python 3?
Python 3 introduced several backward-incompatible changes like print function, integer division, and Unicode support. Python 2 reached its end of life on January 1, 2020.
- Explain the concept of multiple inheritance in Python.
Multiple inheritance allows a class to inherit attributes and methods from more than one base class. In Python, a class can have multiple base classes separated by commas in the class declaration.
class A:
def method_a(self):
print("Method A")
class B:
def method_b(self):
print("Method B")
class C(A, B):
pass
obj = C()
obj.method_a() # Output: Method A
obj.method_b() # Output: Method B
- How can you handle file I/O in Python?
You can use the built-in functions open()
to open a file and perform operations like reading, writing, or appending data.
# Writing to a file
with open("data.txt", "w") as file:
file.write("Hello, World!")
# Reading from a file
with open("data.txt", "r") as file:
content = file.read()
print(content) # Output: Hello, World!
- Explain the use of virtual environments in Python.
Virtual environments allow you to create isolated Python environments to manage dependencies and package versions for different projects.
- What is the difference between a mock object and a stub object?
Mock objects and stub objects are both used in unit testing to simulate the behavior of real objects. However, there are some key differences between the two.A mock object is a fake object that is created to test the behavior of a real object. Mock objects can be used to verify that a real object is called with the correct arguments and that it returns the correct values.A stub object is a fake object that is created to provide canned responses to requests. Stub objects can be used to simulate the behavior of a real object without having to actually create the real object.
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
def test_factorial():
# Create a mock object that simulates the behavior of a real function.
mock_factorial = mock.Mock()
mock_factorial.return_value = 120
# Use the mock object to test the factorial function.
assert factorial(5) == mock_factorial.call_count
# Create a stub object that provides canned responses to requests.
stub_factorial = stub.Stub()
stub_factorial.return_value = 120
# Use the stub object to test the factorial function.
assert factorial(5) == stub_factorial.return_value
- What is the difference between unittest and pytest?
Here are some of the key differences between unittest
and pytest
:
- Syntax:
unittest
uses a more verbose syntax than pytest
. For example, unittest
requires you to explicitly define a class for each test case, while pytest
allows you to define test cases directly in functions.
- Fixtures:
unittest
does not have a built-in fixture system, while pytest
does. Fixtures are reusable bits of code that can be used to set up or tear down your tests.
- Assertions:
unittest
and pytest
both have assertion libraries, but pytest
‘s assertions are more concise and expressive. For example, unittest
requires you to use the assertEqual()
method to compare two values, while pytest
allows you to use the more expressive assert
statement.
- Plugins:
pytest
has a plugin system that allows you to extend its functionality. There are many plugins available for pytest
, including plugins for generating test reports, collecting code coverage data, and running tests in parallel.
In general, pytest
is a more modern and expressive testing framework than unittest
. However, unittest
is still a widely used testing framework, and it may be a better choice for some projects.
- What is the difference between a continuous integration (CI) server and a continuous delivery (CD) server?
- Continuous integration (CI) is a practice of merging code changes into a shared repository on a regular basis. This helps to identify and fix bugs early in the development process.
- Continuous delivery (CD) is a practice of automatically deploying code changes to a production environment after they have been merged into a shared repository. This helps to ensure that code changes are always available to users.
A CI server is a tool that automates the process of continuous integration. A CD server is a tool that automates the process of continuous delivery.
Here is an example of how a CI server and a CD server can be used together:
- A developer makes a change to a code file.
- The developer commits the change to a shared repository.
- The CI server automatically runs tests on the code change.
- If the tests pass, the CI server automatically deploys the code change to a staging environment.
- The developer tests the code change in the staging environment.
- If the code change is working correctly, the CD server automatically deploys the code change to a production environment.
- What is the difference between a microservice architecture and a monolithic architecture?
- Microservice architecture is a software architecture style that structures an application as a collection of loosely coupled services. Each service is self-contained and performs a specific task.
- Monolithic architecture is a software architecture style that structures an application as a single unit. All of the code for the application is contained in a single unit.
Microservice architecture is more scalable and flexible than monolithic architecture. However, it can be more complex to develop and maintain.
Here is an example of how a microservice architecture and a monolithic architecture can be used:
- Microservice architecture: An e-commerce application might be divided into microservices for the product catalog, the shopping cart, the checkout process, and the shipping and billing system.
- Monolithic architecture: An e-commerce application might be implemented as a single unit with all of the code for the product catalog, the shopping cart, the checkout process, and the shipping and billing system in a single codebase.
- What is the difference between a RESTful API and a SOAP API?
- RESTful API is an API that uses the Representational State Transfer (REST) architectural style. REST APIs are based on the HTTP protocol and use standard HTTP verbs like GET, POST, PUT, and DELETE to access resources.
- SOAP API is an API that uses the Simple Object Access Protocol (SOAP) architectural style. SOAP APIs are based on XML and use SOAP messages to communicate between clients and servers.
RESTful APIs are more lightweight and easier to use than SOAP APIs. However, SOAP APIs can be more powerful and can support more complex data types.
Here is an example of how a RESTful API and a SOAP API can be used:
- RESTful API: A weather API might use a RESTful API to provide access to weather data. The API might use the GET verb to get the current weather conditions for a specific location.
- SOAP API: A banking API might use a SOAP API to provide access to bank account information. The API might use the SOAP message to request the balance of a specific bank account.
- What is the difference between a JSON API and a XML API?
- JSON API is an API that uses the JavaScript Object Notation (JSON) data format. JSON is a lightweight data format that is easy to read and write.
- XML API is an API that uses the Extensible Markup Language (XML) data format. XML is a more complex data format than JSON, but it can be used to represent more complex data structures.
JSON APIs are more lightweight and easier to use than XML APIs. However, XML APIs can be more powerful and can support more complex data types.
Here is an example of how a JSON API and an XML API can be used:
- JSON API: A weather API might use a JSON API to provide access to weather data. The API might return a JSON object with the current weather conditions for a specific location.
- XML API: A banking API might use an XML API to provide access to bank account information. The API might return an XML document with the balance of a specific bank account.
- What is RESTful API?
A RESTful API (Representational State Transfer API) is an application programming interface (API) that conforms to the constraints of the REST architectural style. REST is an acronym for Representational State Transfer, which is an architectural style for distributed hypermedia systems.RESTful APIs are based on the HTTP protocol and use standard HTTP verbs like GET, POST, PUT, and DELETE to access resources. Resources are identified by URIs (Uniform Resource Identifiers), and the data associated with a resource is returned in a format like JSON or XML.Here are some examples of RESTful APIs:
- The GitHub API
- The Twitter API
- The Google Maps API
- The Facebook API
from flask import Flask
app = Flask(__name__)
@app.route('/users', methods=['GET'])
def get_users():
"""Get a list of all users."""
users = [
{'id': 1, 'name': 'John Doe'},
{'id': 2, 'name': 'Jane Doe'},
]
return jsonify(users)
@app.route('/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
"""Get a specific user by ID."""
user = {'id': user_id, 'name': 'John Doe'}
return jsonify(user)
if __name__ == '__main__':
app.run(debug=True)
This code defines two RESTful APIs:
/users
: This API returns a list of all users.
/users/<int:user_id>
: This API returns a specific user by ID.
The GET
method is used to retrieve data from the API, the POST
method is used to create new data, the PUT
method is used to update existing data, and the DELETE
method is used to delete data.
The data returned by the API is in JSON format. JSON is a lightweight data-interchange format that is easy to read and write.
- What is the difference between a GraphQL API and a RESTful API?
- Querying: GraphQL APIs use a single query language to fetch data, while RESTful APIs use different verbs for different types of requests. For example, a GraphQL API might use the following query to fetch the name and age of a user:
-
query {
user(id: 1) {
name
age
}
}
A RESTful API might use the following HTTP requests to fetch the same data:
GET /users/1
GET /users/1/name
GET /users/1/age
- Data fetching: GraphQL APIs allow clients to specify exactly the data that they need, while RESTful APIs return all of the data for a resource. This can make GraphQL APIs more efficient, as clients only need to fetch the data that they need.
- Data modeling: GraphQL APIs are designed to be data-driven, while RESTful APIs are designed to be resource-driven. This means that GraphQL APIs are better suited for applications where the data is the most important part of the API.
- Complexity: GraphQL APIs can be more complex to develop than RESTful APIs. However, GraphQL APIs can also be more powerful and flexible.
In general, GraphQL APIs are a good choice for applications where the data is the most important part of the API. RESTful APIs are a good choice for applications where the resources are the most important part of the API.
Here is a table that summarizes the key differences between GraphQL APIs and RESTful APIs:
-
Feature |
GraphQL API |
RESTful API |
Querying |
Single query language |
Different verbs for different types of requests |
Data fetching |
Clients specify exactly the data that they need |
Clients fetch all of the data for a resource |
Data modeling |
Data-driven |
Resource-driven |
Complexity |
More complex to develop |
Less complex to develop |
Best for |
Applications where the data is the most important part of the API |
Applications where the resources are the most important part of the API |