PythonBasics Flashcards
What are the differences between Python 2 and Python 3? Why is Python 3 preferred for new projects?
Python 2 and Python 3 have several differences, including changes in print statements, integer division, Unicode handling, and more. Python 3 is preferred for new projects because it is the latest version, has better support for modern programming practices, and is more actively maintained.
Explain the differences between a list and a tuple in Python. When would you use one over the other?
Lists are mutable (can be modified after creation), while tuples are immutable (cannot be changed). Lists are typically used when you need to store a collection of items that may change, whereas tuples are used for data that should not be modified.
How do you handle exceptions in Python? Can you provide examples of how to use try, except, and finally blocks?
Exceptions are handled using try, except, and finally blocks. Code within the try block is tested for exceptions. If an exception occurs, the code in the corresponding except block is executed. The finally block is always executed, whether an exception occurred or not. Here’s an example:
try:
# Code that may raise an exception
result = 10 / 0
except ZeroDivisionError:
# Handle the specific exception
result = “Division by zero is not allowed”
finally:
# This block is always executed
print(“Execution completed”)
What is the purpose of virtual environments in Python, and how do you create and activate them?
Virtual environments are used to create isolated Python environments for different projects, preventing conflicts between dependencies. To create and activate a virtual environment, you can use the following commands:
Create a virtual environment:
python -m venv myenv
Activate the virtual environment:
On Windows: myenv\Scripts\activate
On macOS and Linux: source myenv/bin/activate
Describe the role of NumPy in Python data analysis. Provide an example of how you would create a NumPy array and perform basic operations on it.
Create a NumPy array
NumPy is a library for numerical operations in Python. It provides support for large, multi-dimensional arrays and matrices, along with mathematical functions to operate on these arrays. Here’s an example:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
sum_result = np.sum(arr)
mean_result = np.mean(arr)
What is Pandas, and how does it differ from NumPy? Can you explain the primary data structures in Pandas and how to load data into a DataFrame?
Load data from a CSV file
Pandas is a Python library for data manipulation and analysis. It provides data structures like Series (1-dimensional) and DataFrame (2-dimensional). Pandas is more focused on tabular data, while NumPy deals with arrays and matrices. To load data into a Pandas DataFrame:
import pandas as pd
df = pd.read_csv(‘data.csv’)
Explain the purpose of Matplotlib and Seaborn in data visualization with Python. Can you create a simple line plot using Matplotlib?
Sample data
Matplotlib and Seaborn are Python libraries for data visualization. Matplotlib is a powerful library for creating various types of plots, while Seaborn is built on top of Matplotlib and provides a higher-level interface with better aesthetics. To create a simple line plot using Matplotlib:
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 8, 6, 4, 2]
plt.plot(x, y)
plt.xlabel(‘X-axis’)
plt.ylabel(‘Y-axis’)
plt.title(‘Simple Line Plot’)
plt.show()
How do you read data from a SQL database using Python? Provide an example using a popular library.
Create a database connection
You can read data from a SQL database in Python using libraries like SQLAlchemy or the built-in sqlite3 for SQLite databases. Here’s an example using SQLAlchemy to connect to a MySQL database:
from sqlalchemy import create_engine
import pandas as pd
engine = create_engine(‘mysql://username:password@localhost/database_name’)
query = “SELECT * FROM table_name”
df = pd.read_sql(query, engine)
What is the purpose of list comprehensions in Python? Can you provide an example of using list comprehensions to filter or transform data?
List comprehensions provide a concise way to create lists by applying an expression to each item in an iterable. They are often used for filtering and transforming data. Here’s an example to create a list of squared numbers using a list comprehension:
original_list = [1, 2, 3, 4, 5]
squared_list = [x**2 for x in original_list]
What are the differences between supervised and unsupervised machine learning? Can you name a few algorithms for each type and briefly explain their applications?
Supervised learning involves training a model using labeled data (input and corresponding output) to make predictions or classifications. Common algorithms include Linear Regression, Decision Trees, and Support Vector Machines (SVMs). Unsupervised learning involves finding patterns in unlabeled data, often used for clustering and dimensionality reduction. Examples include K-Means clustering and Principal Component Analysis (PCA).
What is the Global Interpreter Lock (GIL) in Python, and how does it affect multi-threaded programs?
The Global Interpreter Lock (GIL) is a mutex in Python that allows only one thread to execute in the interpreter at a time. This means that in multi-threaded programs, even on multi-core CPUs, only one thread can execute Python bytecode at a time. This can limit the performance of CPU-bound multi-threaded programs. However, it does not affect multi-processing, which can utilize multiple CPU cores effectively.
Explain the concept of list slicing in Python and provide an example.
List slicing is a way to extract a portion of a list by specifying a start and end index. The slice includes elements from the start index up to (but not including) the end index. For example:
my_list = [1, 2, 3, 4, 5]
sliced_list = my_list[1:4] # Creates a new list [2, 3, 4]
What is a lambda function in Python, and when would you use it?
A lambda function is a small, anonymous function defined using the lambda keyword. It can take any number of arguments but can only have one expression. Lambda functions are often used when you need a simple, short function for a specific purpose, such as sorting or filtering data. Example:
double = lambda x: x * 2
result = double(5) # Returns 10
How does garbage collection work in Python, and what is its significance?
Python uses automatic memory management and a garbage collector to reclaim memory that is no longer in use. The garbage collector identifies and deallocates objects that are no longer referenced by the program, ensuring efficient memory usage and preventing memory leaks.
What is the purpose of the __init__ method in Python classes?
The __init__ method is a special method in Python classes, also known as the constructor. It is called when a new object of the class is created. The __init__ method initializes the attributes and properties of the object, allowing you to set the initial state of the object.
Explain the concept of a Python generator. How is it different from a regular function?
A Python generator is a special type of function that allows you to iterate over a sequence of values lazily, one at a time, without loading the entire sequence into memory. Generators use the yield keyword to yield values as they are generated, and they maintain their state between calls. This is different from regular functions that execute and return a result immediately.
What is the purpose of the if __name__ == “__main__” block in a Python script, and when would you use it?
The if __name__ == “__main__” block is used to determine if a Python script is being run as the main program or if it is being imported as a module into another script. Code within this block will only execute if the script is run directly. It is often used to include code that should only run when the script is executed as a standalone program and not when it is imported as a module.
Describe the concept of a Python decorator. Provide an example of how to use a decorator in a function.
A decorator is a function that can be used to modify or enhance the behavior of another function or method. Decorators are often used to add functionality such as logging, authentication, or validation to functions. Here’s a simple example of a decorator:
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()
What is the difference between a shallow copy and a deep copy of an object in Python?
A shallow copy of an object creates a new object that is a copy of the original object, but it does not create copies of nested objects within the original object. In contrast, a deep copy creates a new object and recursively creates copies of all nested objects within the original object. Shallow copies are often created using methods like copy.copy() in Python, while deep copies are created using methods like copy.deepcopy().
How do you handle file I/O in Python? Provide an example of how to read and write to a text file.
Reading from a file
File I/O in Python can be handled using built-in functions like open(), read(), write(), and close(). Here’s an example of reading and writing to a text file:
with open(‘file.txt’, ‘r’) as file:
contents = file.read()
with open(‘output.txt’, ‘w’) as file:
file.write(‘This is a sample text.’)
What is a Python decorator and how does it work? Can you provide an example of a built-in decorator in Python?
A Python decorator is a function that modifies the behavior of another function or method without changing its source code. Decorators are often used for tasks like logging, access control, and memoization. Built-in decorators in Python include @staticmethod, @classmethod, and @property. For example, the @property decorator can be used to create getter methods for class attributes without explicitly calling a method.
Explain the concept of a Python context manager and how it is used. Provide an example of creating a custom context manager.
Using the custom context manager
A Python context manager is an object that defines the methods __enter__() and __exit__() to set up and tear down a context for a block of code. Context managers are often used for resource management, such as file handling with with statements. Here’s an example of creating a custom context manager for timing code execution:
import time
class TimerContextManager:
def __enter__(self):
self.start_time = time.time()
return self
def \_\_exit\_\_(self, exc_type, exc_value, traceback): self.end_time = time.time() elapsed_time = self.end_time - self.start_time print(f"Elapsed time: {elapsed_time} seconds")
with TimerContextManager():
# Code to be timed
time.sleep(2)
What is a Python generator function, and how does it differ from a regular function?
A Python generator function is a special type of function that contains one or more yield statements. It allows you to create iterators lazily, generating values one at a time instead of storing them all in memory. Generator functions pause their execution state when encountering a yield statement and resume from where they left off when the next value is requested. This differs from regular functions that execute and return a result immediately.
Explain the purpose of the Python collections module. Provide examples of two data structures available in this module.
The collections module in Python provides specialized data structures beyond the built-in types like lists and dictionaries. Two commonly used data structures from this module are:
namedtuple: It creates a new class with named fields, allowing you to create simple, memory-efficient data objects.
Example:
from collections import namedtuple
Point = namedtuple(‘Point’, [‘x’, ‘y’])
p = Point(1, 2)
print(p.x, p.y) # Outputs: 1 2
Counter: It is used to count the occurrences of elements in an iterable and returns a dictionary-like object with the counts.
Example:
from collections import Counter
word_list = [‘apple’, ‘banana’, ‘apple’, ‘cherry’, ‘banana’]
counts = Counter(word_list)
print(counts) # Outputs: Counter({‘apple’: 2, ‘banana’: 2, ‘cherry’: 1})