Python¶
67 cards — 🟢 30 easy | 🟡 17 medium | 🔴 6 hard
🟢 Easy (30)¶
1. What is "tuple unpacking"?
Show answer
Assigning elements of a tuple to multiple variables in one line.Example: a, b, c = (1, 2, 3). You can also use
* for catch-all: first, *rest = (1, 2, 3,
4) gives rest = [2, 3, 4]. Works with any iterable, not just tuples.
2. How do you write a comment in Python?
Show answer
By starting the line with a #. For multi-line explanations, use consecutive # lines. Triple-quoted strings (docstrings) serve a different purpose — they document modules, classes, and functions and are accessible at runtime via __doc__.3. What is the "math" module?
Show answer
A standard library module providing mathematical functions like sqrt(), ceil(), floor(), log(), and constants like math.pi and math.e. For example, math.sqrt(16) returns 4.0. For more advanced work (arrays, stats), use numpy instead.4. What is a tuple and how does it differ from a list?
Show answer
An immutable, ordered sequence of items defined with parentheses: t = (1, 2, 3). Because they are immutable, tuples are hashable and can be used as dictionary keys or set elements. A single-element tuple requires a trailing comma: (42,).5. What is "nested loop"?
Show answer
A loop placed inside the body of another loop. The inner loop runs completely for each iteration of the outer loop.Example: iterating a 2D grid with for row in matrix: for cell in row. Be cautious — deeply nested loops can cause performance issues (O(n^2) or worse).
6. What are the three logical operators?
Show answer
and, or, and not. They operate on boolean values and use short-circuit evaluation — and stops at the first False, or stops at the first True. This enables patterns like value = x or default_value to set a fallback when x is falsy.7. What is an "integer division" operator?
Show answer
// (floor division) divides and returns only the whole number part, discarding the remainder.Example: 7 // 2 gives
3. It always rounds toward negative infinity, so -7 // 2 gives -4 (not -3). Pair with % (modulus) to get both quotient and remainder.
8. What does the input() function always return?
Show answer
A string value, regardless of what the user types. If you need a number, you must explicitly cast: int(input("Enter a number: ")). Forgetting this cast is one of the most common beginner bugs — comparing input() == 5 will always be False.9. What is a list data type and how is it used?
Show answer
A mutable, ordered sequence of items defined with square brackets: my_list = [1, 2, 3]. Lists support indexing, slicing, appending, and iteration. They can hold mixed types but in practice usually hold one type. Under the hood, Python lists are dynamic arrays, not linked lists.10. How do you install a package in Python?
Show answer
Using pip: pip install package_name (downloads from PyPI by default).Best practice: always install into a virtual environment, not system Python. Use pip install -r requirements.txt for project dependencies, and pin versions for reproducibility (e.g., requests==2.31.0).
11. What is Python and what makes it popular for DevOps and scripting?
Show answer
Python is a high-level, interpreted programming language known for its readable syntax and broad usage in web development, automation, data analysis, AI, and DevOps scripting. Its "batteries included" standard library and large ecosystem (PyPI) make it a go-to language for rapid prototyping and production systems alike.12. What function returns the data type of an object?
Show answer
type().Example: type(42) returns
13. What does the len() function do?
Show answer
Returns the number of items in an object — works on strings, lists, tuples, dicts, sets, and any object implementing __len__.Example: len("hello") returns 5, len([1,2,3]) returns
3. Calling len on an object that does not support it raises TypeError.
14. What is "decrementing"?
Show answer
Subtracting a value (usually one) from a variable, typically in a loop. Python has no -- operator like C/Java; use x -= 1 instead. Incrementing is the opposite: x += 1. These augmented assignment operators also work with other operations: *=, /=, %=.15. What is the difference between a parameter and an argument?
Show answer
A parameter is the variable name in a function definition; an argument is the actual value passed when calling the function.Example: in def greet(name), name is the parameter; in greet("Alice"), "Alice" is the argument. Python supports positional, keyword, default, and variadic (*args, **kwargs) parameters.
16. What is iteration in programming and what are common patterns?
Show answer
The repeated execution of a set of statements, typically using a for loop (iterating over a sequence) or a while loop (iterating until a condition is false). Python's for loop works on any iterable: lists, strings, dicts, files, generators. The iter()/next() protocol underlies all iteration.17. Which operator gives the remainder of division?
Show answer
% (modulus).Example: 10 % 3 returns 1. Commonly used to check if a number is even (n % 2 == 0), cycle through indices, or implement wrap-around behavior. In Python, the result always has the same sign as the divisor, unlike some other languages.
18. What is a Boolean data type and how is it used in programming?
Show answer
A data type representing True or False (capitalized in Python). Booleans are a subclass of int: True == 1, False == 0. Falsy values include 0, None, empty strings, empty collections. Used in conditionals, loops, and logical expressions.19. What does the import statement do in Python?
Show answer
Loads a module (or specific names from it) into the current namespace so you can use its functions, classes, and variables. Variants: import math (full module), from math import sqrt (single name), from math import* (all names — discouraged, pollutes namespace). Python caches imports in sys.modules.
20. Is Python statically or dynamically typed?
Show answer
Dynamically typed — variable types are determined at runtime and you do not declare types explicitly. You can reassign x = 5 then x = "hello". This adds flexibility but can hide bugs. Type hints (PEP 484) add optional static checking via tools like mypy without changing runtime behavior.21. What value is returned if a function has no return statement?
Show answer
None. Python implicitly returns None when a function exits without a return statement or with a bare return. This is important when chaining function calls — if you accidentally forget return, downstream code receives None, often causing subtle AttributeError bugs.22. What is a "Syntax Error"?
Show answer
An error raised when Python's parser encounters code that violates the language's structural rules — such as missing colons, unmatched brackets, or incorrect indentation. SyntaxErrors are caught before runtime so the program never starts. Read the error message carefully: it points to the line and position of the problem.23. How does Python define code blocks?
Show answer
By using indentation (whitespace at the start of a line), not braces like C/Java. The standard is 4 spaces per level (PEP 8). Mixing tabs and spaces causes IndentationError. Consistent indentation is enforced by the parser, making Python code visually structured by default.24. How do you add an item to the end of a list?
Show answer
Using .append(item) to add a single element, or .extend(iterable) to add multiple elements.Note: append([1,2]) adds the list as one nested element; extend([1,2]) adds each element individually. For inserting at a specific position, use .insert(index, item).
25. What is a "local variable"?
Show answer
A variable defined inside a function, accessible only within that function's scope. It is created when the function runs and destroyed when it returns. Attempting to access it outside raises NameError. Use the global keyword (sparingly) to modify a module-level variable from within a function.26. What are variables in Python and how are they defined?
Show answer
Named references to data stored in memory. In Python, variables do not have fixed types — they are labels pointing to objects. Assignment (x = 42) binds the name x to an integer object. Multiple names can reference the same object. Use descriptive names (user_count, not uc) for readable code.27. What is a "high-level" language?
Show answer
A language abstracted from hardware details, closer to human language than machine code. High-level languages (Python, JavaScript, Ruby) handle memory management and provide rich built-in data structures.Trade-off: easier to write and read, but generally slower than low-level languages like C. Python bridges the gap with C extensions and libraries like numpy.
28. How do you check if two values are equal?
Show answer
Using the == operator, which compares values.Example: 5 == 5.0 is True (cross-type equality). For identity comparison (same object in memory), use is. For inequality, use !=. For ordered comparisons: <, >, <=, >=. You can chain comparisons: 1 < x < 10 checks both bounds.
29. What is the "range()" function used for?
Show answer
Generating a sequence of numbers, typically for loops. range(5) gives 0-4; range(2,8) gives 2-7; range(0, 10,
2) gives even numbers 0-8. It returns a lazy range object (not a list), so range(10**9) uses almost no memory. Convert to a list with list(range(5)) if needed.
30. What does case-sensitivity mean in Python?
Show answer
Uppercase and lowercase letters are treated as distinct — myVar, myvar, and MYVAR are three different names. This applies to variable names, function names, keywords (True not true), and module names. Convention: constants use ALL_CAPS, classes use CamelCase, everything else uses snake_case.🟡 Medium (17)¶
1. What's the difference between a list and a tuple in Python?
Show answer
A list is mutable (you can change, add, remove elements), while a tuple is immutable (once created, its elements cannot be changed). Tuples are hashable (usable as dict keys), slightly faster, and signal intent that data should not change. Use tuples for fixed collections like coordinates or DB rows.2. What is the difference between return and print?
Show answer
return sends a value back to the caller and exits the function — it can be captured in a variable or used in expressions. print outputs text to the console for human reading but returns None. A common beginner mistake is using print inside a function and wondering why the result can't be reused.3. What does the open() mode 'a' do?
Show answer
Opens a file for appending — new writes go to the end without overwriting existing content. If the file does not exist, it is created. Contrast with 'w' which truncates the file. Use 'a' for log files or any case where you want to accumulate data across multiple writes.4. What is a list comprehension in Python?
Show answer
A concise way to create a new list by iterating over an iterable and optionally filtering.Example: [x**2 for x in range(5) if x % 2 == 0] creates [0, 4, 16]. Also supports nested loops and can be turned into generator expressions with parentheses for memory efficiency. Prefer comprehensions over map/filter for readability.
5. What does if name == "main": do?
Show answer
It checks if the file is being run directly (as a script) vs being imported as a module. Code inside this block only executes on direct run. This idiom lets you put tests, demos, or CLI logic in a module file without it running on import. Every well-structured Python script should use this pattern.6. What is a "Value Error"?
Show answer
Raised when a function receives the right type but an inappropriate value.Example: int("abc") raises ValueError because "abc" is a string (correct type for int()) but not a valid integer. Handle with try/except ValueError. Common in input parsing, type conversion, and data validation.
7. What is the "os" module primarily used for?
Show answer
Interacting with the operating system: file/directory operations (os.listdir, os.remove, os.makedirs), environment variables (os.environ), path manipulation (os.path.join), and process management (os.getpid). For modern path handling, prefer pathlib. For running shell commands, prefer subprocess over os.system.8. What is PEP 8 and why does it matter for Python code?
Show answer
The official Python style guide promoting consistent, readable code: 4-space indents, snake_case for functions/variables, CamelCase for classes, max 79-char lines. Enforced by linters like ruff, flake8, or pylint. Following PEP 8 is expected in professional Python codebases and code reviews.9. What is the difference between == and is in Python?
Show answer
== checks value equality (whether two objects have equal values), while is checks identity (whether they are the same object in memory).Gotcha: small integers (-5 to 256) and short strings are cached/interned by CPython, so is may appear to work but is unreliable for value comparison. Always use == for values; reserve is for None checks (x is None).
10. What is "slicing" in Python?
Show answer
Accessing a range of items using [start:stop:step] syntax. Works on lists, strings, and tuples. Examples: lst[1:4] gets indices 1-3, lst[::-1] reverses, lst[::2] gets every other element. Slicing returns a new object and never raises IndexError even if indices are out of range — it just returns what is available.11. What is "type casting"?
Show answer
Manually converting a value from one data type to another using built-in constructors: int("42"), float(3), str(100), list("abc"). Also called type conversion. Implicit conversion happens automatically in some cases (int + float yields float). Failed casts raise ValueError or TypeError — always handle these in user-facing code.12. What is the difference between read() and readlines()?
Show answer
read() returns the entire file as one string; readlines() returns a list where each element is one line. For large files, neither is ideal — iterate line by line with for line in file: instead, which is memory-efficient. readline() reads a single line. Always use context managers (with open(...) as f:) to ensure the file is closed.13. What is an "exception"?
Show answer
An error raised during execution that disrupts normal program flow. Python has a hierarchy of built-in exceptions (ValueError, TypeError, KeyError, etc.) all inheriting from BaseException. Handle with try/except/finally blocks. You can define custom exceptions by subclassing Exception. Unhandled exceptions produce a traceback and crash the program.14. What is a "dictionary"?
Show answer
A mutable, unordered (insertion-ordered since Python 3.7) collection of key-value pairs: d = {"name": "Alice", "age": 30}. Keys must be hashable (strings, numbers, tuples). Lookup, insert, and delete are O(1) average. Use .get(key, default) to avoid KeyError. Dicts are the backbone of Python internals — namespaces, kwargs, and JSON all map to dicts.15. What is a virtual environment in Python and why use it?
Show answer
An isolated Python environment with its own installed packages, avoiding dependency conflicts between projects. Create with python -m venv .venv, activate with source .venv/bin/activate. Each venv has its own site-packages. Essential for reproducible builds — without one, pip install affects the system Python and can break other projects.16. What does the open() mode 'w' do?
Show answer
Opens a file for writing and truncates (empties) it immediately — all existing content is lost. If the file does not exist, it is created. This is destructive: accidentally opening a log file with 'w' erases it. Use 'a' to append instead. Always use with open(...) as f: to ensure the file is properly closed.17. What is an "infinite loop"?
Show answer
A loop that never terminates because its exit condition is never met.Example: while True: without a break. Common causes: forgetting to increment a counter, wrong comparison operator, or modifying the wrong variable. Ctrl+C sends KeyboardInterrupt to stop it. Sometimes intentional — e.g., event loops and server main loops use while True with break conditions.
🔴 Hard (6)¶
1. What does the yield keyword do?
Show answer
It turns a function into a generator, allowing it to produce a sequence of values lazily over multiple invocations. Each yield outputs a value and pauses the function; calling next() resumes it. This enables memory-efficient iteration over large datasets since values are generated on demand rather than stored in a list.2. What is a decorator in Python?
Show answer
A decorator is a function that takes another function and extends its behavior without modifying it. The @decorator syntax above a function definition wraps it in additional functionality. Common uses: @staticmethod, @property, logging, access control, memoization. Decorators can be stacked and can accept arguments via a decorator factory pattern.3. What is the purpose of garbage collection in Python?
Show answer
Python manages memory using reference counting (freeing objects when their refcount hits zero) plus a cyclic garbage collector that detects reference cycles (e.g., two objects pointing at each other). The gc module lets you inspect or force collection. Memory leaks can still happen if objects are unintentionally held in global lists, caches, or closures.4. What are args and *kwargs in Python functions?
Show answer
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dictionary. This enables flexible APIs.Example: def log(msg, *args, **kwargs) can accept log("error", code, timestamp=now). Order matters in the signature: regular params, *args, keyword-only params, **kwargs. Overusing them hurts readability — prefer explicit parameters when the interface is known.
5. What is the Global Interpreter Lock (GIL) in Python?
Show answer
In CPython, the GIL is a mutex allowing only one thread to execute Python bytecode at a time. It simplifies memory management but limits true parallelism for CPU-bound tasks. Workarounds: use multiprocessing for CPU-bound work, or asyncio/threading for I/O-bound work where threads release the GIL during waits. Python 3.13+ experiments with GIL-free builds.6. What is a Python generator?