0% found this document useful (0 votes)
12 views

Python Flashcards V2

Uploaded by

madow58340
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Python Flashcards V2

Uploaded by

madow58340
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 13

What does `\\` signify in Python?

,"It indicates that the following character is an


escape sequence."
How does Python perform type hinting?,"By specifying data types for function
parameters, e.g., `def multiply(num: int) -> int:`."
Explain the use of the formatted print function in Python.,"Allows direct variable
insertion in strings, e.g., `print(f"text {variable}")`."
What is chaining of functions and methods?,"Combining methods on variables, e.g.,
`a = a.strip().title()` for strip and title cases."
How does `range()` work in Python?,"Generates sequences but does not accept floats
as arguments."
What does unpacking mean in Python?,"Assigning elements of a container to multiple
variables, e.g., `x, y, z = (1, 2, 3)`."
What is match-case in Python?,"A concise tool for handling conditions, replacing
elif chains, e.g., `match status: case 200`."
What is the purpose of type hinting?,"Type hinting specifies expected data types,
improving readability and debugging."
What are first-class functions?,"Functions that Python treats as objects, allowing
them to be passed, returned, and stored."
How does Python handle multiple constructors?,"By using `@classmethod`, as Python
does not support direct method overloading."
What is name mangling?,"Using `__` prefix to make attributes harder to access
outside the class."
How is a docstring used?,"Docstrings provide documentation for functions, e.g.,
`"""This function calculates the area."""`."
What does the `finally` clause do?,"Ensures cleanup actions execute, regardless of
exceptions, in a try block."
How is `else` used in loops?,"Runs when the loop ends naturally, but not if a
`break` occurs."
Explain list comprehension for filtering.,"Provides a filtered list, e.g., `[x for
x in vec if x >= 0]` for non-negatives."
What is set comprehension?,"Set comprehension avoids duplicates, e.g., `{x for x in
'aabb'}` gives `{'a', 'b'}`."
Describe dictionary comprehension.,"Generates key-value pairs, e.g., `{x: x**2 for
x in (2, 4, 6)}` gives `{2: 4, 4: 16, 6: 36}`."
What does `__init__()` do in Python classes?,"Initializes class variables, e.g.,
`def __init__(self, name): self.name = name`."
Explain method overriding in classes.,"Child classes redefine methods from parent
classes, e.g., reimplementing `flight()` in a subclass."
What is encapsulation?,"Encapsulation restricts access to variables using naming
conventions like `__var`."
Describe data abstraction in Python.,"Data abstraction hides internal details,
using `_` or `__` prefixes for variable protection."
What is `__del__()` used for?,"Removes an object and all references to it, freeing
memory."
What does `__add__` do?,"Customizes the behavior of `+` for user-defined objects,
implementing addition."
How does `__repr__` differ from `__str__`?,"`__repr__` provides developer-friendly
output, `__str__` is end-user-friendly."
What does `map()` do?,"`map()` applies a function to each item in a container,
e.g., `map(lambda x: x*2, numbers)`."
What does `filter()` do?,"Selects elements based on a boolean function, e.g.,
filtering vowels from a string."
What is the purpose of `yield`?,"`yield` returns generator objects, keeping
function state for the next execution."
Explain `*args` and `**kwargs` usage.,"`*args` allows variable-length arguments,
`**kwargs` passes named arguments as a dictionary."
What does the walrus operator `:=` do?,"Assigns variables within expressions, e.g.,
`while (chunk := file.read(200)):`."
What is a decorator?,"A function that modifies another function with wrappers,
e.g., `@count_calls` to track calls."
How is `random.choice()` different from `random.shuffle()`?,"`choice()` picks one
item, `shuffle()` rearranges all items."
What does `OrderedDict` provide?,"Maintains element order based on insertion,
unlike regular dictionaries."
Explain `itertools.permutations()` usage.,"Generates all arrangements for container
elements, e.g., `permutations('abc')`."
What does `re.sub()` do?,"Replaces matched patterns with a string, e.g.,
`re.sub(r'\\s', '_', text)`."
What is `reduce()` used for in functools?,"Applies functions cumulatively, e.g.,
summing values in a list with `reduce(lambda x, y: x + y, list)`."
What does `batched()` in itertools do?,"Groups elements in batches, e.g.,
`batched('ABCDEFG', n=3)` produces `['ABC', 'DEF', 'G']`."
How does the `join()` function work on containers?,"Combines container items into a
single string, e.g., `'-'.join(['a', 'b', 'c'])` gives `a-b-c`."
What does `starmap()` do?,"Applies functions to container elements with tuple-form
arguments, e.g., `starmap(f, [(1,2), (3,4)])`."
How are closures used in Python?,"Closures store a function and its environment,
allowing out-of-scope execution."
What does `str.format()` do?,"Inserts variables into strings without requiring
formatting, e.g., `'{0} and {1}'.format('a', 'b')`."
What is a lambda expression?,"An inline function that returns output without
`return`, e.g., `lambda x, y: x - y`."
What is `__slots__`?,"A special mechanism to reduce memory usage by fixing
attributes in a class."
What is a comprehension in Python?,"A way to create lists, sets, or dictionaries in
a single line, e.g., `[x for x in range(5)]`."
How does `enumerate()` work?,"Adds an index to an iterable, e.g., `enumerate(['a',
'b'])` produces `(0, 'a'), (1, 'b')`."
Explain the `__call__` method.,"Allows an instance to be called as a function,
using `object()` syntax."
What does the `time.perf_counter()` function do?,"Measures the execution time of
code blocks precisely."
How does `with` work for files?,"Automatically closes files after use, simplifying
file handling."
What is the difference between `any()` and `all()`?,"`any()` checks if any element
is true, `all()` checks if all elements are true in an iterable."
How does the `setdefault()` method work?,"Inserts a key with a default value if it
is not already present in a dictionary."
What does the `Counter` class in collections do?,"Counts hashable objects,
returning a dictionary of item counts."
What are magic methods in Python?,"Special methods with double underscores (e.g.,
`__init__`) that provide extra functionality to classes."
How is method resolution order (MRO) handled?,"Defines the sequence in which
methods are inherited, using C3 linearization."
What does the `assert` keyword do?,"Used to test expressions, raising an error if
the expression is false."
Explain the `@property` decorator.,"Makes class attributes accessible as
properties, without parentheses."
How do `__iter__` and `__next__` work?,"Turn objects into iterables, with
`__next__` providing each item sequentially."
What is `zip()` used for?,"Combines multiple iterables into tuples, e.g., `zip([1,
2], ['a', 'b'])` gives `[(1, 'a'), (2, 'b')]`."
How does `deque` differ from a list?,"`deque` allows faster appends/pops from both
ends, making it suitable for queue operations."
What is a metaclass in Python?,"Defines the behavior of classes and is used in
class creation, like a class factory."
Explain `@classmethod` and `@staticmethod`.,"`@classmethod` takes `cls` parameter;
`@staticmethod` does not need any class or instance reference."
How does `str.split()` work?,"Divides a string by a specified separator into a list
of substrings."
Explain list slicing syntax.,"Accesses a portion of a list using
`list[start:stop:step]` syntax."
What does `math.floor()` do?,"Rounds a number down to the nearest integer."
What is `@functools.lru_cache`?,"Caches function results to speed up calls with the
same arguments."
Explain dictionary comprehensions with example.,"Creates dictionaries concisely,
e.g., `{x: x**2 for x in (2, 4, 6)}`."
How does `heapq` work in Python?,"Implements a priority queue for fast access to
the smallest item."
What is `re.search()` used for?,"Finds the first instance of a regex pattern in a
string."
What is the `repr()` function for?,"Provides a developer-oriented representation of
an object."
How is `pop()` used with dictionaries?,"Removes a key-value pair by key, returning
the value or an optional default."
Explain the role of `sys.argv` in command-line arguments.,"Provides a list of
arguments passed to a Python script from the command line."
What does `round()` do in Python?,"Rounds a number to the nearest integer or
specified decimal places."
What is `datetime.now()` used for?,"Returns the current local date and time."
How does the `and` operator work in Python?,"Evaluates expressions left to right
and returns the first falsy value or the last value."
What does the `or` operator return?,"Evaluates expressions left to right, returning
the first truthy value or the last value."
Explain `try-except` with example.,"Handles exceptions, allowing code to proceed
when errors occur."
What is the purpose of `del` keyword?,"Deletes variables, list items, or object
attributes."
What does `abs()` function return?,"Returns the absolute value of a number."
How do you define a global variable inside a function?,"Using the `global` keyword
before the variable name."
What is a syntax error in Python?,"Occurs when code violates Python’s syntax
rules."
Explain the `is` operator.,"Checks if two variables point to the same object."
What is the `not` operator?,"Inverts the boolean value of an expression."
What is the difference between `list` and `tuple` in Python?,"Lists are mutable,
meaning they can be changed after creation, while tuples are immutable."
How does Python handle variable scope in functions?,"Python has local, enclosing,
global, and built-in scopes, where variables are resolved in the LEGB order."
What are lambda functions in Python?,"Lambda functions are anonymous, one-line
functions using syntax: `lambda parameters: expression`."
Explain Python's `map()` function with lambda functions.,"`map()` applies a
function to all items in an iterable, e.g., `map(lambda x: x*2, [1, 2, 3])`."
What does the `filter()` function do?,"Filters an iterable based on a condition,
e.g., `filter(lambda x: x > 5, [3, 6, 9])` returns `[6, 9]`."
How does list comprehension improve readability?,"List comprehensions condense
loops into a single line, e.g., `[x**2 for x in range(5)]` for squares."
Describe `dict.get()` method in Python.,"Fetches a value for a specified key,
returning `None` (or default) if key is absent."
What is a set and how does it differ from a list?,"Sets are unordered collections
of unique elements, while lists allow duplicates and preserve order."
Explain the use of `add()` in sets.,"Adds an element to a set, with no effect if it
already exists in the set."
What are frozen sets?,"Frozen sets are immutable sets that prevent modification,
created using `frozenset()`."
What is the `@property` decorator?,"Converts a method into a property, allowing
access to it without calling it as a function."
How does `isinstance()` function work?,"Checks if an object is an instance of a
class or tuple of classes, e.g., `isinstance(3, int)` returns `True`."
Explain Python’s garbage collection mechanism.,"Python automatically reclaims
memory of unreachable objects, managed by reference counting and cyclic GC."
What does the `copy` module do in Python?,"Supports shallow and deep copying of
objects with `copy.copy()` and `copy.deepcopy()`."
What is method resolution order (MRO)?,"Determines the order in which base classes
are searched when inheriting attributes, using the C3 linearization algorithm."
Explain inheritance in Python with example.,"Inheritance allows a class to inherit
attributes from another, e.g., `class Dog(Animal):` inherits from `Animal`."
What is method overriding?,"When a subclass provides a specific implementation of a
method already defined in its superclass."
How is encapsulation achieved in Python?,"By using single `_` for protected and
double `__` for private variables."
What is the difference between protected and private variables?,"Protected
variables `_var` are accessible in subclasses, while private variables `__var` are
not."
Describe `@classmethod` and `@staticmethod` with example.,"`@classmethod` takes
`cls` and accesses class attributes; `@staticmethod` doesn’t access class or
instance."
Explain `super()` function in inheritance.,"Calls a parent class method, e.g.,
`super().method()` calls the superclass `method()`."
What are magic methods?,"Special methods with `__` (like `__init__`, `__str__`)
providing built-in behaviors for custom classes."
What does `__str__` do?,"Defines a string representation for an object when
`print(object)` is called."
Explain the `__call__` method.,"Allows an instance to be called like a function,
e.g., `obj()` if `__call__` is defined in the class."
How does `__iter__` and `__next__` work in iterators?,"`__iter__()` returns the
iterator object; `__next__()` returns the next item and raises `StopIteration` when
done."
What are Python generators?,"Functions using `yield` to produce items one at a
time, allowing iteration without creating the whole list."
What are decorators in Python?,"Functions that add functionality to other
functions, e.g., `@my_decorator` above a function."
What does `functools.wraps()` do in decorators?,"Preserves the original function's
metadata when wrapped by a decorator."
What is a metaclass?,"A class of classes defining how classes behave, created with
`type` or by inheriting from `type`."
What is an abstract class?,"A class with one or more abstract methods, defined
using `ABC` from `abc` module."
Explain context managers and the `with` statement.,"Manage resources (like files),
ensuring proper acquisition and release, e.g., `with open(file) as f:`."
What is `itertools.chain()`?,"Combines multiple iterables into a single iterable,
e.g., `chain([1, 2], [3, 4])` produces `1, 2, 3, 4`."
Describe `itertools.groupby()`.,"Groups items in an iterable based on a key
function, useful for grouping sorted data."
Explain `itertools.cycle()`.,"Cycles through an iterable indefinitely, e.g.,
`cycle([1, 2, 3])` repeats `1, 2, 3` endlessly."
What is the purpose of `collections.Counter`?,"Counts elements in an iterable,
returning a dictionary of elements and their frequencies."
How does `heapq` work in Python?,"Implements a min-heap for efficient access to the
smallest item, often used in priority queues."
What does `time.time()` do?,"Returns the current time in seconds since the epoch
(usually Unix timestamp)."
What is the `datetime` module used for?,"Supports date and time manipulation, e.g.,
`datetime.datetime.now()` gives the current date and time."
Explain `random.randint(a, b)`.,"Generates a random integer between `a` and `b`,
inclusive."
What is `json.dumps()`?,"Serializes a Python object to a JSON formatted string."
Explain `json.loads()`.,"Parses a JSON string into a Python dictionary or list."
How does `re.match()` differ from `re.search()`?,"`re.match()` checks for a match
only at the beginning, while `re.search()` checks throughout the string."
What does `re.findall()` return?,"Returns all non-overlapping matches of a pattern
in a list."
Explain the `re.compile()` function.,"Compiles a regex pattern for faster reuse,
e.g., `pattern = re.compile(r'\\d+')`."
What is the `subprocess` module used for?,"Runs external commands and pipelines
within Python code."
Describe the `os.path` module.,"Provides functions to manipulate file paths, like
`os.path.join()` and `os.path.exists()`."
What does `sys.exit()` do?,"Exits from the Python interpreter or script, optionally
with a status code."
What is `argparse` used for?,"Creates command-line interfaces by parsing command-
line arguments, e.g., `argparse.ArgumentParser()`."
Explain `@functools.lru_cache`.,"Caches results of expensive function calls to
improve performance on repeated inputs."
How does `enumerate()` function work?,"Adds an index to an iterable, useful in
loops for both index and value access."
What does `zip()` do?,"Combines multiple iterables into pairs of tuples, stopping
at the shortest iterable."
What is `deepcopy` in the `copy` module?,"Creates a fully independent copy of
nested objects."
How does `__getattr__` work?,"Called when an attribute is not found in an instance,
useful for dynamic attribute handling."
Explain `pickle` in Python.,"Serializes objects to a byte stream for storage or
transmission and deserializes them back."
What does `gc.collect()` do?,"Explicitly runs the garbage collector to free up
memory by reclaiming unreachable objects."
Describe `traceback` module.,"Used for retrieving, formatting, and printing error
traceback information."
What does `@dataclass` decorator provide?,"Generates common methods like `__init__`
and `__repr__` for classes automatically."
Explain `weakref` in Python.,"Allows reference to objects without increasing
reference count, avoiding memory leaks."
What is the `collections.deque` used for?,"Efficient double-ended queue that
supports appends and pops from both ends."
How does the `hash()` function work?,"Returns a hash value of an object for use in
hashing-based structures like dictionaries."
Explain `__eq__` and `__lt__` methods.,"Define equality (`==`) and less-than (`<`)
comparison operations in custom classes."
What does `__getitem__` allow?,"Customizes item access using square brackets, e.g.,
`object[index]`."
How does `property()` function work?,"Creates managed attributes that can use
getter, setter, and deleter methods."
What are `__setitem__` and `__delitem__` used for?,"Define setting and deleting
item behavior in custom container classes."
What is `TypeError` in Python?,"An exception raised when an operation or function
is applied to an object of inappropriate type."
Explain `AttributeError` with example.,"Raised when an attribute reference or
assignment fails, e.g., accessing an undefined attribute."
How does `IndexError` occur?,"Raised when a sequence subscript is out of range,
like accessing an index beyond list length."
What is the purpose of `KeyError`?,"Raised when a dictionary key is not found, like
`dict['nonexistent_key']`."
Describe `ZeroDivisionError`.,"Raised when a division or modulo operation has a
zero divisor."
What is `ValueError`?,"Occurs when a function receives an argument of the right
type but with an inappropriate value."
How is `AssertionError` raised?,"Triggered by a failed assert statement, e.g.,
`assert x > 0` when `x` is not positive."
Explain the `raise` statement.,"Used to manually trigger exceptions in code, e.g.,
`raise ValueError('Invalid')`."
How does `is` operator differ from `==`?,"`is` checks for object identity; `==`
checks for value equality."
What is `__main__`?,"The scope where top-level code runs, useful in `if __name__ ==
'__main__':` for script entry."
Explain the difference between `break` and `continue`.,"`break` exits the loop,
while `continue` skips to the next iteration."
How does `global` keyword work?,"Declares a variable global, allowing it to be
modified outside its local scope."
What is `nonlocal` used for?,"Accesses a variable from an enclosing (non-global)
scope in nested functions."
Describe Python's `pass` statement.,"A no-op, commonly used as a placeholder in
code blocks."
Explain use of `async` and `await`.,"Keywords for defining and managing
asynchronous operations in Python."
What does `await` do in async functions?,"Pauses function execution until a
specified task completes."
What is `AsyncIO`?,"Python's library for writing asynchronous code, allowing for
concurrent execution."
Explain the use of `__slots__`.,"Defines a fixed set of attributes, reducing memory
usage by avoiding dictionaries."
What is type hinting?,Type hinting is used to indicate the expected data types for
function arguments.
What does chaining of functions mean?,"It allows methods to be called in
succession, e.g., a = a.strip().title()."
How do you use formatted print in Python?,Use print(f'text {variable}') for string
interpolation.
What is unpacking?,"Assignment of multiple variables to elements in a container,
e.g., x, y, z = (Item1, Item2, Item3)."
Does range() accept floats?,"No, `range()` does not accept floats as arguments."
What are first-class objects in Python?,"Functions that can be assigned to
variables, passed as arguments, or returned from another function."
How can functions be stored?,"Functions can be stored in variables, dictionaries,
or lists."
Explain method overloading in Python.,Python does not support method overloading;
only the latest constructor in the code will be considered.
What are docstrings?,Docstrings are a concise summary of a function's purpose.
How does Python handle garbage collection?,Python automatically recollects memory
occupied by unreachable objects.
What is a match-case statement?,A match-case can be used instead of else-if
statements.
Provide an example of match-case usage.,def http_error(status): match status: case
400: return 'Bad request'.
What is the purpose of the finally clause?,The finally clause runs regardless of
whether an exception was raised.
How do you use an else block in loops?,The else block runs when the loop completes
normally without a break.
What is the zip() function?,Zip() is used to combine multiple iterables into
tuples.
How can you transpose a matrix using zip()?,Use zip(*matrix) to transpose a matrix.
What is list comprehension?,"A concise way to create lists based on existing lists,
e.g., [x for x in range(10)]."
What is the output of using reversed() in a loop?,It iterates through the items in
reverse order.
How can you use sorted() in Python?,sorted() returns a new sorted list from the
elements of any iterable.
What are formatted strings for minimum field length?,Specify minimum field length
using `:` inside `{}` after the variable name.
How do you round numbers in formatted strings?,Use math.pi:.3f to round the value
of pi to three digits.
How can you join strings in Python?,"Use `'-'.join(('1', '2', '3'))` to join
strings with a specified separator."
What is the str.format() method?,str.format() can substitute variables without
needing to declare them.
What does str.format() allow with keywords?,Allows positional and keyword arguments
to be combined freely.
How do you use dictionaries in str.format()?,You can use `{key}` to access
dictionary values directly within format.
What is the purpose of the popitem() method?,It removes and returns the last
inserted key-value pair from a dictionary.
How do you initialize a class in Python?,Use the __init__() method to initialize
class variables.
What is method overriding?,It's when a child class implements a method differently
than its parent class.
What does __slots__ do in a class?,__slots__ reduces memory usage by limiting
dynamically created attributes.
How do you access protected members in a subclass?,Protected members can be
accessed using `_ClassName__member` syntax.
Explain the purpose of __del__ method in Python.,It undefines the variable
name/reference name of an object when it is deleted.
What is the use of nonlocal keyword?,The nonlocal keyword allows you to modify a
variable in an outer (but non-global) scope.
How do decorators work in Python?,Decorators modify the functionality of a function
without changing its code.
What are regular expressions in Python?,"They are sequences of characters defining
a search pattern, used with the re module."
Provide an example of the findall() function.,"re.findall(r'[aeiou]', 'The quick
brown fox') returns all vowels."
What does re.search() do?,It searches for the first occurrence of a pattern in a
string.
What is the purpose of the re.sub() function?,It replaces occurrences of a pattern
with a replacement string.
What is the time complexity of filter()?,The time complexity of filter() is O(n).
How do you apply the map() function?,"Use map(function, container) to apply a
function to all items in an iterable."
What is a lambda function?,A lambda function is an anonymous function defined using
the `lambda` keyword.
What is the significance of yield in a generator?,"Yield returns a value and pauses
the function, resuming on the next call."
Explain the purpose of functools.reduce().,It applies a binary function
cumulatively to items in a iterable.
What is the role of iter() and next()?,"iter() converts an iterable into an
iterator, while next() retrieves the next item."
What does the any() function do?,It checks if any element of the argument container
is True.
What is the __future__ module?,It allows the use of features from future Python
versions.
How can you handle exceptions in Python?,Use try-except or try-except-finally to
manage exceptions.
What is the significance of the walrus operator?,The walrus operator (`:=`) allows
assignment within expressions.
What are *args and **kwargs?,"*args allows for passing a variable number of
arguments, while **kwargs allows for variable keyword arguments."
What is the use of the collections module?,"It provides specialized container data
types, like namedtuple and deque."
What does the itertools module provide?,It provides functions that return iterators
which operate on tuples and other sequences.
What is the role of the time module?,"The time module provides functions to work
with time, including delays and performance measurement."
What is the random module used for?,It provides functions to generate random
numbers and perform random selections.
How do you implement a closure in Python?,By defining a nested function that
captures variables from the enclosing scope.
How is inheritance implemented in Python?,"Inheritance is implemented by passing
the parent class in parentheses during class definition, e.g., class
Child(Parent)."
What is the key concept of encapsulation?,Encapsulation restricts access to certain
attributes or methods to safeguard from unwanted modifications.
Explain data abstraction in Python.,Data abstraction is hiding the complex reality
while exposing only the necessary parts.
What is an OrderedDict?,An OrderedDict remembers the order in which items were
inserted.
How do you define a static method?,Use the @staticmethod decorator to define a
static method in a class.
What is the purpose of the count_calls decorator?,It counts and prints the number
of times a function is called.
What is the difference between a module and a package?,"A module is a single file,
while a package is a collection of modules in a directory."
How to create a package in Python?,"To create a package, create a directory
containing an __init__.py file."
What are the key features of the Python programming language?,"Easy to read syntax,
interpreted, dynamic typing, extensive libraries."
How can you improve memory efficiency in Python?,Utilize techniques like using
tuples instead of lists and properly managing variable scopes.
What does the strftime() function do?,It formats date objects into readable strings
according to specified formats.
How can multiple exceptions be handled?,You can handle multiple exceptions in a
single except block using a tuple.
What is the difference between == and is?,"== checks for value equality, while is
checks for identity (same object)."
How can you check if a key exists in a dictionary?,"Use the in keyword, e.g., `if
key in dictionary:`."
What does the pop() method do in a list?,The pop() method removes and returns the
element at a specific index or from the end if not specified.
What is a binary tree?,A binary tree is a hierarchical data structure in which each
node has at most two children.
Explain the LRU Cache concept.,An LRU cache stores a limited number of items and
evicts the least recently used when the limit is reached.
What is regex for email validation?,A common regex for email validation: r'^[\w\.-]
+@[\w\.-]+\.\w+$'.
What is the difference between deep copy and shallow copy?,"A shallow copy creates
a new object but inserts references into it, while a deep copy creates a new object
and recursively inserts copies of the nested objects."
What does the self keyword represent?,The self keyword is used to represent the
instance of the class.
In what situation should you use a list over a tuple?,Use a list when you need a
mutable sequence; use a tuple for immutable sequences.
What is the benefit of using list comprehensions?,List comprehensions provide a
concise way to create lists and can improve performance.
What is the role of a function as a parameter?,Functions can be passed as arguments
to other functions for higher-order programming.
How is an empty class defined in Python?,An empty class can be defined using `class
MyClass: pass`.
How do you implement error handling in Python?,Use try-except blocks to catch and
handle exceptions gracefully.
What code will raise an exception when executed?,Trying to divide by zero like `1 /
0` will raise a ZeroDivisionError.
What is the significance of the if __name__ == '__main__' statement?,It allows or
prevents parts of code from being run when the modules are imported.
What is a Python list?,"A list is a mutable, ordered collection of elements,
defined using square brackets."
What is the significance of the init method in a class?,The __init__ method is the
constructor that initializes instance variables when an object is created.
What is Python's interactive mode?,"It allows you to execute Python commands
directly in the terminal, providing immediate feedback."
How do you convert a list to a set?,"Use the set() function, e.g., my_set =
set(my_list)."
What are the key characteristics of Python?,"Interpreted, high-level, dynamically
typed, and multi-paradigm."
What is a context manager?,A context manager is used to allocate and release
resources precisely using the with statement.
What does enumerate() return?,It returns an iterator that produces pairs of index
and value from an iterable.
What is the use of the property() function?,It allows you to set custom getters and
setters for class attributes.
What is the purpose of assert statements?,"They are used for debugging, to test
conditions that must be True."
How do you create a virtual environment?,Use the command python -m venv env_name to
create a virtual environment.
What is the significance of the __name__ variable?,"It holds the name of the
module; if the module is run directly, it is set to '__main__'."
How can you check the memory size of an object?,Use the sys.getsizeof() function
from the sys module.
What is a generator expression?,A compact way to create a generator without
defining a separate function using () instead of [].
How do you use a try-except block to catch a specific exception?,Use `try: ...
except SpecificException: ...` format to handle a specific error type.
How do you format strings using f-strings?,Use f'Your string here {variable}' to
embed expressions inside string literals.
Explain multi-threading in Python.,"Multi-threading allows concurrent execution of
threads, enabling efficient resource utilization."
What is the use of the random.choice() function?,It selects a random element from a
non-empty sequence.
What is a classmethod?,"A method that is bound to the class and not the instance,
defined using the @classmethod decorator."
What does the isinstance() function do?,It checks if an object is an instance of a
specified class or a tuple of classes.
What is the purpose of the CSV module?,The CSV module provides functionality to
read from and write to CSV files easily.
What does the exec() function do?,It executes the given string as a Python command.
How do you merge two dictionaries in Python?,"Use the `**` unpacking operator,
e.g., merged = {**dict1, **dict2}."
What does list slicing do?,List slicing allows you to extract portions of a list
based on index ranges.
How can you generate a random integer within a range?,"Use random.randint(start,
end) to get a random integer between start and end, inclusive."
What is the purpose of the functools module?,It provides higher-order functions
that operate on or return other functions.
What does the timeit module do?,It measures the execution time of small code
snippets for performance optimization.
How can you handle non-ASCII characters in strings?,Use UTF-8 encoding and the
encode() method to handle various character sets.
What is the purpose of the __str__ method?,The __str__ method provides a user-
friendly string representation of an object.
How can you remove duplicates from a list?,"Convert the list to a set and back to a
list, `list(set(my_list))`."
What is a decorator in Python?,"A decorator is a function that takes another
function as an argument, enhancing its behavior."
How does exception handling improve code quality?,"It allows for graceful
degradation and error management, avoiding program crashes."
What does the sys.argv list contain?,It contains the command-line arguments passed
to a Python script.
How do you check if a string is empty?,Use `if not my_string:` to check if the
string is empty.
What is the purpose of try-except-else blocks?,The else block executes if the try
block does not raise an exception.
How can you copy a file in Python?,"Use the shutil.copy(src, dst) function from the
shutil module."
What is the role of the `with` statement?,It simplifies exception handling by
encapsulating common preparation and cleanup tasks.
What is the difference between '==' and 'is' operators in Python?,== checks for
value equality; is checks for object identity.
Explain the significance of the global keyword.,The global keyword allows you to
modify a global variable inside a function.
What does the method `str.split()` do?,It splits a string into a list based on a
specified delimiter.
How do you sort a dictionary by its values?,"Use sorted(dict.items(), key=lambda
item: item[1]) to sort by values."
What is the difference between a list and a tuple?,Lists are mutable while tuples
are immutable.
How do you implement polymorphism in Python?,By defining methods in multiple
classes with the same name but different implementations.
What does the round() function do?,It rounds a number to a specified number of
decimal places.
What is the significance of the main() function?,It typically serves as the entry
point for a Python program when executed directly.
How do you remove leading/trailing whitespace from a string?,Use the .strip()
method to trim whitespace from both ends.
What are iterators in Python?,Iterators are objects that allow traversal through a
collection without exposing its underlying structure.
How do you convert a list into a dictionary?,Use the dict() constructor with zip()
to create key-value pairs from two lists.
What is the output of [x**2 for x in range(5)]?,"The output is [0, 1, 4, 9, 16]."
What is the time complexity of dictionary lookups?,The average time complexity is
O(1) due to hash table implementation.
What is the purpose of the map() function?,map() applies a specified function to
each item in an iterable.
How can you create a new list from an existing list while applying a
transformation?,"Use list comprehension, e.g., [transform(x) for x in
existing_list]."
What does the os.remove() function do?,It deletes a file specified by a path.
What are global and local variables?,Global variables are accessible throughout the
entire program; local variables are confined to the scope of a function.
How do you convert a string to uppercase?,"Use the .upper() method, e.g.,
my_string.upper()."
What is the role of the shutil module?,"It provides functions to manage files and
directories, including copying and moving."
What is a subscript out of range error?,It occurs when trying to access an index in
a sequence that does not exist.
How can you create a shallow copy of an object?,Use the copy() method or the `copy`
module.
What is type casting?,"Type casting is converting one data type to another, e.g.,
from string to integer."
What are the methods available to check if a variable is iterable?,Use the
`isinstance()` function with collections.abc.Iterable.
What is the behavior of the break statement in nested loops?,It exits only the
innermost loop where the break statement is called.
How can you sort a list in Python?,Use the sort() method to sort the list in place
or sorted() to return a new sorted list.
What is a key in a dictionary?,A key is a unique identifier used to access a value
within a dictionary.
How do you remove a key from a dictionary?,Use the del statement or the pop()
method.
What is the difference between mutable and immutable types?,"Mutable types can be
changed (like lists), immutable types cannot (like strings)."
How do you create an empty dictionary?,Use {} or dict() to create an empty
dictionary.
What does the __init__ method do?,It initializes the class when an instance of the
class is created.
What are instance variables?,Instance variables are variables that are bound to the
instance of a class.
How do you define a method in a class?,Define a method inside a class using the def
keyword followed by the method name.
What is the purpose of the self parameter?,The self parameter refers to the
instance of the class and is used to access variables that belong to the class.
What is method chaining in Python?,"Calling multiple methods on the same object in
a single line, e.g., a.method1().method2()."
How is a function defined in Python?,Use the def keyword followed by the function
name and parentheses.
What are default parameters in a function?,Default parameters are values assigned
to parameters if no value is provided during the function call.
How do you handle multiple exceptions?,Use a single except clause with multiple
exception types in parentheses.
What is a comprehension in Python?,"A comprehension is a syntactic construct for
creating a new list, set, or dictionary from an existing iterable."
How do you reverse a string in Python?,Use slicing: my_string[::-1] or the
reversed() function.
What does the input() function do?,It reads a line of text from the user input.
What is the difference between string and bytes in Python?,String is a sequence of
characters; bytes is a sequence of bytes.
How can you convert an integer to a string?,"Use the str() function, e.g.,
str(10)."
How do you get the length of a list?,Use the len() function to get the length of a
list.
What is the purpose of the filter() function?,The filter() function applies a
function to an iterable and returns elements that evaluate to True.
What does the map() function return?,The map() function returns a map object
(iterator) containing the results of applying the function.
What is the role of the zip() function?,It combines two or more iterables into
tuples based on their index.
How do you combine two lists into a dictionary?,"Use the zip() function and dict(),
e.g., dict(zip(keys, values))."
What are positional-only parameters?,"Parameters that can only be specified by
position, not by keyword."
How do you define a private variable in a class?,"Use name mangling with two
leading underscores, e.g., __private_var."
What is the significance of the logging module in Python?,The logging module is
used for generating log messages for tracking events.
What command is used to install packages in Python?,Use pip install package_name to
install packages.
What is a generator function?,"A generator function uses yield to produce values
one at a time, preserving state between calls."
What does isinstance() do?,isinstance() checks if an object is an instance of a
specific class or a tuple of classes.
What are mutable types in Python?,"Mutable types can be modified after their
creation, e.g., lists, dictionaries."
What are immutable types in Python?,"Immutable types cannot be changed once
created, e.g., strings, tuples."
How can you check the presence of an item in a list?,"Use the `in` keyword, e.g.,
if item in my_list:."
What is the difference between shallow copy and deep copy?,"Shallow copy copies the
reference, deep copy creates a new separate copy."
How do you concatenate lists in Python?,Use the + operator or the extend() method
to concatenate two lists.
What does the time.sleep() function do?,The time.sleep() function pauses execution
for the given number of seconds.
How do you format a string with placeholders in Python?,Use the str.format() method
or f-strings for formatting.
What is duck typing?,Duck typing is a concept where the type or class of an object
is less important than the methods it defines.
What does the @property decorator do?,"It allows the method to be accessed like an
attribute, providing a getter for a class attribute."
How do you create a class in Python?,Use the class keyword followed by the class
name and a colon.
What does the assert statement do?,It tests a condition and raises an
AssertionError if the condition evaluates to False.
What is the life cycle of an object in Python?,"Creation, reference counting, and
garbage collection."
How can you create a custom exception in Python?,By subclassing the Exception class
to create a custom error type.
What is pickling?,Pickling is the process of serializing a Python object to a byte
stream.
What is unpickling?,Unpickling is the reverse process of converting a byte stream
back into a Python object.
What are Python's built-in data types?,"int, float, str, bool, list, tuple, set,
dict."
How can you check if a string contains only numeric characters?,Use the isdigit()
method.
What are keyword arguments in Python?,Keyword arguments are arguments that are
passed to a function by explicitly specifying their names.
How do you create a tuple in Python?,"Use parentheses, e.g., my_tuple = (1, 2, 3)."
What is the purpose of the __repr__ method?,It provides an unambiguous string
representation of an object for debugging.
How can you iterate through a dictionary?,"Use a for loop: for key, value in
dictionary.items():."
How do you implement a stack in Python?,Use a list and utilize append() for pushing
and pop() for popping items.
What is the purpose of a breakpoint in debugging?,A breakpoint pauses the execution
of the program at a specific line for inspecting the state.
What does the raise keyword do?,"It raises an exception, either specified directly
or re-raises the last exception caught."
How can you define a constant in Python?,"By convention, use uppercase letters for
variable names, e.g., PI = 3.14."
What is the purpose of the sys.exit() function?,It allows you to exit from Python
program or script.
What does the os module provide?,The os module provides a way of using operating
system-dependent functionality.
What is a class method?,A method that operates on the class itself rather than
instances of the class.
What does the @staticmethod decorator indicate?,It defines a method that does not
require access to the instance or class.
What is the difference between 'deep' and 'shallow' in data copying?,"Deep copies
duplicate the full structure, shallow copies replicate references."
What are the advantages of using a virtual environment?,Isolates package
installations from the system Python installation.
How do you create a simple class without attributes?,Use class MyClass: pass to
define an empty class.
What are default arguments in a function?,Default arguments provide a specified
value if no value is provided when called.
What is the purpose of the format specifier in strings?,"It allows you to format
strings in a specified way, including better readability."
How can you handle files in Python?,Use the open() function with a context manager
to handle file operations.
How do you check for a substring within a string?,"Use the `in` keyword, e.g., 'my'
in 'mystring'."
What does the random.sample() function do?,It returns a specified number of unique
elements chosen from a sequence.
What are positional arguments in a function?,Positional arguments are the arguments
that need to be passed in the correct order to the function.

You might also like