Python Programming Flashcards
Arrow keys or swipe to navigate cards
Master Python programming with flashcards covering fundamental and advanced concepts like data types, control structures, functions, and libraries. Learn tips and tricks for writing efficient and Pythonic code.
What are Python's core data types?
Python's core data types include:
- Numbers: \(\texttt{int, float, complex}\)
- Sequences: \(\texttt{list, tuple, range, str}\)
- Sets: \(\texttt{set, frozenset}\)
- Mappings: \(\texttt{dict}\)
- Other types: \(\texttt{bool, NoneType}\)
What is the difference between \(\texttt{list}\) and \(\texttt{tuple}\)?
\(\texttt{list}\) is mutable (modifiable), while \(\texttt{tuple}\) is immutable (cannot be modified after creation). For example:
\(\texttt{list: [1, 2, 3]}\)
\(\texttt{tuple: (1, 2, 3)}\).
What are Python's control structures?
Python control structures include:
- Conditional statements: \(\texttt{if, elif, else}\)
- Loops: \(\texttt{for, while}\)
- Exception handling: \(\texttt{try, except, finally}\)
How do you define a function in Python?
Functions in Python are defined using \(\texttt{def}\). Example:
\(\texttt{def greet(name):}\)
\(\texttt{ return f'Hello, {name}!'}\)
What is the difference between a \(\texttt{set}\) and a \(\texttt{dict}\)? \(\texttt{set}\) is an unordered collection of unique elements, while \(\texttt{dict}\) is a key-value mapping where each key is unique.
What is a Python \(\texttt{module}\)? A \(\texttt{module}\) is a file containing Python code (functions, classes, or variables) that can be imported and reused. Example: \(\texttt{import math}\).
What is a Python \(\texttt{try-except}\) block?
A \(\texttt{try-except}\) block is used to handle exceptions. Example:
\(\texttt{try:}\)
\(\texttt{ x = 1 / 0}\)
\(\texttt{except ZeroDivisionError:}\)
\(\texttt{ print('Cannot divide by zero!')}\)
What is \(\texttt{pandas}\), and why is it used? \(\texttt{pandas}\) is a library for data analysis and manipulation, offering structures like \(\texttt{DataFrame}\) and \(\texttt{Series}\) for handling tabular data.
What is \(\texttt{NumPy}\), and why is it used? \(\texttt{NumPy}\) is a library for numerical computing. It provides support for arrays, matrices, and high-performance mathematical functions.
What is a Python class, and how do you define one?
A class is a blueprint for creating objects. Example:
\(\texttt{class MyClass:}\)
\(\texttt{ def __init__(self, value):}\)
\(\texttt{ self.value = value}\)
What is the difference between \(\texttt{instance}\) and \(\texttt{class}\) variables? \(\texttt{Instance}\) variables are specific to an object, while \(\texttt{class}\) variables are shared among all instances of a class.
What is the difference between \(\texttt{==}\) and \(\texttt{is}\)? \(\texttt{==}\) checks for value equality, while \(\texttt{is}\) checks for object identity (whether two variables point to the same object).
What is a Python generator?
A generator is a function that produces items lazily using the \(\texttt{yield}\) keyword instead of \(\texttt{return}\). Example:
\(\texttt{def gen(): yield 1; yield 2}\)
What is the Global Interpreter Lock (GIL) in Python? The GIL is a mutex in CPython that prevents multiple threads from executing Python bytecode simultaneously, ensuring thread safety.
How do you install Python libraries? Use \(\texttt{pip}\), the Python package manager. Example: \(\texttt{pip install requests}\)
What is Python's \(\texttt{NoneType}\)? \(\texttt{NoneType}\) is the type of \(\texttt{None}\), a special object representing the absence of a value.
How do you merge two dictionaries in Python?
In Python 3.9+, use \(\texttt{|}\). Example:
\(\texttt{dict1 | dict2}\)
In earlier versions, use \(\texttt{update()}\).
What is a \(\texttt{break}\) statement in Python? \(\texttt{break}\) exits the nearest enclosing loop prematurely.
What are Python's anonymous functions?
Anonymous functions are defined using \(\texttt{lambda}\). Example:
\(\texttt{lambda x: x * 2}\)
What is a Python dictionary?
A dictionary is a collection of key-value pairs where each key is unique. Example:
How do you add a key-value pair to a dictionary?
To add a key-value pair to a dictionary, use the syntax:
\(\texttt{dict[key] = value}\).
Example:
\(\texttt{my_dict['city'] = 'New York'}\).
What is a Python \(\texttt{set}\), and how is it different from a \(\texttt{list}\)?
A \(\texttt{set}\) is an unordered collection of unique elements. Unlike a \(\texttt{list}\), it does not allow duplicates. Example:
\(\texttt{my_set = {1, 2, 3}}\).
What is the difference between \(\texttt{continue}\) and \(\texttt{break}\)? \(\texttt{break}\) exits the nearest loop entirely, while \(\texttt{continue}\) skips the current iteration and moves to the next one.
What is a default parameter in Python?
A default parameter has a predefined value if no argument is passed. Example:
print(f'Hello, {name}!')
How do you return multiple values from a Python function?
You can return multiple values using a \(\texttt{tuple}\):
\(\texttt{def my_func(): return 1, 2}\).
Calling \(\texttt{my_func()}\) returns \(\texttt{(1, 2)}\).
What is inheritance in Python?
Inheritance allows a class to derive attributes and methods from another class. Example:
\(\texttt{class Child(Parent): pass}\).
What is method overriding in Python? Method overriding occurs when a subclass provides a specific implementation of a method already defined in its parent class.
What is the difference between \(\texttt{try-except}\) and \(\texttt{try-finally}\)? \(\texttt{try-except}\) handles exceptions, while \(\texttt{try-finally}\) ensures the \(\texttt{finally}\) block executes regardless of an exception.
What is \(\texttt{matplotlib}\), and what is it used for? \(\texttt{matplotlib}\) is a Python library for creating visualizations like line plots, bar charts, and scatter plots.
What is \(\texttt{scikit-learn}\)? \(\texttt{scikit-learn}\) is a Python library for machine learning. It provides tools for classification, regression, clustering, and preprocessing.
What is slicing in Python?
Slicing extracts a subset of elements from sequences like \(\texttt{list}\), \(\texttt{tuple}\), or \(\texttt{str}\). Syntax:
\(\texttt{sequence[start:stop:step]}\).
What is a Python decorator?
A decorator is a function that modifies the behavior of another function. Example:
\(\texttt{@decorator}\)
\(\texttt{def func(): pass}\).
What is Python's with statement used for?
The with statement ensures proper acquisition and release of resources. Example:
data = f.read()
What is the difference between \(\texttt{deepcopy}\) and \(\texttt{copy}\)? \(\texttt{copy}\) creates a shallow copy, while \(\texttt{deepcopy}\) creates a new object with recursively copied nested objects.
What is \(\texttt{TensorFlow}\)? \(\texttt{TensorFlow}\) is a Python library for building and training machine learning models, especially deep neural networks.
What is \(\texttt{Flask}\), and why is it used? \(\texttt{Flask}\) is a lightweight Python web framework for building web applications.
What is a \(\texttt{while}\) loop, and how is it used?
A \(\texttt{while}\) loop repeats as long as a condition is \(\texttt{True}\). Example:
\(\texttt{while x < 10: x += 1}\).
How do you create a list comprehension in Python?
List comprehensions provide a concise way to create lists. Example:
\(\texttt{[x**2 for x in range(5)]}\) creates \(\texttt{[0, 1, 4, 9, 16]}\).
What is a Python \(\texttt{range}\) object?
A \(\texttt{range}\) object generates a sequence of numbers. Example:
\(\texttt{range(5)}\) produces \(\texttt{0, 1, 2, 3, 4}\).
What is a for loop in Python, and how does it work?
A for loop iterates over items of a sequence (e.g., list, string) or any iterable. Example:
print(item)
What is the purpose of \(\texttt{print()}\) in Python?
\(\texttt{print()}\) outputs data to the console. Example:
\(\texttt{print('Hello, World!')}\) displays \(\texttt{Hello, World!}\).
What is a \(\texttt{variable}\) in Python?
A \(\texttt{variable}\) is a name that refers to a value. Example:
\(\texttt{x = 10}\) assigns the value \(\texttt{10}\) to \(\texttt{x}\).
What is a \(\texttt{list}\) comprehension, and how is it used?
A \(\texttt{list}\) comprehension provides a concise way to create lists. Example:
\(\texttt{squares = [x**2 for x in range(5)]}\) creates \(\texttt{[0, 1, 4, 9, 16]}\).
What are keyword arguments in Python?
Keyword arguments are passed with a key-value pair, making the function call more readable. Example:
print(f'Hello, {name}!')
greet(name='Alice')
What is a \(\texttt{lambda}\) function in Python?
A \(\texttt{lambda}\) function is an anonymous function defined using the \(\texttt{lambda}\) keyword. Example:
\(\texttt{square = lambda x: x**2}\).
What does the \(\texttt{finally}\) block do in Python? The \(\texttt{finally}\) block is always executed, whether or not an exception occurs in the \(\texttt{try}\) block.
What is an \(\texttt{object}\) in Python? An \(\texttt{object}\) is an instance of a class. It encapsulates data and behavior defined by the class.
What is encapsulation in Python? Encapsulation is the practice of bundling data and methods within a class while restricting direct access to some components.
What is requests, and how is it used?
The requests library is used for sending HTTP requests in Python. Example:
response = requests.get('https://api.example.com')
print(response.text)
What is \(\texttt{BeautifulSoup}\), and what is it used for? \(\texttt{BeautifulSoup}\) is a library for parsing HTML and XML documents, used in web scraping.
What is a Python \(\texttt{tuple}\), and when should you use it?
A \(\texttt{tuple}\) is an immutable sequence. Use it when the data should not change. Example:
\(\texttt{coordinates = (10, 20)}\).
How do you create a dictionary in Python?
Use curly braces or the \(\texttt{dict()}\) function. Example:
\(\texttt{my_dict = {'key': 'value'}}\).
What is a Python context manager?
A context manager ensures resources are properly managed, such as opening and closing files, using the `with` statement. Example:
data = f.read()
What are Python's \(\texttt{*args}\) and \(\texttt{**kwargs}\)? \(\texttt{*args}\) collects positional arguments into a tuple, and \(\texttt{**kwargs}\) collects keyword arguments into a dictionary.
What is Python's \(\texttt{pass}\) statement?
The \(\texttt{pass}\) statement is a placeholder that does nothing. Example:
\(\texttt{if condition: pass}\).
What is a nested loop in Python?
A nested loop is a loop inside another loop. Example:
\(\texttt{for i in range(3):}\)
\(\texttt{ for j in range(2): print(i, j)}\).
What is the purpose of \(\texttt{else}\) in a loop? The \(\texttt{else}\) block in a loop runs if the loop completes without a \(\texttt{break}\).
What is a \(\texttt{metaclass}\) in Python? A \(\texttt{metaclass}\) is a class of a class that defines how a class behaves.
What are Python's async and await keywords?
The async and await keywords enable asynchronous programming, allowing tasks to run without blocking the main program. Example:
async def func():
await asyncio.sleep(1)
print('Finished!')
asyncio.run(func())
How do you check the length of a sequence in Python?
Use the \(\texttt{len()}\) function. Example:
\(\texttt{len([1, 2, 3])}\) returns \(\texttt{3}\).
How do you access elements in a list?
Use zero-based indexing. Example:
\(\texttt{my_list = [10, 20, 30]}\)
\(\texttt{my_list[0]}\) returns \(\texttt{10}\).
How do you reverse a list in Python?
Use slicing or the \(\texttt{reverse()}\) method. Example:
\(\texttt{my_list[::-1]}\) or \(\texttt{my_list.reverse()}\).
What is \(\texttt{os}\), and how is it used?
\(\texttt{os}\) is a library for interacting with the operating system. Example:
\(\texttt{import os}\)
\(\texttt{os.getcwd()}\) returns the current working directory.
What is \(\texttt{sys}\), and what is it used for?
\(\texttt{sys}\) provides access to system-specific parameters and functions. Example:
\(\texttt{sys.argv}\) contains command-line arguments.
What is a Python \(\texttt{iterator}\)? An \(\texttt{iterator}\) is an object that implements the \(\texttt{__iter__()}\) and \(\texttt{__next__()}\) methods to iterate over a sequence.
What is a Python generator expression?
A generator expression creates a generator in a single line, which is an iterator that yields values lazily. Example:
for val in gen:
print(val)
What is polymorphism in Python?
Polymorphism allows the same interface to be used for different data types. Example:
\(\texttt{len('abc')}\) and \(\texttt{len([1, 2, 3])}\).
What is abstraction in Python? Abstraction hides implementation details and only exposes the necessary features. Example: using abstract base classes with \(\texttt{abc}\).
What is a \(\texttt{try-except-else}\) block in Python? The \(\texttt{else}\) block runs if no exception occurs in the \(\texttt{try}\) block.
What does \(\texttt{raise}\) do in Python?
The \(\texttt{raise}\) statement manually triggers an exception. Example:
\(\texttt{raise ValueError('Invalid input')}\).
What is \(\texttt{deque}\) in Python? \(\texttt{deque}\) is a double-ended queue from the \(\texttt{collections}\) module that supports fast appends and pops.
What is itertools, and why is it useful?
The itertools library provides tools for creating iterators for efficient looping and combinatorial tasks. Example:
# Generate all combinations of 2 elements
combinations = itertools.combinations([1, 2, 3], 2)
for combo in combinations:
print(combo)
How do you convert a \(\texttt{list}\) to a \(\texttt{set}\)?
Use the \(\texttt{set()}\) constructor. Example:
\(\texttt{set([1, 2, 2, 3])}\) returns \(\texttt{{1, 2, 3}}\).
How do you exit a loop prematurely? Use the \(\texttt{break}\) statement to exit the loop.
What is a \(\texttt{pass}\) statement in Python?
The \(\texttt{pass}\) statement is a placeholder that does nothing. Example:
\(\texttt{if condition: pass}\).
What are \(\texttt{nested functions}\) in Python?
Nested functions are functions defined inside other functions. Example:
\(\texttt{def outer():}\)
\(\texttt{ def inner(): print('Inner')}\).
What is the \(\texttt{isinstance()}\) function in Python? The \(\texttt{isinstance()}\) function checks if an object is an instance of a specified class or a subclass. Example: \(\texttt{isinstance(10, int)}\) returns \(\texttt{True}\).
How do you create a multiline string in Python?
Use triple quotes (`'''` or `"""`). Example:
a multiline string.'''
What is the difference between \(\texttt{pop()}\) and \(\texttt{remove()}\) in a list?
\(\texttt{pop()}\) removes an item by index and returns it, while \(\texttt{remove()}\) removes the first matching value. Example:
\(\texttt{my\_list.pop(0)}\) vs \(\texttt{my\_list.remove('value')}\).
How do you sort a list in Python? Use \(\texttt{sorted()}\) for a new sorted list or \(\texttt{list.sort()}\) to sort in place. Example: \(\texttt{sorted([3, 1, 2])}\) returns \(\texttt{[1, 2, 3]}\).
What is \(\texttt{random}\), and how do you generate a random number? The \(\texttt{random}\) module generates random numbers. Example: \(\texttt{random.randint(1, 10)}\) returns a random integer between 1 and 10.
What is \(\texttt{time}\), and how is it used? The \(\texttt{time}\) module provides time-related functions. Example: \(\texttt{time.sleep(1)}\) pauses the program for 1 second.
What is recursion in Python?
Recursion occurs when a function calls itself to solve smaller instances of the same problem. Example:
return 1 if n == 0 else n * factorial(n-1)
print(factorial(5)) # Output: 120
How do you create a function with a variable number of arguments?
Use \(\texttt{*args}\) for positional arguments and \(\texttt{**kwargs}\) for keyword arguments. Example:
\(\texttt{def func(*args, **kwargs): pass}\).
What is an \(\texttt{AssertionError}\) in Python?
An \(\texttt{AssertionError}\) occurs when an \(\texttt{assert}\) statement fails. Example:
\(\texttt{assert 2 + 2 == 5}\) raises \(\texttt{AssertionError}\).
How do you define a custom exception in Python?
Create a new class that inherits from \(\texttt{Exception}\). Example:
\(\texttt{class MyException(Exception): pass}\).
What is a descriptor in Python?
A descriptor is an object with `__get__()`, `__set__()`, and `__delete__()` methods to control attribute access. Example:
def __get__(self, instance, owner):
return 'value'
class MyClass:
attr = Descriptor()
obj = MyClass()
print(obj.attr) # Triggers __get__
What is the purpose of \(\texttt{global}\) in Python? The \(\texttt{global}\) keyword declares a variable as global, allowing it to be modified inside a function.
How do you create a shallow copy of a list? Use slicing or the \(\texttt{copy()}\) method. Example: \(\texttt{list\_copy = my\_list[:]}\).
What is the difference between \(\texttt{set.add()}\) and \(\texttt{set.update()}\)?
\(\texttt{set.add()}\) adds a single element, while \(\texttt{set.update()}\) adds multiple elements. Example:
\(\texttt{my\_set.add(1)}\) vs \(\texttt{my\_set.update([2, 3])}\).
What is \(\texttt{json}\), and how do you use it? \(\texttt{json}\) is a module for working with JSON data. Example: \(\texttt{json.dumps()}\) converts a Python object to JSON format.
How do you open a file in Python?
Use the `open()` function to open a file. Example:
data = f.read()
print(data)
What is the difference between \(\texttt{if-elif-else}\) and multiple \(\texttt{if}\) statements? Use \(\texttt{if-elif-else}\) for mutually exclusive conditions. Multiple \(\texttt{if}\) statements can all execute if their conditions are true.
How do you iterate over a dictionary?
Use `for key, value in dict.items()` to iterate over a dictionary. Example:
for k, v in my_dict.items():
print(k, v)
What is Python's @property decorator?
The @property decorator defines a method as a property, allowing it to be accessed like an attribute. Example:class MyClass:
@property
def value(self):
return 42
obj = MyClass()
print(obj.value) # Accessing value as an attribute
What is a \(\texttt{weakref}\) in Python? A \(\texttt{weakref}\) allows access to an object without increasing its reference count, useful for cache management.