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.
What executes Python bytecode in CPython?
CPython first compiles .py source into bytecode, which its Python Virtual Machine executes. Python is therefore not simply "uncompiled."
How does Python mark blocks of code?
Indentation defines blocks after a colon, such as under if, for, def, and class. Consistent indentation is syntactically required.
What are .py files?
Files ending in .py contain Python source code and can be executed as scripts or imported as modules.
What does python app.py do?
Starts the selected Python interpreter and executes the code in app.py, using the current environment when applicable.
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.
Are Python identifiers case-sensitive?
Yes. Variables called name and Name are different because Python distinguishes uppercase and lowercase letters.
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 UPPER_SNAKE_CASE used for?
UPPER_SNAKE_CASE conventionally marks constants such as MAX_RETRIES; Python does not enforce immutability.
What does the type() function return?
type(obj) returns the object's class or type; e.g., type(42) is int.
What does isinstance(x, int) check?
Returns True if x is an int or an instance of its subclass; bool is a subclass of int in Python.
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 does len() return?
len(obj) reports the number of elements for supported objects, such as a list's items or a string's characters.
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('42') return?
It converts the numeric string "42" into the integer 42, which can then be used in arithmetic.
What happens for int('hello')?
int("hello") raises ValueError because the string cannot be interpreted as a valid integer.
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.
What does in test?
in checks membership, e.g., 2 in [1,2] or "py" in "python"; dictionaries test membership among keys.
What is a falsy value?
A falsy value behaves like False in if or while conditions, even if it is not the bool object False.
Name common falsy values.
False, None, 0, 0.0, "", [], {}, (), and set() are falsy; most nonempty objects are truthy.
What is match/case?
match/case selects branches using structural patterns; case _ is a wildcard fallback. It is more powerful than a basic switch.
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 def do?
def introduces a function definition: def add(a, b): return a + b. The body runs when the function is called.
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 a function return by default?
A function without a return statement, or with a bare return, returns None.
What does *args capture?
*args gathers extra positional arguments into a tuple, enabling functions to accept varying numbers of positional inputs.
What does **kwargs capture?
**kwargs collects extra keyword arguments into a dictionary of parameter names and values.
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 does strip() do?
strip() returns a copy without leading or trailing whitespace. It does not remove spaces in the middle of the string.
What does ' '.join(parts) do?
" ".join(parts) combines the strings in parts, inserting a space between neighboring elements.
What does replace(old, new) do?
replace(old, new) returns a new string with matching substrings substituted; the original str is unchanged.
What does title() do?
title() produces a new title-cased string, typically capitalizing words; it may not match linguistic title-case rules.
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.
Which collections preserve insertion order?
Lists and tuples are ordered sequences; dictionaries preserve key insertion order in modern Python. Sets guarantee no ordering.
Which Python built-in collections are mutable?
list, dict, and set are mutable; tuple, str, and frozenset are immutable. A tuple may still contain a mutable object.
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.insert(i, x)?
insert(i, x) adds x immediately before position i, shifting later list items right.
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.
What does list.clear() do?
clear() mutates the existing list, removing all elements without creating a replacement list.
How do you sort a list descending?
items.sort(reverse=True) modifies the list; sorted(items, reverse=True) creates a new sorted list.
What does list.reverse() do?
reverse() reverses the existing list in place and returns None; reversed(items) produces a reverse iterator.
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 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.index(x) do?
tuple.index(x) returns the position of the first matching element and raises ValueError if the value is absent.
How can you modify values represented by a tuple?
You cannot assign tuple elements. Create a new tuple, or modify a mutable object already stored inside it.
What does set.add(x) do?
add(x) inserts one hashable element if not already present; set elements remain unique.
What does set.pop() remove?
set.pop() removes and returns an arbitrary element. Unlike list.pop(), it does not mean the last item.
What is set intersection?
A & B returns elements shared by both sets, e.g., {1,2} & {2,3} gives {2}.
What is set difference?
A - B returns members present in A but not B; set difference is not symmetric.
What is frozenset?
frozenset is an immutable, hashable set type (when its elements are hashable), useful as a dictionary key or set member.
Why can True and 1 be duplicates in a set?
True == 1 and hash(True) == hash(1); a set treats them as equivalent and stores one representative.
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.
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 shallow copying?
A shallow copy duplicates only the outer container. Nested mutable objects are still shared between the two copies.
What is deepcopy()?
copy.deepcopy(obj) recursively copies supported nested objects, avoiding shared references in many mutable structures.
What is collections.OrderedDict?
OrderedDict is a dict subclass with explicit reordering operations such as move_to_end(), beyond ordinary dict ordering.
What does OrderedDict.move_to_end(k) do?
move_to_end(key) moves an existing entry to the end; last=False moves it to the beginning.
What is collections.namedtuple?
namedtuple creates an immutable tuple subtype with named attributes, e.g., Point(2,3).x, while retaining index access.
Is a namedtuple mutable?
Yes, it is immutable: named fields cannot be reassigned. Use _replace() to produce a modified copy.
What does namedtuple._replace(x=5) do?
_replace(x=5) creates a new namedtuple with x changed; it leaves the original object untouched.
What does Counter('banana')['a'] equal?
Counter("banana") counts characters; "a" appears three times, so its count is 3.
What does Counter.most_common(2) return?
most_common(2) returns up to two (item, count) pairs ranked by frequency, useful for top-occurrence queries.
What does Counter.subtract(iterable) do?
subtract(iterable) decreases frequencies based on occurrences; unlike normal set subtraction, negative counts can remain.
What does Counter A | B compute?
A | B combines Counters using the maximum count per key, not ordinary set-style uniqueness.
What is procedural programming?
Procedural programming organizes a program around a sequence of commands and functions rather than object state.
What is a class?
A class defines the data and behavior of instances, e.g., class Student:; each created object is an instance.
What is self?
self is the conventional name for the instance passed to an instance method; used to access self.name or other attributes.
Does self have to be named self?
Technically no: self is a naming convention. However, using another name would confuse readers and tools.
What does __init__ do?
__init__ initializes an object after creation, often assigning instance attributes; __new__ actually creates the instance.
What is a class attribute?
A class attribute belongs to the class and is looked up by instances unless an instance attribute shadows it.
What does __str__ define?
__str__ returns an informal, human-readable representation used by str(obj) and usually print(obj).