1. Core Python
A fast overview of everyday Python building blocks: types, truthiness, slicing, and small-but-crucial idioms you use constantly.
Question: What are the main built-in data types?
Answer: Python has numbers (int
, float
, complex
), strings (str
), booleans (bool
), binary types (bytes
, bytearray
, memoryview
), ranges (range
), and collections. None
represents the absence of a value.
Explanation:
Strings: Immutable sequences of characters. Use f-strings (
f"Hello, {name}"
) for easy formatting.Collections:
list
[1, 2]
: Mutable (changeable) and ordered.tuple
(1, 2)
: Immutable (cannot be changed) and ordered.dict
{"k": 1}
: Mutable key-value pairs, ordered by insertion (Python 3.7+).set
{1, 2}
: Mutable, unordered, and contains unique elements.frozenset
frozenset({1, 2})
: Immutable set; hashable and usable as a dictionary key.
Question: When would you use a tuple instead of a list?
Answer: Use a tuple for data that should not change, like coordinates (x, y)
. Because they are immutable, tuples are hashable and can be used as dictionary keys, whereas lists cannot.
Question: What does it mean for a value to be "falsy"?
Answer: In a boolean context (like an if
statement), some values evaluate to False
. These are called "falsy" values. They include 0
, 0.0
, empty strings ''
, empty collections ([]
, {}
, ()
, set()
), None
, and False
itself. All other values are "truthy".
Question: How do you slice strings and sequences?
Answer: Use sequence[start:stop:step]
; negative indices count from the end.
s = "abcdef"
s[1:4] # 'bcd'
s[:3] # 'abc'
s[-2:] # 'ef'
s[::2] # 'ace'
Explanation: Slicing returns a new object of the same type; out-of-range indices are clamped, not errors.
Question: What’s the difference between
str
andbytes
?
Answer: str
is text (Unicode), bytes
is raw 8-bit data. Convert with .encode()
/.decode()
.
text = "Привет"
data = text.encode("utf-8") # bytes
back = data.decode("utf-8") # str
Question: How does iterable unpacking work?
Answer: You can unpack sequences into names; use *rest
to capture remaining items.
a, b = (1, 2)
first, *middle, last = [10, 20, 30, 40] # first=10, middle=[20,30], last=40