Python Flashcards (Anki Alternative) | Best Decks for Python Mastery
Arrow keys or swipe to navigate cards
Master Python quickly with our Flashcards - an Anki alternative. Explore the best study decks for Python mastery at Stellar Study Cards!
What is a variable in Python? A variable in Python is used to store data values. It acts as a reference to an object in memory.
How do you create a list in Python?
You create a list in Python using square brackets, e.g.,
What is the difference between a list and a tuple in Python? The main difference is that lists are mutable (they can be changed), whereas tuples are immutable (they cannot be changed).
How do you write a comment in Python?
You write a comment in Python using the hash symbol
What is a dictionary in Python?
A dictionary is a collection of key-value pairs in Python, defined using curly braces, e.g.,
How do you check the data type of a variable in Python?
You use the
What are Python's logical operators?
Python's logical operators include
How can you convert a string to an integer in Python?
You can convert a string to an integer using the
What does the
How do you handle exceptions in Python?
You handle exceptions using
What is the purpose of the
How do you define a function in Python?
You define a function using the
What is a module in Python? A module is a file containing Python code, which can include functions, classes, and variables. It allows you to organize and reuse code.
How can you import a module in Python?
You can import a module using the
What does the
What are the basic built-in data types in Python?
Python has several built-in data types including:
- int for integers
- float for floating-point numbers
- str for strings
- bool for boolean values
- list for lists
- tuple for tuples
- set for sets
- dict for dictionaries.
How do you declare a string in Python?
A string in Python can be declared using single or double quotes.
For example:
What is the difference between a list and a tuple in Python? The main difference is that lists are mutable, meaning their elements can be changed, whereas tuples are immutable and cannot be altered after their creation.
How can you convert a number to a string in Python?
You can use the
For example:
What function do you use to check the data type of a variable in Python?
In Python, you use the
For example:
How can you create an empty dictionary in Python?
An empty dictionary in Python can be created by using a pair of curly braces:
What is a set in Python and how does it differ from lists? A set is a collection type in Python, similar to lists, but with distinct elements and no specific order. Unlike lists, sets do not allow duplicate entries.
How do you define a boolean variable in Python?
A boolean in Python can be set to
For example:
What is the difference between '==' and 'is' operators in Python? The '==' operator checks if the values of two operands are equal, whereas the 'is' operator checks if two operands refer to the same object in memory.
How can you add an element to a list in Python?
In Python, you can add an element to a list using the
For example:
What is a control structure in Python? A control structure is a block of programming that decides which path a program takes based on certain conditions.
How do you write an if statement in Python?
An if statement evaluates a condition, and if the condition is true, the block of code within it is executed. Example:
# code to execute
What is the purpose of an else statement in Python? An else statement is used to execute a block of code if the condition in the if statement is false.
How does an elif clause work in Python? Elif allows you to check multiple expressions for true and execute a block of code as soon as one of the conditions is true. It is short for 'else if'.
Write a simple for loop in Python that prints numbers from 1 to 5.
print(i)
What is the purpose of a while loop in Python? A while loop repeatedly executes a set of statements as long as a given condition is true.
Explain the difference between a for loop and a while loop in Python. A for loop is used for iterating over a sequence (like a list or a range), while a while loop continues until a specified condition is false.
How can you exit a loop prematurely in Python? Use the break statement to exit a loop before it has iterated over all elements or conditions.
What is the purpose of the continue statement in loops? The continue statement skips the rest of the code inside a loop for the current iteration only, and proceeds with the next iteration.
When would you use a nested loop in Python? Nested loops are used when you need to perform a loop within another loop, for example, when working with multi-dimensional data.
How do you implement a pass statement in a loop? The pass statement is a null operation; when it's executed, nothing happens. It acts as a placeholder in loops or conditional statements.
What does the else clause do in a loop in Python? The else clause can be used with loops. It executes after the for or while loop completes unless the loop is terminated by a break statement.
What is a function in Python? A function in Python is a block of reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.
How do you define a function in Python?
You can define a function in Python using the
What is the purpose of the
How can you pass arguments to a function?
You can pass arguments to a function by placing them inside the parentheses of the function definition. These arguments can be variables or values, and they are specified as a comma-separated list. For example:
What are default arguments in Python functions?
Default arguments are those that take a default value if no argument is provided. They are specified by assigning a default value to them in the function definition. For example:
Explain the difference between positional and keyword arguments. Positional arguments are passed to a function in the order they are defined, whereas keyword arguments are specified by the parameter name in the function call. This allows you to skip arguments or place them in any order.
What are variable-length arguments and how are they represented in Python?
Variable-length arguments allow a function to accept any number of arguments. In Python, they are represented by an asterisk (*) for non-keyword arguments and two asterisks (**) for keyword arguments. For example:
Describe the concept of recursion in Python functions. Recursion in Python refers to a function calling itself. This method is often used in problems that can be broken down into smaller, more manageable tasks. A base case is necessary to prevent infinite recursion.
How do you document a function using docstrings?
A docstring is a string literal that occurs as the first statement in a function, module, class, or method definition and is used to document its purpose. It is written using triple quotes (
What is a lambda function?
A lambda function is a small anonymous function defined using the
What is meant by a higher-order function in Python?
A higher-order function is a function that takes another function as an argument or returns a function as a result. Common examples include
How does Python handle function arguments with mutable and immutable data types? In Python, mutable objects (e.g., lists, dictionaries) can be changed within a function, whereas immutable objects (e.g., strings, integers) cannot be altered. The function receives a reference to the object, allowing changes to mutable objects.
What is function overloading and does Python support it? Function overloading refers to defining multiple functions with the same name but different implementations. Python does not support traditional function overloading; subsequent definitions overwrite the previous ones.
Explain decorators in Python functions.
Decorators are a special kind of function that either returns a function or gets passed into a function in order to modify its behavior. They are implemented by prefixing a function definition with a decorator function preceded by an @ symbol, like
What does the
How do you create a generator function in Python?
A generator function is created using the
What is the purpose of the
How can you achieve function memoization in Python?
Function memoization can be achieved using the
What is the purpose of the NumPy library in Python? NumPy is a library for the Python programming language, adding support for large, multi-dimensional arrays and matrices, along with a collection of mathematical functions to operate on these arrays.
How do you import the Pandas library in Python?
You can import the Pandas library using the following code:
What is the primary use of the Matplotlib library? Matplotlib is a plotting library for the Python programming language and its numerical mathematics extension NumPy. It is primarily used for creating static, interactive, and animated visualizations in Python.
Explain the use of the 'requests' library in Python. The 'requests' library is used to send HTTP/1.1 requests using Python. It allows you to send HTTP requests with methods like GET, POST, PUT, DELETE, etc., and also manage the response data.
What does the Python library 'BeautifulSoup' do? BeautifulSoup is used for web scraping purposes to pull data out of HTML and XML files. It provides Pythonic idioms for iterating, searching, and modifying the parse tree.
Describe the 'random' module in Python and its main use. The 'random' module implements pseudo-random number generators for various distributions. It is mainly used for generating random numbers, selecting random elements, or shuffling elements randomly.
What is the primary goal of the 'datetime' module in Python? The 'datetime' module in Python supplies classes for manipulating dates and times in both simple and complex ways. It allows the input and output of date and time data, computations, and formatting.
How do you install external libraries in Python?
You can install external libraries in Python using the package manager, pip. Usage:
What is the 'sys' module used for in Python? The 'sys' module provides access to some variables used or maintained by the Python interpreter and to functions that interact strongly with the interpreter. It can be used to manipulate the Python runtime environment.
What is the difference between 'os' and 'os.path' modules? The 'os' module provides a way of using operating system dependent functionality like reading or writing to the filesystem. The 'os.path' module is a sub-module of 'os' and is used for common pathname manipulations such as checking if a path exists, joining paths, etc.
What is object-oriented programming? Object-oriented programming (OOP) is a programming paradigm based on the concept of 'objects', which can contain data and code to manipulate that data.
What is a class in Python? A class in Python is a blueprint for creating objects. It defines a set of attributes and methods that the created object will have.
What is an object in Python? An object is an instance of a class. It contains the data in the form of fields and the procedures in the form of methods.
Explain the concept of inheritance in OOP. Inheritance is a mechanism in OOP where a new class can inherit properties and methods from an existing class.
What is polymorphism in Python? Polymorphism allows objects to be treated as instances of their parent class, letting a single interface be used for different data types.
What is encapsulation in OOP? Encapsulation is the concept of wrapping data and the methods that operate on that data within a single unit or class.
What is a method in Python? A method is a function that is defined inside a class and is meant to operate on instances of that class.
What is the purpose of the __init__ method in Python? The __init__ method is a special method in Python classes and is called a constructor. It is used to initialize the attributes of an object.
How do you access attributes of an object in Python?
Attributes of an object can be accessed using the dot operator:
What is a static method in Python? A static method is a method that belongs to the class rather than any object instance and can be called on the class itself.
Explain the concept of 'self' in Python methods. 'Self' is a reference to the current instance of the class and is used to access variables that belong to the class.
What is the difference between a class method and a static method in Python? A class method takes a class as the first parameter (typically called 'cls'), while a static method does not take any special first argument.
What is multiple inheritance? Multiple inheritance is a feature in which a class can inherit attributes and methods from more than one parent class.
How do you define a class in Python?
A class is defined using the
What is an abstract class in Python? An abstract class is a class that cannot be instantiated and is meant to be inherited by other classes. It often contains one or more abstract methods that must be implemented by subclasses.
How do you open a file in Python for reading?
To open a file in Python for reading, use the
What is the purpose of the 'with' statement in file handling?
The 'with' statement is used to ensure proper acquisition and release of resources. It automatically closes the file after the block of code is executed, even if exceptions occur. For example:
How can you write data to a file using Python?
To write data to a file, open the file in write ('w') or append ('a') mode and use the
What is the difference between 'read', 'readline', and 'readlines' methods? read() reads the entire content of a file into a single string. readline() reads one line at a time, and readlines() reads all lines and returns them as a list of strings.
How do you check if a file exists in Python?
To check if a file exists, use the
What is the mode used to open a file for binary reading?
To open a file for binary reading, use the mode 'rb'. For example:
How can you handle exceptions when working with files?
Use a try-except block to handle exceptions. For example:
Explain the difference between 'w' and 'a' modes in file handling. The 'w' mode overwrites the file if it exists or creates a new file. The 'a' mode appends data to the end of the file if it exists or creates a new file.
What keyword is used to catch exceptions in Python?
The try-except block is used to catch exceptions. You start with the
How do you ensure that certain code runs no matter what in a try-except block?
Use the
Can you handle multiple exceptions in a single try-except block?
Yes, you can handle multiple exceptions by specifying a tuple of exceptions in one
How do you raise an exception in Python?
Use the
What is the purpose of the
How can custom exceptions be created in Python?
Custom exceptions can be created by defining a new class that inherits from
What is the syntax to catch all exceptions without specifying them?
To catch all exceptions, use
What is a decorator in Python and how is it used?
A decorator in Python is a function that wraps another function to modify its behavior. Decorators are commonly used for logging, access control, and instrumentation. They are applied using the @ symbol before a function definition. For example:
def my_function():
pass
How can you create a generator in Python?
In Python, a generator is created using a function that contains one or more yield statements. Each time a generator's __next__() method is called, control resumes where it last left off (after the last yield statement). For example:
yield 1
yield 2
yield 3
Explain the use of the 'yield' keyword in Python.
The yield keyword is used in a function to make it a generator. When the function is called, it returns a generator object without executing the function. Each time the generator's __next__() method is called, the function executes until it reaches a yield statement. The value following yield is returned to the caller.
What is a 'closure' in Python?
A closure in Python is a function object that remembers values in enclosing scopes even if they are not present in memory. Closures are often used when a nested function references a value from its enclosing function. This allows the function to have 'remembered' behaviors. For example:
def inner_function(y):
return x + y
return inner_function
How do you apply multiple decorators to a single function in Python?
Multiple decorators can be applied to a function by stacking them above the function definition, with the decorator closest to the function being applied first. For example:
@decorator_2
def my_function():
pass
What is the purpose of the functools.wraps() decorator?
The functools.wraps() decorator is used in Python to preserve the metadata of the original function when using a decorator. This includes the original function's name, docstring, and other attributes. This is important for maintaining function introspection capabilities.
Describe how generator expressions differ from list comprehensions in Python.
Generator expressions are similar to list comprehensions but return a generator object instead of a list. They use parentheses instead of square brackets and are more memory efficient because they yield items one by one using the lazy evaluation approach. Example:
What is the advantage of using generators over lists? Generators are more memory efficient than lists because they do not store all elements in memory at once. Instead, they generate items on-the-fly using lazy evaluation. This makes generators especially useful for iterating over large datasets or streams of input data.
How does the @staticmethod decorator differ from @classmethod in Python?
The @staticmethod decorator defines a method that does not access or modify instance or class state, meaning it does not require a reference to self or cls. The @classmethod decorator, however, requires a reference to the class (cls) and can modify class state. Both decorators define methods that are associated with a class rather than its instances.
What are context managers in Python and how can they be implemented?
Context managers in Python allow for resource management, encapsulating the setup and teardown code. They can be implemented using classes with __enter__ and __exit__ methods or by using the contextlib.contextmanager decorator on a generator function. They are typically used with the with statement.
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
return False
What is the time complexity of searching for an element in a balanced binary search tree? The time complexity is \(O(\log n)\) for searching in a balanced binary search tree.
What is a hash table? A hash table is a data structure that implements an associative array, a structure that can map keys to values using hash functions.
What is the basic idea of a quicksort algorithm? Quicksort is a divide-and-conquer algorithm that selects a 'pivot' element from the array and partitions the other elements into two sub-arrays according to whether they are less than or greater than the pivot.
How does a stack differ from a queue? A stack is a LIFO (last-in, first-out) data structure, whereas a queue is a FIFO (first-in, first-out) data structure.
What are the primary operations of a linked list? The primary operations include insertion, deletion, and traversal of nodes in the list.
What is the main disadvantage of a linear search compared to a binary search? The main disadvantage is that linear search has a time complexity of \(O(n)\) whereas binary search has a time complexity of \(O(\log n)\), making it less efficient for large datasets.
What is a priority queue? A priority queue is an abstract data type similar to a regular queue, but where each element has a priority value associated with it. Elements with higher priority are served before elements with lower priority.
What is an AVL tree? An AVL tree is a type of self-balancing binary search tree, where the difference in heights between the left and right subtrees of any node is at most one.
Describe the merge operation in the merge sort algorithm. The merge operation in merge sort combines two sorted sub-arrays into a single sorted array by comparing the elements of both sub-arrays one by one.
What is the space complexity of the merge sort algorithm? The space complexity of merge sort is \(O(n)\) due to the additional storage required for the temporary arrays used during the merge process.
What is a graph's adjacency list representation? An adjacency list representation of a graph consists of a list of lists, where each list corresponds to a vertex and contains a list of vertices adjacent to it.
What distinguishes a directed graph from an undirected graph? A directed graph consists of edges with directions, indicating a one-way relationship, while an undirected graph has edges without any direction, showing a bidirectional relationship.
What is dynamic programming in algorithms? Dynamic programming is a method for solving complex problems by breaking them down into simpler subproblems, storing the results of subproblems to avoid solving the same problem multiple times.
What is the difference between breadth-first search (BFS) and depth-first search (DFS) in graph traversal? BFS explores the closest nodes first by using a queue, while DFS explores as far down a branch as possible before backtracking, typically using a stack or recursion.
Explain what a minimum spanning tree is in a graph. A minimum spanning tree is a subset of the edges in a weighted connected graph that connects all the vertices together, without any cycles and with the minimum possible total edge weight.
What is the Big O notation used for? Big O notation describes the upper bound of the time complexity or space complexity of an algorithm, representing the worst-case scenario.
How does a heap data structure work? A heap is a complete binary tree that maintains the heap property, where each parent node is greater than (in a max heap) or less than (in a min heap) its child nodes.
What is the purpose of a depth-first traversal in trees? Depth-first traversal helps in exploring all the nodes in a tree completely along one branch before retracing its steps to explore other branches.
What is a circular buffer? A circular buffer is a fixed-size buffer that wraps around upon reaching the end, enabling efficient queue-like access with constant time complexity for insertion and deletion.
What is the main advantage of a doubly linked list over a singly linked list? A doubly linked list allows for traversal in both directions (forward and backward) due to its usage of two pointers for each node, whereas a singly linked list only allows forward traversal.
What is Flask in Python web development? Flask is a lightweight, WSGI web application framework in Python that is designed with simplicity and flexibility in mind. It is known as a 'micro' framework because it does not require specific tools or libraries. Flask provides essentials and lets developers choose additional components to suit their needs.
How do you set up a basic Flask application?
To set up a basic Flask application, create a Python file (e.g.,
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run()
What are Django models and how are they used? Django models are Python classes that define the structure of your application's database. They map to database tables, and each attribute of the model class represents a database field. Models are used to perform operations such as creating, retrieving, updating, and deleting data.
Explain the concept of 'routes' in Flask.
In Flask, routes are URL patterns that are bound to Python functions. These functions handle the requests made to a specific URL. You define a route using the
What is a Django ORM, and why is it useful? Django ORM (Object-Relational Mapping) is a tool that allows developers to interact with the database using Python code instead of SQL. It simplifies database operations, such as querying data, by handling database tables as Python objects. This abstraction layer makes it easier to work with databases and simplifies cross-database compatibility.
How do you handle form data in Flask?
In Flask, form data can be handled by importing and using the
Example:
app = Flask(__name__)
@app.route('/submit', methods=['POST'])
def submit_form():
data = request.form['field_name']
return f'Received: {data}'
What is Django's 'settings.py' used for?
In Django,
How can you create a virtual environment for a Flask project?
A virtual environment can be created in Python using the following command line steps:
1. Navigate to your project directory.
2. Run
3. Activate the virtual environment:
- On Windows:
- On macOS/Linux:
Explain middleware in Django and its usage.
Middleware in Django is a series of hooks in the request/response processing. They are used to process requests before they reach the view, modify responses before they are sent to the client, and handle other tasks such as session handling, authentication, etc. Middleware is configured in the
What is a 'Flask Blueprint', and when should it be used? A Flask Blueprint is a way to organize a Flask application into smaller, manageable components. It allows you to define the application structure in a modular way with routes, templates, and static files, helping keep the code organized. Blueprints are used especially in larger applications to split functionality into reusable pieces.
How to manage static files in Django?
In Django, static files such as CSS, JavaScript, and images are managed using the
How can you define a URL pattern in Django?
In Django, a URL pattern is defined using the
Example:
from . import views
urlpatterns = [
path('home/', views.home, name='home')
]
What is the purpose of the Python
How do you run a test case using the
What is a breakpoint in the context of debugging? A breakpoint is a designated stop point set inside a line of code during debugging that allows you to pause program execution, examine variables, call stacks, and execute code step-by-step to find bugs.
Which Python statement is used to handle exceptions in a code block?
The Python
Explain the PDB module in Python. PDB stands for Python Debugger. It is a built-in module that allows for interactive debugging of Python programs. It lets you set breakpoints, step through code, inspect variables, and evaluate expressions interactively.
Describe how to test for expected exceptions using
What is the role of assertions in testing?
Assertions are statements that allow you to check certain conditions in your code. If the condition fails, an
What command is used to start the Python debugger (PDB)?
To start the Python debugger, you use the command
What is PEP 8 and why is it important in Python programming? PEP 8 is the Python Enhancement Proposal which provides guidelines and best practices on how to write Python code. It is important because it improves the readability of the code, helps maintain consistency across Python projects, and facilitates collaborative coding.
How can you ensure that your Python code is error-free before execution? You can use linting tools such as pylint or flake8 to analyze your code for errors and enforce coding standards. These tools can identify syntax errors, coding style violations, and potential bugs before the code is run.
What is the significance of using meaningful variable names in Python? Using meaningful variable names enhances code readability and maintainability by clearly indicating the purpose of the variable. It helps both the original developers and others who read the code understand its functionality without requiring excessive comments.
Explain the importance of function documentation in Python. Function documentation, typically done using docstrings, provides a description of the function's purpose, parameters, return values, and usage examples. It is crucial for understanding and using the function correctly without reading the entire code and facilitates easier maintenance and updating of the code base.
What does code refactoring mean and how does it contribute to code quality? Code refactoring is the process of restructuring existing code without changing its external behavior to improve its internal structure. It contributes to code quality by making the code cleaner, more efficient, and easier to understand, thereby reducing the risk of bugs and errors.
How do you handle exceptions in Python, and why is it a best practice?
Exceptions in Python are handled using the
What role does version control play in maintaining code quality? Version control systems like Git help manage changes to code by tracking revisions and facilitating collaboration among multiple developers. They help maintain code quality by ensuring that changes are well-documented, allowing developers to revert to previous versions if needed, and aiding in identifying and resolving conflicts.
How do you create a NumPy array from a Python list?
You can create a NumPy array from a Python list using the
What is the primary object of the Pandas library?
The primary object of the Pandas library is the
How do you access the first three rows of a DataFrame in Pandas?
You can access the first three rows of a DataFrame using the
Explain how you can add a new column to a Pandas DataFrame.
A new column can be added to a DataFrame by assigning a list or NumPy array to a new column name:
Describe how to perform element-wise multiplication of two NumPy arrays.
Element-wise multiplication of two NumPy arrays can be performed using the
How do you compute the mean of all elements in a NumPy array?
Use the
What is the method to handle missing data in Pandas?
The
How can you concatenate two Pandas DataFrames vertically?
Use the
Describe how to filter rows in a Pandas DataFrame based on a condition.
Use a boolean condition to filter rows:
What is the Pandas method for reading a CSV file into a DataFrame?
The
How do you save a Pandas DataFrame to a CSV file?
Use the
Explain how to transpose a DataFrame in Pandas.
The
How do you merge two Pandas DataFrames based on a common column?
Use the
How can you create a new DataFrame with a multi-index in Pandas?
Use
What function is used to find the standard deviation of values in a NumPy array?
The
What is project-based learning in the context of programming? Project-based learning involves students actively engaging in real-world and meaningful projects to apply programming concepts and skills.
Why is project-based learning beneficial for mastering Python? It allows learners to apply theoretical knowledge to practical situations, enhancing problem-solving skills and retention of concepts.
How can you incorporate project-based learning for Python beginners? Start with small, manageable projects like creating a simple calculator or a to-do list application, gradually increasing complexity as skills improve.
Describe a simple Python project that involves using data structures. Developing a contact book application where you can add, remove, and search contacts using lists and dictionaries.
What role does feedback play in project-based learning? Feedback helps learners identify mistakes and areas for improvement, promoting iterative development and enhancing learning.
What is an example of a project that can teach file handling in Python? Creating a program that reads, writes, and appends data to a text file, such as a personal diary application.
How does collaboration enhance project-based learning in Python? Collaboration encourages sharing of knowledge and skills, leading to diverse solutions and enhanced learning experiences.
Outline a project that uses APIs to gather data in Python. Design a weather application that fetches and displays current weather data using a public weather API.
What is a beneficial project to learn about Python's libraries for data visualization? Creating a data visualization dashboard using libraries like Matplotlib or Seaborn to display insights from a dataset.
How can Python projects be used to simulate real-world problems? Projects such as developing a stock market analysis tool or a traffic simulation can mimic real-world scenarios, providing practical experience.