Beginner Flashcards
What is the default Python prompt of the interactive shell?
The default Python prompt is often seen for code examples which can be executed interactively in the interpreter.
What does an abstract base class (ABC) provide in Python?
ABCs provide a way to define interfaces and introduce virtual subclasses recognized by isinstance() and issubclass().
What is an annotation in Python?
A label associated with a variable, class attribute, or function parameter or return value, used as a type hint.
What are the two kinds of arguments in Python?
- Keyword argument
- Positional argument
What is an asynchronous context manager?
An object which controls the environment seen in an async with statement by defining __aenter__() and __aexit__() methods.
What is an asynchronous generator?
A function which returns an asynchronous generator iterator, defined with async def and containing yield expressions.
What is an asynchronous iterable?
An object that can be used in an async for statement and must return an asynchronous iterator from its __aiter__() method.
What is a callable in Python?
An object that can be called, possibly with a set of arguments, including functions, methods, and instances of classes with __call__().
What is the role of a callback in programming?
A subroutine function passed as an argument to be executed at some point in the future.
What is a class in Python?
A template for creating user-defined objects, typically containing method definitions.
What is a closure variable?
A free variable referenced from a nested scope that is defined in an outer scope.
What defines a complex number in Python?
A number expressed as a sum of a real part and an imaginary part, written with a j suffix, e.g., 3+1j.
What is a context manager?
An object that implements the context management protocol and controls the environment seen in a with statement.
What does the term ‘contiguous’ refer to in Python?
A buffer is considered contiguous if it is either C-contiguous or Fortran contiguous.
What is a coroutine?
A more generalized form of subroutines that can be entered, exited, and resumed at many different points.
What is the purpose of decorators in Python?
Functions that return another function, usually applied as a transformation using the @wrapper syntax.
What is a dictionary in Python?
An associative array where arbitrary keys are mapped to values, with keys being any object with __hash__() and __eq__().
What is a dictionary comprehension?
A compact way to process elements in an iterable and return a dictionary with the results.
What is a docstring?
A string literal that appears as the first expression in a class, function, or module, used for documentation.
What is duck-typing?
A programming style that emphasizes interfaces rather than specific types, allowing polymorphic substitution.
What does EAFP stand for?
Easier to ask for forgiveness than permission.
Fill in the blank: An _______ is an accumulation of expression elements that returns a value.
expression
What is an extension module?
A module written in C or C++, using Python’s C API to interact with the core and with user code.
What are f-strings in Python?
String literals prefixed with ‘f’ or ‘F’, known as formatted string literals.
What are expression elements?
Elements like literals, names, attribute access, operators or function calls which all return a value
Not all language constructs are expressions; statements like while and assignments are not expressions.
What are f-strings?
String literals prefixed with ‘f’ or ‘F’, short for formatted string literals
See also PEP 498.
Define a file object.
An object exposing a file-oriented API (with methods such as read() or write()) to an underlying resource.
What are the three categories of file objects?
- Raw binary files
- Buffered binary files
- Text files
Their interfaces are defined in the io module.
What is a file-like object?
A synonym for file object.
What is the filesystem encoding?
Encoding and error handler used by Python to decode bytes from the operating system and encode Unicode to the operating system.
What must the filesystem encoding guarantee?
To successfully decode all bytes below 128.
How can you get the filesystem encoding and error handler?
Using sys.getfilesystemencoding() and sys.getfilesystemencodeerrors() functions.
What is a finder in Python?
An object that tries to find the loader for a module that is being imported.
What are the two types of finders?
- Meta path finders for use with sys.meta_path
- Path entry finders for use with sys.path_hooks
What is floor division?
Mathematical division that rounds down to the nearest integer.
What operator is used for floor division?
//
What is free threading?
A threading model where multiple threads can run Python bytecode simultaneously within the same interpreter.
What is a free variable?
Any variable used in a namespace which is not a local variable in that namespace.
What is a function in Python?
A series of statements which returns some value to a caller.
What is a function annotation?
An annotation of a function parameter or return value, often used for type hints.
What does the __future__ statement do?
Directs the compiler to compile the current module using syntax or semantics that will become standard in a future release of Python.
What is garbage collection?
The process of freeing memory when it is not used anymore.
How does Python perform garbage collection?
Via reference counting and a cyclic garbage collector that is able to detect and break reference cycles.
What is a generator?
A function which returns a generator iterator and contains yield expressions.
What does a generator iterator do?
It is an object created by a generator function that remembers the execution state.
What is a generator expression?
An expression that returns an iterator, defined with a for clause and an optional if clause.
Define a generic function.
A function composed of multiple functions implementing the same operation for different types.
What is a generic type?
A type that can be parameterized, typically a container class like list or dict.
What is the GIL?
Global Interpreter Lock; ensures only one thread executes Python bytecode at a time.
What is the purpose of the global interpreter lock?
To simplify the CPython implementation by making the object model safe against concurrent access.
What is a hash-based pyc?
A bytecode cache file that uses the hash to determine its validity.
What makes an object hashable?
It has a hash value that never changes and can be compared to other objects.
What is IDLE in Python?
An Integrated Development and Learning Environment that includes a basic editor and interpreter.
What are immortal objects in CPython?
Objects whose reference count is never modified and are never deallocated.
Define immutable.
An object with a fixed value that cannot be altered.
What is the import path?
A list of locations searched for modules to import, usually from sys.path.
What is importing in Python?
The process by which code in one module is made available to code in another module.
What is a loader in Python?
An object that loads a module and must define exec_module() and create_module() methods.
What is locale encoding on Unix?
The encoding of the LC_CTYPE locale, set with locale.setlocale(locale.LC_CTYPE, new_locale).
What is a magic method?
An informal synonym for special method.
Define mapping in Python.
A container object that supports arbitrary key lookups, like dict and collections.OrderedDict.
What is a metaclass?
The class of a class responsible for creating the class from its definition.
What is method resolution order (MRO)?
The order in which base classes are searched for a member during lookup.
What is a module in Python?
An object that serves as an organizational unit of Python code with its own namespace.
What is a named tuple?
A class that inherits from tuple and allows access to elements using named attributes.
What does LBYL stand for?
Look Before You Leap; a coding style that tests for pre-conditions before making calls.
What is a lambda function?
An anonymous inline function consisting of a single expression.
True or False: Mutable objects can change their value but keep their id().
True
What is a list comprehension?
A compact way to process elements in a sequence and return a list with the results.
What is an iterable?
An object capable of returning its members one at a time.
Define an iterator.
An object representing a stream of data that returns items on successive calls to __next__().
What is a key function?
A callable that returns a value used for sorting or ordering.
What is a namespace?
The place where a variable is stored, implemented as dictionaries.
Includes local, global, built-in, and nested namespaces.
What is a namespace package?
A PEP 420 package that serves only as a container for subpackages and has no __init__.py file.
It may have no physical representation.
What is nested scope?
The ability to refer to a variable in an enclosing definition.
Works for reference but not for assignment by default.
What is a new-style class?
The flavor of classes now used for all class objects, allowing access to Python’s newer features.
Previously, only new-style classes could use features like __slots__ and descriptors.
Define an object in Python.
Any data with state (attributes or value) and defined behavior (methods).
It is also the ultimate base class of any new-style class.
What is an optimized scope?
A scope where target local variable names are reliably known to the compiler, allowing optimization of access.
Local namespaces for functions, generators, and comprehensions are optimized.
What is a package in Python?
A Python module that can contain submodules or subpackages, technically defined by having a __path__ attribute.
Includes regular and namespace packages.
What are the five kinds of parameters in a function definition?
- positional-or-keyword
- positional-only
- keyword-only
- var-positional
- var-keyword
Each of these specifies how arguments can be passed to functions.
What is a path entry?
A single location on the import path for module importing.
It is consulted by the path based finder.
What is a path entry finder?
A finder returned by a callable on sys.path_hooks that knows how to locate modules given a path entry.
Implements methods defined in importlib.abc.PathEntryFinder.
What is a path-like object?
An object representing a file system path, either as a str or bytes object or implementing the os.PathLike protocol.
Supports conversion to str or bytes using os.fspath().
What does PEP stand for?
Python Enhancement Proposal.
A design document providing information or describing new features for Python.
What is a portion in the context of namespace packages?
A set of files in a single directory that contribute to a namespace package, possibly stored in a zip file.
Defined in PEP 420.
What is a provisional API?
An API excluded from standard library’s backwards compatibility guarantees, allowing for potential changes or removals.
Major changes are not expected but may occur if necessary.
What is Python 3000?
Nickname for the Python 3.x release line, also abbreviated as Py3k.
Coined when the release of version 3 was anticipated.
What does Pythonic mean?
An idea or piece of code that follows the common idioms of the Python language.
Example: using a for loop over an iterable instead of a numerical counter.
Define qualified name.
A dotted name showing the path from a module’s global scope to a defined class, function, or method.
E.g., C.D.meth.__qualname__ returns ‘C.D.meth’.
What is reference count?
The number of references to an object, which determines its deallocation.
When it drops to zero, the object is deallocated.
What is a regular package?
A traditional package, such as a directory containing an __init__.py file.
Distinct from namespace packages.
What does REPL stand for?
Read–eval–print loop.
It refers to the interactive interpreter shell.
What are __slots__?
A declaration inside a class that saves memory by pre-declaring space for instance attributes.
It eliminates instance dictionaries.
What is a sequence in Python?
An iterable that supports efficient element access using integer indices and defines a __len__() method.
Examples include list, str, tuple, and bytes.
What is set comprehension?
A compact way to process elements in an iterable and return a set with the results.
Example: results = {c for c in ‘abracadabra’ if c not in ‘abc’}.
What is single dispatch?
A form of generic function dispatch based on the type of a single argument.
It allows different implementations based on argument type.
Define slice.
An object usually containing a portion of a sequence, created using subscript notation with colons.
Example: variable_name[1:3:5].
What does soft deprecated mean?
An API that should not be used in new code but is safe for existing code.
It remains documented and tested but will not be enhanced.
What is a special method in Python?
A method that is called implicitly by Python to execute a certain operation on a type, such as addition.
Special methods have names starting and ending with double underscores and are documented in Special method names.
What is a statement in Python?
A statement is part of a suite (a ‘block’ of code) and can be either an expression or a construct with a keyword, such as if, while, or for.
What is a static type checker?
An external tool that reads Python code and analyzes it for issues such as incorrect types.
See also type hints and the typing module.
What is a strong reference in Python’s C API?
A reference to an object that is owned by the code holding the reference, created with Py_INCREF() and released with Py_DECREF().
What function can be used to create a strong reference?
The Py_NewRef() function.
What is text encoding?
The process of serializing a string into a sequence of bytes and recreating the string from the byte sequence is known as encoding and decoding, respectively.
What is a text file in Python?
A file object able to read and write str objects, often handling text encoding automatically.
Examples include files opened in text mode (‘r’ or ‘w’), sys.stdin, sys.stdout, and instances of io.StringIO.
What is a triple-quoted string?
A string bound by three instances of either a quotation mark or an apostrophe, allowing unescaped quotes and spanning multiple lines.
What determines the type of a Python object?
The type of a Python object determines what kind of object it is; every object has a type.
What is a type alias?
A synonym for a type, created by assigning the type to an identifier, useful for simplifying type hints.
What is a type hint?
An annotation that specifies the expected type for a variable, class attribute, or function parameter/return value.
True or False: Type hints are enforced by Python.
False
What are universal newlines?
A manner of interpreting text streams where Unix, Windows, and old Macintosh end-of-line conventions are all recognized as line endings.
What is a variable annotation?
An annotation of a variable or a class attribute, often used for type hints.
What is a virtual environment in Python?
A cooperatively isolated runtime environment that allows installation and upgrading of Python packages without interfering with other applications.
What is a virtual machine in the context of Python?
A computer defined entirely in software that executes the bytecode emitted by the bytecode compiler.
What is the Zen of Python?
A listing of Python design principles and philosophies that are helpful in understanding and using the language.
What is the output of the expression 2 + 3 * 5
?
The output is 17.
True or False: In Python, ==
checks for value equality.
True.
Fill in the blank: The expression len([1, 2, 3])
returns __.
3.
What will be the result of the expression 5 ** 2
?
The result is 25.
What is the data type of the expression type([1, 2, 3])
?
The data type is <class ‘list’>.
Which of the following is a valid Python list? A) [1, 2, 3]
B) 1, 2, 3
C) list(1, 2, 3)
A) [1, 2, 3]
.
What does the expression max([1, 2, 3, 4])
return?
It returns 4.
True or False: The expression 3 in [1, 2, 3]
evaluates to True.
True.
What is the output of sum([1, 2, 3, 4])
?
The output is 10.
Fill in the blank: The expression range(5)
generates numbers from __ to __.
0 to 4.
What will be the result of the expression 5 // 2
?
The result is 2.
Which operator is used for string concatenation in Python?
’+’ is used for string concatenation.
True or False: Lists in Python are mutable.
True.
What does the expression ['a', 'b', 'c'][1]
return?
‘b’.
What will be the output of ['a', 'b', 'c'] + ['d', 'e']
?
The output is ['a', 'b', 'c', 'd', 'e']
.
Fill in the blank: The expression ['x', 'y', 'z'][::-1]
results in __.
[‘z’, ‘y’, ‘x’].
What is the output of 3 * 'abc'
?
The output is ‘abcabcabc’.
Which of the following is not a valid list method? A) .append()
B) .remove()
C) .add()
C) .add()
.
What does the expression list(range(3))
return?
[0, 1, 2].
True or False: The expression 2 == '2'
evaluates to True.
False.
What is the result of the expression if 0: print('Hello')
?
No output; the condition evaluates to False.
Fill in the blank: The expression {'key': 'value'}.get('key')
returns __.
‘value’.
What is the output of the expression tuple([1, 2, 3])
?
(1, 2, 3).
Which method would you use to sort a list in Python?
The .sort()
method.
What will be the result of bool([])
?
The result is False.
What does the expression set([1, 2, 2, 3])
return?
The output is {1, 2, 3}
.
What is the output of the following code: print(2 ** 3)?
8
True or False: A list in Python can contain elements of different data types.
True
Fill in the blank: In Python, a _______ is a collection of key-value pairs.
dictionary
What will be the output of: print(len(‘Hello, World!’))?
13
Which of the following is a valid way to create a function in Python?
A) def my_function():
B) function my_function():
C) create my_function():
A) def my_function():
What does the ‘append()’ method do in a list?
Adds an element to the end of the list.
True or False: Python uses indentation to define blocks of code.
True
What is the difference between ‘==’ and ‘===’ in Python?
’==’ checks for value equality, while ‘===’ does not exist in Python.
What will be the result of this code: print(type(3.14))?
<class ‘float’>
Which keyword is used to create a class in Python?
class
What is the output of: print(‘Hello’ + ‘ World’)?
Hello World
Fill in the blank: The _______ statement is used to exit a loop in Python.
break
What does the ‘range()’ function do in Python?
Generates a sequence of numbers.
Which of the following will create a dictionary in Python?
A) my_dict = {}
B) my_dict = []
C) my_dict = ()
A) my_dict = {}
True or False: Python supports multiple inheritance.
True
What is the output of: print(‘Python’ * 2)?
PythonPython
What will be the result of: print(10 // 3)?
3
What is the purpose of the ‘with’ statement in Python?
To wrap the execution of a block with methods defined by a context manager.
Fill in the blank: To handle exceptions, Python uses _______.
try and except
What is the output of this code: print(‘abc’.upper())?
ABC
What does the ‘strip()’ method do in a string?
Removes leading and trailing whitespace.
Which of the following is a mutable data type in Python?
A) Tuple
B) List
C) String
B) List
True or False: The ‘input()’ function returns a string.
True
What is the purpose of the ‘self’ keyword in Python class methods?
It refers to the instance of the class.
What will be the output of: print(‘Hello, {0}’.format(‘World’))?
Hello, World
Fill in the blank: A _______ is a sequence of characters in Python.
string