1/239
Looks like no tags are added yet.
What is Python?
Python is a high-level, general-purpose language with dynamic typing and indentation-based syntax. Common uses include automation, APIs, data analysis, and AI.
What does dynamically typed mean?
Types belong to objects, not fixed variable declarations. A variable can refer to an integer and later to a string; type errors are checked at runtime.
Is Python strongly typed?
Yes; incompatible types are not generally coerced silently.
Does CPython compile source code?
Yes; it compiles .py source to bytecode before executing it.
What are .py files?
Files ending in .py contain Python source code and can be executed as scripts or imported as modules.
What is the use of python --version?
Displays the version of the selected Python interpreter.
What is py on Windows?
A launcher/manager that can select installed Python versions.
What does py -3.12 app.py do?
The Windows Python launcher selects Python 3.12 to run app.py, provided that version is installed.
What is Python's interactive REPL?
REPL means Read-Eval-Print Loop. It lets you enter code interactively, see immediate results, and test small snippets.
Why use VS Code Pylance?
Pylance provides autocompletion, symbol navigation, diagnostics, and optional static type checking in VS Code.
What does isort do?
isort automatically orders and groups imports consistently, reducing manual formatting and merge conflicts.
What is Jupyter?
Jupyter runs code in interactive cells alongside markdown and output, making it useful for analysis and demonstrations.
What is an ipykernel?
A Python execution kernel that Jupyter can use to run notebook cells.
What is snake_case used for?
PEP 8 commonly uses snake_case for variables, function names, and modules, such as student_name and get_student().
What is PascalCase used for?
Conventionally for class names.
What characters can Python identifiers contain?
Letters, digits, and underscores; they cannot begin with a digit.
What does the type() function return?
type(obj) returns the object's class or type; e.g., type(42) is int.
What is int?
Python's integer numeric type.
What is float?
float is Python's floating-point number type for values such as 3.14; many decimal values are approximations in binary.
What is str?
str is the immutable Unicode text type. Indexing and slicing work, but characters cannot be reassigned in place.
What type is None?
None is the sole instance of NoneType and commonly represents a missing or absent result; compare it using is None.
What does input() return?
input() always returns text as str. Convert with int() or float() when numerical input is required.
How do you write a single-line comment?
Use # to begin a comment until the end of the line; comments explain intent without affecting execution.
What is a docstring?
A string literal documenting a module, class, or function.
What is a type hint?
An annotation describing an expected type, usually checked by tooling.
Are type hints enforced automatically at runtime?
No. Annotations document intended types and support tools; Pydantic or explicit code can validate them at runtime.
What does int(3.9) return?
3; converting a float to int truncates toward zero.
What does / do?
True division; it produces a float for ordinary numeric operands.
What does // do?
// performs floor division, rounding toward negative infinity: 7 // 2 == 3, but -7 // 2 == -4.
What does % do?
% calculates the remainder consistent with floor division. For example, 10 % 3 == 1; commonly used to test evenness.
What does ** do?
** raises a value to a power, such as 2 ** 3 == 8. It also supports fractional exponents.
What does is compare?
is checks whether two names refer to the exact same object; == checks whether their values compare equal.
How should None normally be compared?
Use is None or is not None.
What do and, or, not do?
Logical conjunction, disjunction, and negation.
Name common falsy values.
False, None, 0, 0.0, "", [], {}, (), and set() are falsy; most nonempty objects are truthy.
What is if/elif/else for?
Conditional branching based on expressions.
What does case _ mean?
A wildcard/default case that matches any value.
What is a match guard?
A match guard is an additional condition written as case pattern if condition:; the case matches only if both succeed.
What does break do?
break immediately ends the nearest for or while loop, then execution continues after the loop.
What does continue do?
continue skips the rest of the current loop iteration and proceeds to the next iteration.
What is enumerate(iterable) for?
enumerate(items) yields (index, value) pairs; useful when you need a position while iterating.
What does the walrus operator := do?
The := operator assigns a value as part of an expression, such as while (line := file.readline()):.
What does a chained comparison mean?
Example: 1 < x < 10 tests both bounds without repeating x.
What is the difference between parameter and argument?
A parameter is a name in the function definition; an argument is the actual value passed by a caller.
What does return do?
Ends a function call and supplies its result to the caller.
What is a default parameter?
A parameter with a default argument used if omitted.
What does *args capture?
*args gathers extra positional arguments into a tuple, enabling functions to accept varying numbers of positional inputs.
What is a keyword argument?
An argument provided by parameter name, e.g. greet(name='Ann').
What is LEGB?
LEGB is Python's name lookup order: Local, Enclosing, Global, and Built-in.
What does nonlocal do?
nonlocal lets an inner function rebind a variable in the nearest enclosing function scope rather than creating a new local.
What is a common lambda use?
lambda defines a short anonymous expression-based function, often a key function for sorting: key=lambda x: x[1].
What is a mutable default argument pitfall?
Mutable defaults such as def f(items=[]) are reused across calls. Use None and create a new list inside the function.
What is s[::-1]?
s[::-1] returns a reversed copy of the string using a slice with a step of -1.
What is a negative index?
An index counting backward from the end; -1 is last.
What does split() do?
Splits a string into a list using a delimiter or whitespace.
What does ' '.join(parts) do?
" ".join(parts) combines the strings in parts, inserting a space between neighboring elements.
What does lower() do?
Returns a lowercase copy of a string.
What is an f-string?
A formatted string literal that evaluates expressions inside braces.
What is an r-string?
An r-prefixed literal treats most backslashes literally, useful for regular expressions and Windows paths.
Are strings mutable?
No. Strings are immutable; methods like upper(), replace(), and strip() return a new string.
What is a list?
A list is an ordered, mutable sequence supporting duplicate and mixed-type elements; e.g., [1, "a", 1].
What is a set?
A set contains unique, hashable elements and does not guarantee insertion order; ideal for membership and deduplication.
What is a dict?
An insertion-ordered, mutable key-value mapping with unique hashable keys.
Which collections preserve insertion order?
Lists and tuples are ordered sequences; dictionaries preserve key insertion order in modern Python. Sets guarantee no ordering.
Can a tuple contain a list?
Yes; the tuple is immutable, but the nested list can still be modified.
What is list.append(x)?
append(x) adds x as a single final element. append([2,3]) adds one nested list, unlike extend([2,3]).
What is list.extend(xs)?
Appends each element of iterable xs to the list.
What is list.remove(x)?
Removes the first element equal to x; raises ValueError if missing.
What does list.pop() do?
pop() removes and returns the last list item by default; pop(i) removes at index i. Empty lists raise IndexError.
How is sorted(xs) different from xs.sort()?
sorted returns a new list; sort mutates a list and returns None.
How do you sort a list descending?
items.sort(reverse=True) modifies the list; sorted(items, reverse=True) creates a new sorted list.
How do you sort case-insensitively?
Use key=str.lower or key=str.casefold.
How do you test membership in a list?
Use item in items. For lists, membership testing checks values sequentially and is generally O(n).
What does list[a:b:c] mean?
Slice from a to b exclusive, stepping by c.
What is a list comprehension?
A list comprehension creates a new list concisely: [x*x for x in nums if x > 0].
Give a comprehension filtering even numbers.
[x for x in nums if x % 2 == 0] includes only values divisible by 2.
How does a conditional expression differ inside comprehensions?
[x if cond else y for ...] picks an output for each element; [x for ... if cond] removes elements not meeting the condition.
How do you make a one-element tuple?
Use (42,) or 42,; the comma, not the parentheses alone, creates the one-element tuple.
What does tuple.count(x) do?
Counts occurrences of x.
What does tuple.index(x) do?
tuple.index(x) returns the position of the first matching element and raises ValueError if the value is absent.
Why use a set to remove duplicates?
It retains only one occurrence of each equal, hashable element.
What does set.add(x) do?
add(x) inserts one hashable element if not already present; set elements remain unique.
How does set.remove differ from discard?
remove raises KeyError if absent; discard does not.
What is set union?
Elements in either set; A | B.
What is set intersection?
A & B returns elements shared by both sets, e.g., {1,2} & {2,3} gives {2}.
What is symmetric difference?
Elements in exactly one of the sets; A ^ B.
What is frozenset?
frozenset is an immutable, hashable set type (when its elements are hashable), useful as a dictionary key or set member.
Can a set contain a list?
No; lists are unhashable.
What does dict.get(key) do?
get(key, default=None) retrieves a value without raising KeyError if the key is missing; missing keys yield the default.
How does d[key] differ from d.get(key)?
Missing d[key] raises KeyError; get returns its default.
What does dict.items() return?
items() provides a dynamic view of (key, value) pairs for iteration, e.g., for k,v in d.items().
What does dict.values() return?
values() produces a dynamic view of the dictionary's current values rather than an independent list.
What does dict.update(mapping) do?
update(other) adds new key-value pairs and overwrites values for existing keys in place.
What does dict.popitem() do?
popitem() removes and returns the most recently inserted pair in modern Python; raises KeyError when empty.
What is a dictionary comprehension?
A mapping built with {key_expr: value_expr for item in iterable}.
What is shallow copying?
A shallow copy duplicates only the outer container. Nested mutable objects are still shared between the two copies.
What happens when b = a for a list?
Both names reference the same list; mutations through either are visible.
What is collections.OrderedDict?
OrderedDict is a dict subclass with explicit reordering operations such as move_to_end(), beyond ordinary dict ordering.
Why use OrderedDict if dict preserves order?
For operations like move_to_end and order-sensitive behavior.
What does OrderedDict.popitem(last=False) do?
Removes and returns the first key-value pair.