1. What are control structures in Python?
Statements that control the flow of program execution, e.g., conditionals and loops.
2. What are the types of control structures in Python?
Sequential, selection (conditionals), and iteration (loops).
3. What is a sequential control structure?
Execution of statements in the order they appear, line by line.
4. What is a selection control structure?
Execution of statements based on conditions, e.g., `if-else`.
5. What is an iteration control structure?
Repeated execution of statements, e.g., `for` or `while` loops.
6. What is the `if` statement used for?
Executes a block of code if a condition is `True`.
7. What is the syntax of an `if` statement?
`if condition:`, followed by an indented block.
8. What is the `else` statement used for?
Executes a block of code if the `if` condition is `False`.
9. What is the syntax of an `if-else` statement?
`if condition: block1 else: block2`.
10. What is the `elif` statement used for?
Checks additional conditions if previous `if` or `elif` conditions are `False`.
11. What is the syntax of an `if-elif-else` statement?
`if condition1: block1 elif condition2: block2 else: block3`.
12. Can you use multiple `elif` statements in a single `if` block?
Yes, to check multiple conditions sequentially.
13. What happens if no condition in an `if-elif-else` block is `True`?
The `else` block executes, if present; otherwise, no block executes.
14. What is a nested `if` statement?
An `if` statement inside another `if` statement.
15. What is the syntax of a nested `if` statement?
`if condition1: if condition2: block`.
16. What is the purpose of indentation in control structures?
Defines the scope and hierarchy of code blocks in Python.
17. What happens if indentation is incorrect in an `if` statement?
Python raises an `IndentationError`.
18. How many spaces are typically used for indentation in Python?
Four spaces, as per PEP 8 guidelines.
19. Can you use tabs instead of spaces for indentation?
Yes, but spaces are preferred; mixing tabs and spaces causes errors.
20. What is a conditional expression in Python?
A shorthand `if-else` expression, e.g., `x if condition else y`.
21. What is the syntax of a conditional expression?
`value_if_true if condition else value_if_false`.
22. Give an example of a conditional expression.
`status
23. What is the advantage of a conditional expression?
Concise code for simple `if-else` logic.
24. Can you nest conditional expressions?
Yes, e.g., `x if cond1 else y if cond2 else z`.
25. What is a `for` loop used for?
Iterates over a sequence, e.g., list, string, or range.
26. What is the syntax of a `for` loop?
`for variable in sequence: block`.
27. Give an example of a `for` loop iterating over a list.
`for x in [1, 2, 3]: print(x)` prints `1`, `2`, `3`.
28. How do you use a `for` loop with `range()`?
`for i in range(5): print(i)` prints `0`, `1`, `2`, `3`, `4`.
29. What is the `range()` function in a `for` loop?
Generates a sequence of numbers, e.g., `range(1, 6)` yields `1` to `5`.
30. Can you specify a step in `range()`?
Yes, e.g., `range(0, 10, 2)` yields `0`, `2`, `4`, `6`, `8`.
31. What is a `while` loop used for?
Repeats a block as long as a condition is `True`.
32. What is the syntax of a `while` loop?
`while condition: block`.
33. Give an example of a `while` loop.
`x
34. What happens if a `while` loop’s condition never becomes `False`?
The loop runs indefinitely, causing an infinite loop.
35. How do you avoid an infinite `while` loop?
Ensure the condition eventually becomes `False`, e.g., update a counter.
36. What is the `break` statement used for?
Exits the nearest enclosing loop immediately.
37. Give an example of a `break` statement in a `for` loop.
`for i in range(10): if i
38. What is the `continue` statement used for?
Skips the rest of the current loop iteration and proceeds to the next.
39. Give an example of a `continue` statement in a `while` loop.
40. What is the `pass` statement used for in loops?
A placeholder that does nothing, used for empty loop bodies.
41. Give an example of a `pass` statement in an `if` block.
`if x > 5: pass else: print(\"Small\")`.
42. Can `break` be used in nested loops?
Yes, but it only exits the innermost loop.
43. Give an example of `break` in nested loops.
`for i in range(3): for j in range(3): if j
44. What is a loop variable?
A variable that takes on each value in a sequence in a `for` loop.
45. What happens to a loop variable after a `for` loop ends?
It retains the last value from the sequence.
46. Can you modify a loop variable inside a `for` loop?
Yes, but it doesn’t affect the loop’s iteration sequence.
47. What is the `else` clause in a loop used for?
Executes when the loop completes normally, not when terminated by `break`.
48. Give an example of a `for` loop with an `else` clause.
`for i in range(5): print(i) else: print(\"Done\")` prints `0` to `4`, then `\"Done\"`.
49. Give an example of a `while` loop with an `else` clause.
50. Does the `else` clause execute if a loop is terminated by `break`?
No, the `else` clause is skipped.
51. What is a nested loop?
A loop inside another loop, e.g., a `for` loop inside a `while` loop.
52. Give an example of nested loops.
`for i in range(2): for j in range(2): print(i, j)` prints `0 0`, `0 1`, `1 0`, `1 1`.
53. What is the time complexity of a single `for` loop over `n` items?
O(n), where `n` is the number of iterations.
54. What is the time complexity of nested loops with `n` iterations each?
O(n^2), as the inner loop runs `n` times for each outer loop iteration.
55. What is a loop counter?
A variable tracking the number of loop iterations, e.g., `i` in `for i in range(5)`.
56. How do you skip odd numbers in a `for` loop?
Use `if i % 2
57. How do you print even numbers using a `while` loop?
58. What is a sentinel-controlled loop?
A loop that continues until a specific value (sentinel) is encountered.
59. Give an example of a sentinel-controlled loop.
`while (x :
60. What is a counter-controlled loop?
A loop that runs a fixed number of times, e.g., `for i in range(5)`.
61. What is a condition-controlled loop?
A loop that runs until a condition is `False`, e.g., `while x > 0`.
62. How do you iterate over a string using a `for` loop?
`for char in \"hello\": print(char)` prints each character.
63. How do you iterate over a string using a `while` loop?
`s
64. What is the `in` operator used for in loops?
Checks if an item is in a sequence, e.g., `for x in [1, 2, 3]`.
65. Can you use `else` with nested loops?
Yes, it applies to the loop it’s attached to, e.g., the inner loop.
66. How do you exit both loops in a nested loop structure?
Use a flag or `return` in a function, as `break` only exits the innermost loop.
67. What is a loop invariant?
A condition that holds true before and after each loop iteration.
68. What is loop unrolling?
Manually expanding loop iterations to reduce overhead, e.g., for performance.
69. What is a `for` loop’s iterable?
Any object that can return items one at a time, e.g., lists, strings, `range()`.
70. What is an iterator in Python?
An object with `__next__()` method, used by `for` loops.
71. How do you create an iterator from a list?
Use `iter()`, e.g., `it
72. What is the `next()` function used for?
Retrieves the next item from an iterator, e.g., `next(it)`.
73. What happens if `next()` is called on an exhausted iterator?
Raises a `StopIteration` exception.
74. What is the `iter()` function used for?
Returns an iterator from an iterable, e.g., `iter([1, 2])`.
75. Can you use a `for` loop with a dictionary?
Yes, it iterates over keys by default, e.g., `for k in {\"a\": 1}`.
76. How do you iterate over dictionary values in a `for` loop?
Use `.values()`, e.g., `for v in {\"a\": 1}.values()`.
77. How do you iterate over dictionary key-value pairs?
Use `.items()`, e.g., `for k, v in {\"a\": 1}.items()`.
78. What is short-circuit evaluation in Python?
Stopping evaluation when the result is determined, e.g., `False and X` skips `X`.
79. How does short-circuiting work with `and`?
If the first operand is `False`, the second is not evaluated.
80. How does short-circuiting work with `or`?
If the first operand is `True`, the second is not evaluated.
81. Give an example of short-circuiting with `and`.
82. What is a ternary operator in Python?
Another name for conditional expression, e.g., `x if x > 0 else 0`.
83. How do you check multiple conditions in an `if` statement?
Use `and` or `or`, e.g., `if x > 0 and x < 10:`.
84. What is the `match` statement introduced in Python 3.10?
A structural pattern matching statement, similar to `switch` in other languages.
85. What is the syntax of a `match` statement?
`match value: case pattern: block`.
86. Give an example of a `match` statement.
`match x: case 1: print(\"One\") case _: print(\"Other\")`.
87. What is the `_` in a `match` statement?
A wildcard pattern matching any value, like `else`.
88. Can `match` handle complex patterns?
Yes, e.g., matching lists or objects, like `case [1, x]:`.
89. What is a guard in a `match` statement?
An `if` condition in a case, e.g., `case x if x > 0: print(\"Positive\")`.
90. How do you loop until a condition is met?
Use a `while` loop, e.g., `while not valid: input_data()`.
91. What is a `do-while` loop equivalent in Python?
Use a `while True` with `break`, e.g., `while True: x
92. How do you iterate over two lists simultaneously?
Use `zip()`, e.g., `for x, y in zip([1, 2], [3, 4]): print(x, y)`.
93. What is the `enumerate()` function in loops?
Provides index and value, e.g., `for i, v in enumerate([\"a\", \"b\"])` yields `(0, \"a\")`, `(1, \"b\")`.
94. How do you reverse a `for` loop?
Use `reversed()`, e.g., `for i in reversed(range(5)): print(i)` prints `4` to `0`.
95. How do you skip iterations conditionally in a `for` loop?
Use `continue`, e.g., `for i in range(5): if i % 2: continue; print(i)`.
96. What is a loop optimization technique?
Reducing redundant computations, e.g., moving invariants outside the loop.
97. What is a flag variable in loops?
A boolean tracking a condition, e.g., `found
98. How do you count occurrences in a list using a `for` loop?
`count
99. How do you sum numbers in a list using a `while` loop?
`total
100. What is a loop termination condition?
The condition that stops a loop, e.g., `i < 5` in `while i < 5`.
101. How do you handle empty sequences in a `for` loop?
The loop body doesn’t execute, and `else` runs if present.
102. What is a loop invariant example?
In a sum loop, `total` equals the sum of processed elements.
103. How do you check if a number is prime using a `for` loop?
`for i in range(2, n): if n % i
104. What is the `all()` function with loops?
Checks if all items satisfy a condition, e.g., `all(x > 0 for x in lst)`.
105. What is the `any()` function with loops?
Checks if any item satisfies a condition, e.g., `any(x < 0 for x in lst)`.
106. How do you implement a countdown using a `while` loop?
107. How do you iterate over a range with negative step?
`for i in range(10, -1, -1): print(i)` prints `10` to `0`.
108. What is a comprehension equivalent of a `for` loop?
A list comprehension, e.g., `[x * 2 for x in range(5)]` vs. a loop.
109. How do you avoid nested loops for performance?
Use set operations or dictionaries for lookups, e.g., `if x in set(lst)`.
110. What is a loop unrolling example?
Replacing `for i in range(4): lst[i]
111. How do you simulate a `for` loop with a `while` loop?
`i
112. What is the `map()` function with loops?
Applies a function to each item, e.g., `map(str, [1, 2])` yields `\"1\"`, `\"2\"`.
113. What is the `filter()` function with loops?
Selects items based on a condition, e.g., `filter(lambda x: x > 0, lst)`.
114. How do you iterate over a file line by line?
`for line in open(\"file.txt\"): print(line)`.
115. What is a generator expression in loops?
A memory-efficient iterable, e.g., `(x * 2 for x in range(5))`.
116. What is the difference between a generator and a list comprehension?
Generator yields items one at a time; list stores all items in memory.
117. How do you debug a loop in Python?
Use `print()` statements or a debugger to inspect variables each iteration.
118. What is a common loop-related error?
Off-by-one errors, e.g., iterating to `n` instead of `n-1`.
119. How do you handle loop-related infinite recursion?
Ensure a base case or condition stops the loop, e.g., decrement a counter.
120. What is database connectivity in Python?
Interfacing Python with databases like SQLite or MySQL to perform operations.
121. What is a database in the context of Python?
A structured collection of data, accessed via Python modules like `sqlite3`.
122. What is the `sqlite3` module in Python?
A built-in module for SQLite database operations, e.g., `import sqlite3`.
123. What is SQLite in Python?
A lightweight, serverless database integrated with Python via `sqlite3`.
124. What is the `mysql-connector-python` module?
A library for connecting Python to MySQL databases, e.g., `import mysql.connector`.
125. How do you install `mysql-connector-python`?
Use `pip`, e.g., `pip install mysql-connector-python`.
126. How do you connect to an SQLite database?
Use `sqlite3.connect()`, e.g., `conn
127. How do you connect to a MySQL database?
Use `mysql.connector.connect()`, e.g., `conn
128. What is a database connection object?
An object managing database interactions, e.g., `conn` from `sqlite3.connect()`.
129. What is a cursor object in database connectivity?
An object to execute SQL queries, e.g., `cursor
130. How do you create a cursor object in SQLite?
Call `cursor()` on the connection, e.g., `cursor
131. How do you create a cursor object in MySQL?
Same as SQLite, e.g., `cursor
132. What is the `execute()` method of a cursor?
Runs an SQL query, e.g., `cursor.execute(\"SELECT * FROM table\")`.
133. How do you create a table in SQLite?
Use `CREATE TABLE`, e.g., `cursor.execute(\"CREATE TABLE users (id INT, name TEXT)\")`.
134. How do you create a table in MySQL?
Same as SQLite, e.g., `cursor.execute(\"CREATE TABLE users (id INT, name VARCHAR(50))\")`.
135. What is the `commit()` method in database connectivity?
Saves changes to the database, e.g., `conn.commit()`.
136. What is the `rollback()` method in database connectivity?
Undoes changes since the last commit, e.g., `conn.rollback()`.
137. How do you insert data into a table?
Use `INSERT INTO`, e.g., `cursor.execute(\"INSERT INTO users VALUES (1, \'Alice\')\")`.
138. How do you retrieve data from a table?
Use `SELECT`, e.g., `cursor.execute(\"SELECT * FROM users\")`.
139. How do you fetch query results in Python?
Use `fetchall()`, `fetchone()`, or `fetchmany()`, e.g., `cursor.fetchall()`.
140. What does `fetchall()` return?
A list of all query result rows, e.g., `[(1, \'Alice\'), (2, \'Bob\')]`.
141. What does `fetchone()` return?
The next row of query results, or `None`, e.g., `(1, \'Alice\')`.
142. What does `fetchmany(size)` return?
A list of up to `size` rows, e.g., `cursor.fetchmany(2)` for two rows.
143. How do you update data in a table?
Use `UPDATE`, e.g., `cursor.execute(\"UPDATE users SET name
144. How do you delete data from a table?
Use `DELETE`, e.g., `cursor.execute(\"DELETE FROM users WHERE id
145. What is a parameterized query?
A query using placeholders for safe data insertion, e.g., `cursor.execute(\"INSERT INTO users VALUES (?, ?)\", (1, \"Alice\"))`.
146. Why use parameterized queries?
Prevents SQL injection by safely handling user input.
147. How do you use placeholders in SQLite?
Use `?`, e.g., `cursor.execute(\"SELECT * FROM users WHERE id
148. How do you use placeholders in MySQL?
Use `%s`, e.g., `cursor.execute(\"SELECT * FROM users WHERE id
149. How do you close a database connection?
Use `close()`, e.g., `conn.close()`.
150. How do you close a cursor?
Use `close()`, e.g., `cursor.close()`.
151. What is the `with` statement in database connectivity?
Ensures connections are closed, e.g., `with sqlite3.connect(\"mydb.db\") as conn:`.
152. How do you handle database errors in Python?
Use `try-except`, e.g., `try: cursor.execute(...) except sqlite3.Error: print(\"Error\")`.
153. What is a `sqlite3.OperationalError`?
Raised for database operation issues, e.g., table not found.
154. What is a `mysql.connector.DatabaseError`?
Raised for MySQL database errors, e.g., connection failure.
155. How do you check if a table exists in SQLite?
Query `sqlite_master`, e.g., `cursor.execute(\"SELECT name FROM sqlite_master WHERE type
156. How do you check if a table exists in MySQL?
Use `SHOW TABLES`, e.g., `cursor.execute(\"SHOW TABLES LIKE \'users\'\")`.
157. What is a primary key in a database table?
A unique identifier for rows, e.g., `id INT PRIMARY KEY`.
158. What is a foreign key in a database?
A field linking to another table’s primary key, e.g., `user_id INT, FOREIGN KEY(user_id) REFERENCES users(id)`.
159. How do you drop a table in SQLite?
Use `DROP TABLE`, e.g., `cursor.execute(\"DROP TABLE IF EXISTS users\")`.
160. How do you drop a table in MySQL?
Same as SQLite, e.g., `cursor.execute(\"DROP TABLE IF EXISTS users\")`.
161. What is a SQL `JOIN` in database queries?
Combines rows from multiple tables, e.g., `SELECT * FROM users JOIN orders ON users.id
162. What is an `INNER JOIN`?
Returns rows with matching values in both tables, e.g., `INNER JOIN orders ON users.id
163. What is a `LEFT JOIN`?
Returns all rows from the left table, with matches or `NULL` from the right, e.g., `LEFT JOIN orders`.
164. What is a `RIGHT JOIN`?
Returns all rows from the right table, with matches or `NULL` from the left, e.g., `RIGHT JOIN orders`.
165. What is a `FULL JOIN`?
Returns all rows when there’s a match in either table, e.g., `FULL JOIN orders`.
166. How do you group data in a SQL query?
Use `GROUP BY`, e.g., `SELECT COUNT(*) FROM users GROUP BY age`.
167. What is the `HAVING` clause in SQL?
Filters grouped data, e.g., `SELECT age FROM users GROUP BY age HAVING COUNT(*) > 1`.
168. How do you sort query results in SQL?
Use `ORDER BY`, e.g., `SELECT * FROM users ORDER BY name ASC`.
169. What is the `LIMIT` clause in SQL?
Restricts the number of rows returned, e.g., `SELECT * FROM users LIMIT 5`.
170. What is a database transaction?
A sequence of operations treated as a single unit, e.g., `INSERT` then `UPDATE`.
171. How do you start a transaction in Python?
Use `conn.commit()` or `conn.rollback()` after operations, no explicit start needed.
172. What is the `autocommit` mode in SQLite?
Commits changes automatically, enabled with `conn.autocommit
173. What is the `autocommit` mode in MySQL?
Similar to SQLite, enabled with `conn.autocommit(True)`.
174. How do you execute multiple SQL statements at once?
Use `executescript()` in SQLite, e.g., `cursor.executescript(\"CREATE TABLE ...; INSERT ...\")`.
175. How do you execute multiple parameterized queries?
Use `executemany()`, e.g., `cursor.executemany(\"INSERT INTO users VALUES (?, ?)\", [(1, \"Alice\"), (2, \"Bob\")])`.
176. What is the `rowcount` attribute of a cursor?
Returns the number of rows affected, e.g., `cursor.rowcount` after `UPDATE`.
177. What is the `description` attribute of a cursor?
Returns column metadata, e.g., `cursor.description` after a `SELECT`.
178. How do you get column names from a query?
Use `cursor.description`, e.g., `[col[0] for col in cursor.description]`.
179. What is a database schema?
The structure of a database, e.g., tables, columns, and relationships.
180. How do you alter a table in SQLite?
Use `ALTER TABLE`, e.g., `cursor.execute(\"ALTER TABLE users ADD COLUMN age INT\")`.
181. How do you alter a table in MySQL?
Same as SQLite, e.g., `cursor.execute(\"ALTER TABLE users ADD age INT\")`.
182. What is a SQL injection attack?
Injecting malicious SQL via user input, e.g., `\"; DROP TABLE users;\"`.
183. How do you prevent SQL injection in Python?
Use parameterized queries, e.g., `cursor.execute(\"SELECT * FROM users WHERE id
184. What is the Python Database API (DB-API)?
A standard for database interfaces, e.g., `sqlite3` and `mysql-connector` comply.
185. What is a connection pool in database connectivity?
A cache of database connections, e.g., using `mysql.connector.pooling`.
186. How do you create a connection pool in MySQL?
Use `mysql.connector.pooling.MySQLConnectionPool`, e.g., `pool
187. What is the `row_factory` in SQLite?
Customizes row objects, e.g., `conn.row_factory
188. How do you access rows as dictionaries in SQLite?
Set `row_factory`, e.g., `conn.row_factory
189. How do you access rows as dictionaries in MySQL?
Use `dictionary
190. What is an index in a database?
A structure to speed up queries, e.g., `CREATE INDEX idx_name ON users(name)`.
191. How do you create an index in SQLite?
Use `CREATE INDEX`, e.g., `cursor.execute(\"CREATE INDEX idx_id ON users(id)\")`.
192. How do you create an index in MySQL?
Same as SQLite, e.g., `cursor.execute(\"CREATE INDEX idx_id ON users(id)\")`.
193. What is a view in a database?
A virtual table based on a query, e.g., `CREATE VIEW user_view AS SELECT name FROM users`.
194. How do you create a view in SQLite?
Use `CREATE VIEW`, e.g., `cursor.execute(\"CREATE VIEW user_view AS SELECT * FROM users\")`.
195. How do you create a view in MySQL?
Same as SQLite, e.g., `cursor.execute(\"CREATE VIEW user_view AS SELECT * FROM users\")`.
196. What is a stored procedure in MySQL?
A precompiled SQL routine, e.g., `CREATE PROCEDURE get_users() BEGIN SELECT * FROM users; END`.
197. How do you call a stored procedure in MySQL?
Use `CALL`, e.g., `cursor.execute(\"CALL get_users()\")`.
198. What is a trigger in a database?
An automatic action on table events, e.g., `CREATE TRIGGER log AFTER INSERT ON users`.
199. How do you create a trigger in MySQL?
Use `CREATE TRIGGER`, e.g., `cursor.execute(\"CREATE TRIGGER log AFTER INSERT ON users FOR EACH ROW INSERT INTO logs VALUES (NEW.id)\")`.
200. What is the `lastrowid` attribute of a cursor?
Returns the ID of the last inserted row, e.g., `cursor.lastrowid`.
201. How do you handle large datasets in Python?
Fetch rows incrementally, e.g., `while row :
202. What is the `executemany()` method’s benefit?
Optimizes bulk inserts, e.g., `cursor.executemany(\"INSERT INTO users VALUES (?, ?)\", data)`.
203. What is a database constraint?
A rule like `NOT NULL` or `UNIQUE`, e.g., `id INT NOT NULL`.
204. What is the `UNIQUE` constraint?
Ensures column values are unique, e.g., `email VARCHAR(50) UNIQUE`.
205. What is the `CHECK` constraint?
Enforces a condition, e.g., `age INT CHECK(age >
206. How do you enable foreign key support in SQLite?
Execute `PRAGMA foreign_keys
207. What is the `sqlite3.Error` base class?
The base for SQLite exceptions, e.g., `OperationalError` inherits from it.
208. What is a `mysql.connector.Error` base class?
The base for MySQL exceptions, e.g., `DatabaseError` inherits from it.
209. How do you get the SQLite version in Python?
Use `sqlite3.sqlite_version`, e.g., `print(sqlite3.sqlite_version)`.
210. How do you get the MySQL version in Python?
Query `SELECT VERSION()`, e.g., `cursor.execute(\"SELECT VERSION()\"); cursor.fetchone()`.
211. What is the `cursorclass` in MySQL?
Customizes cursor type, e.g., `conn.cursor(cursorclass
212. What is a database dump?
A file with SQL commands to recreate a database, e.g., exported via `mysqldump`.
213. How do you import a database dump in MySQL?
Use `source` in MySQL client or execute dump SQL in Python.
214. What is the `SQLAlchemy` library in Python?
An ORM and SQL toolkit, e.g., for abstracting database operations.
215. What is an ORM in database connectivity?
Object-Relational Mapping, e.g., mapping Python classes to database tables.
216. How do you use `SQLAlchemy` for SQLite?
Create an engine, e.g., `from sqlalchemy import create_engine; engine
217. What is a prepared statement in MySQL?
A precompiled query, e.g., `cursor.execute(\"PREPARE stmt FROM \'SELECT * FROM users WHERE id
218. What is the `rowid` in SQLite?
A unique row identifier, e.g., `SELECT rowid, * FROM users`.
219. How do you backup an SQLite database in Python?
Use `conn.backup()`, e.g., `conn.backup(target_conn)`.
220. What is the `pymysql` library in Python?
An alternative MySQL connector, e.g., `import pymysql; conn
221. What is a dictionary in Python?
A mutable, unordered collection of key-value pairs, e.g., `{\"a\": 1, \"b\": 2}`.
222. What is a set in Python?
A mutable, unordered collection of unique elements, e.g., `{1, 2, 3}`.
223. How do you create an empty dictionary?
Use curly braces `{}` or `dict()`.
224. How do you create an empty set?
Use `set()`, as `{}` creates an empty dictionary.
225. What is the key difference between a dictionary and a set?
Dictionaries store key-value pairs; sets store unique values.
226. How do you create a dictionary with elements?
Use curly braces, e.g., `my_dict
227. How do you create a set with elements?
Use curly braces or `set()`, e.g., `my_set
228. What types can be dictionary keys?
Immutable types like strings, numbers, or tuples (if hashable).
229. What types can be set elements?
Immutable, hashable types like strings, numbers, or tuples.
230. Why can’t lists be dictionary keys or set elements?
Lists are mutable and unhashable.
231. How do you access a dictionary value?
Use the key, e.g., `my_dict[\"name\"]` returns `\"Alice\"`.
232. What happens if you access a non-existent dictionary key?
Raises a `KeyError`, e.g., `my_dict[\"invalid\"]`.
233. How do you use the `get()` method for dictionaries?
Returns a value or `None` if the key is missing, e.g., `my_dict.get(\"age\")`.
234. Can `get()` provide a default value?
Yes, e.g., `my_dict.get(\"score\", 0)` returns `0` if `\"score\"` is missing.
235. How do you add a key-value pair to a dictionary?
Assign a value, e.g., `my_dict[\"city\"]
236. How do you update a dictionary value?
Reassign the key, e.g., `my_dict[\"age\"]
237. How do you remove a key-value pair from a dictionary?
Use `pop()` or `del`, e.g., `my_dict.pop(\"age\")` or `del my_dict[\"age\"]`.
238. What does `pop()` return for dictionaries?
The value of the removed key, e.g., `my_dict.pop(\"name\")` returns `\"Alice\"`.
239. What is the `popitem()` method for dictionaries?
Removes and returns the last key-value pair, e.g., `my_dict.popitem()`.
240. What is the `clear()` method for dictionaries?
Removes all key-value pairs, e.g., `my_dict.clear()` results in `{}`.
241. How do you add an element to a set?
Use `add()`, e.g., `my_set.add(4)`.
242. How do you remove an element from a set?
Use `remove()` or `discard()`, e.g., `my_set.remove(1)`.
243. What is the difference between `remove()` and `discard()` for sets?
`remove()` raises `KeyError` if the element is missing; `discard()` does not.
244. What is the `pop()` method for sets?
Removes and returns an arbitrary element, e.g., `my_set.pop()`.
245. What is the `clear()` method for sets?
Removes all elements, e.g., `my_set.clear()` results in `set()`.
246. What is the `keys()` method for dictionaries?
Returns a view of keys, e.g., `my_dict.keys()`.
247. What is the `values()` method for dictionaries?
Returns a view of values, e.g., `my_dict.values()`.
248. What is the `items()` method for dictionaries?
Returns a view of key-value pairs, e.g., `my_dict.items()`.
249. What is a dictionary view object?
A dynamic view reflecting changes in the dictionary, e.g., `my_dict.keys()`.
250. How do you iterate over dictionary keys?
Use `for k in my_dict:` or `for k in my_dict.keys():`.
251. How do you iterate over dictionary values?
Use `for v in my_dict.values():`.
252. How do you iterate over dictionary key-value pairs?
Use `for k, v in my_dict.items():`.
253. What is the `update()` method for dictionaries?
Updates with key-value pairs, e.g., `my_dict.update({\"city\": \"Paris\"})`.
254. What is the `setdefault()` method for dictionaries?
Returns or sets a default value if the key is missing, e.g., `my_dict.setdefault(\"score\", 0)`.
255. What is the `in` operator for dictionaries?
Checks if a key exists, e.g., `\"name\" in my_dict` returns `True`.
256. What is the `in` operator for sets?
Checks if an element exists, e.g., `1 in my_set` returns `True`.
257. What is the `len()` function for dictionaries and sets?
Returns the number of key-value pairs or elements, e.g., `len(my_dict)`.
258. What is a dictionary comprehension?
A concise way to create a dictionary, e.g., `{x: x*2 for x in range(3)}`.
259. What is a set comprehension?
A concise way to create a set, e.g., `{x*2 for x in range(3)}`.
260. Give an example of a dictionary comprehension with a condition.
`{k: v for k, v in zip([\"a\", \"b\"], [1, 2]) if v > 1}` returns `{\"b\": 2}`.
261. What is the `union()` method for sets?
Returns a set with all elements, e.g., `{1, 2}.union({2, 3})` is `{1, 2, 3}`.
262. What is the `|` operator for sets?
Performs union, e.g., `{1, 2} | {2, 3}` is `{1, 2, 3}`.
263. What is the `intersection()` method for sets?
Returns common elements, e.g., `{1, 2}.intersection({2, 3})` is `{2}`.
264. What is the `&` operator for sets?
Performs intersection, e.g., `{1, 2} & {2, 3}` is `{2}`.
265. What is the `difference()` method for sets?
Returns elements in one set but not another, e.g., `{1, 2}.difference({2, 3})` is `{1}`.
266. What is the `-` operator for sets?
Performs difference, e.g., `{1, 2} - {2, 3}` is `{1}`.
267. What is the `symmetric_difference()` method for sets?
Returns elements in either set but not both, e.g., `{1, 2}.symmetric_difference({2, 3})` is `{1, 3}`.
268. What is the `^` operator for sets?
Performs symmetric difference, e.g., `{1, 2} ^ {2, 3}` is `{1, 3}`.
269. What is the `issubset()` method for sets?
Checks if a set is a subset, e.g., `{1, 2}.issubset({1, 2, 3})` is `True`.
270. What is the `<
Checks if a set is a subset, e.g., `{1, 2} <
271. What is the `issuperset()` method for sets?
Checks if a set contains another, e.g., `{1, 2, 3}.issuperset({1, 2})` is `True`.
272. What is the `>
Checks if a set is a superset, e.g., `{1, 2, 3} >
273. What is a frozen set in Python?
An immutable set, e.g., `frozenset([1, 2, 3])`.
274. How do you create a frozen set?
Use `frozenset()`, e.g., `frozenset({1, 2})`.
275. What is the key difference between a set and a frozen set?
Sets are mutable; frozen sets are immutable and hashable.
276. Can frozen sets be dictionary keys?
Yes, due to immutability, unlike regular sets.
277. What is the `copy()` method for dictionaries?
Creates a shallow copy, e.g., `new_dict
278. What is the `copy()` method for sets?
Creates a new set with the same elements, e.g., `new_set
279. What is a shallow copy for dictionaries?
Copies the dictionary, but nested objects are referenced.
280. What is the `deepcopy()` function for dictionaries?
Creates a deep copy, duplicating nested objects, e.g., `copy.deepcopy(my_dict)`.
281. What is the time complexity of accessing a dictionary key?
O(1) average case, due to hash table implementation.
282. What is the time complexity of adding an element to a set?
283. What is the time complexity of set intersection?
O(min(len(s1), len(s2))), iterating over the smaller set.
284. What is the `collections.defaultdict`?
A dictionary with default values for missing keys, e.g., `defaultdict(int)`.
285. Give an example of `defaultdict`.
`from collections import defaultdict; d
286. What is the `collections.OrderedDict`?
A dictionary preserving insertion order (default in Python 3.7+).
287. What is the `collections.Counter` for sets?
Counts hashable elements, e.g., `Counter([1, 1, 2])` is `{1: 2, 2: 1}`.
288. How do you merge two dictionaries?
Use `|`, e.g., `d1 | d2` (Python 3.9+), or `d1.update(d2)`.
289. What is the `fromkeys()` method for dictionaries?
Creates a dictionary with specified keys, e.g., `dict.fromkeys([\"a\", \"b\"], 0)`.
290. What is a hash table in the context of dictionaries?
The underlying data structure for O(1) lookups.
291. What is a dictionary’s `__getitem__` method?
Implements key access, e.g., `my_dict.__getitem__(\"key\")`.
292. What is a set’s `__contains__` method?
Implements `in`, e.g., `my_set.__contains__(1)` checks if `1` is in the set.
293. How do you check if a dictionary is empty?
Use `if not my_dict:` or `len(my_dict)
294. How do you convert a list of tuples to a dictionary?
Use `dict()`, e.g., `dict([(\"a\", 1), (\"b\", 2)])` is `{\"a\": 1, \"b\": 2}`.
295. How do you sort a dictionary by values?
Use `sorted()`, e.g., `sorted(my_dict.items(), key
296. What is a dictionary’s `__len__` method?
Implements `len()`, e.g., `my_dict.__len__()` returns the number of pairs.
297. What is a set’s `isdisjoint()` method?
Checks if two sets have no common elements, e.g., `{1, 2}.isdisjoint({3, 4})` is `True`.
298. What is the `difference_update()` method for sets?
Removes elements from another set in place, e.g., `s1.difference_update(s2)`.
299. What is the `intersection_update()` method for sets?
Keeps only common elements in place, e.g., `s1.intersection_update(s2)`.
300. What is the `symmetric_difference_update()` method for sets?
Keeps elements in either set but not both, e.g., `s1.symmetric_difference_update(s2)`.
301. What is a dictionary’s key hashability requirement?
Keys must be immutable and implement `__hash__()`.
302. How do you handle dictionary key collisions?
Python’s hash table resolves collisions internally using open addressing.
303. What is the `collections.ChainMap`?
Combines multiple dictionaries, e.g., `ChainMap(d1, d2)` for layered lookups.
304. How do you get unique elements from a list using a set?
Use `list(set(my_list))`, e.g., `list(set([1, 2, 2]))` is `[1, 2]`.
305. What is the memory overhead of a dictionary vs. a list?
Dictionaries use more memory due to hash table storage.
306. What is a dictionary’s `__setitem__` method?
Implements key-value assignment, e.g., `my_dict.__setitem__(\"key\", \"value\")`.
307. What is a set’s `__or__` method?
Implements union, e.g., `s1.__or__(s2)` for `s1 | s2`.
308. How do you check if two sets are equal?
Use `
309. What is a dictionary’s `__iter__` method?
Returns an iterator over keys, e.g., `iter(my_dict)`.
310. How do you invert a dictionary (swap keys and values)?
Use a comprehension, e.g., `{v: k for k, v in my_dict.items()}`.
311. What is the pitfall of inverting a dictionary?
Values must be unique and hashable, or data is lost.
312. What is a dictionary’s sparsity?
Ability to store non-contiguous keys efficiently, unlike lists.
313. How do you create a dictionary from two lists?
Use `zip()`, e.g., `dict(zip([\"a\", \"b\"], [1, 2]))` is `{\"a\": 1, \"b\": 2}`.
314. What is a set’s hash table implementation?
Uses a hash table for O(1) average-case membership testing.
315. What is the `types.MappingProxyType`?
Creates a read-only dictionary view, e.g., `MappingProxyType(my_dict)`.
316. How do you check for duplicate keys in a dictionary?
Later assignments overwrite earlier ones, e.g., `{\"a\": 1, \"a\": 2}` keeps `\"a\": 2`.
317. What is a dictionary’s `__missing__` method?
Handles missing keys in subclasses, e.g., in `defaultdict`.
318. What is a set’s `__and__` method?
Implements intersection, e.g., `s1.__and__(s2)` for `s1 & s2`.
319. What is an exception in Python?
An error that occurs during program execution, e.g., `ZeroDivisionError`.
320. What is exception handling in Python?
Managing errors using `try`, `except`, `else`, and `finally` blocks.
321. How do you handle an exception in Python?
Use a `try-except` block, e.g., `try: x
322. What is the purpose of the `try` block?
Contains code that might raise an exception, e.g., `try: int(\"abc\")`.
323. What is the purpose of the `except` block?
Handles specific exceptions, e.g., `except ValueError: print(\"Invalid input\")`.
324. Can you handle multiple exceptions in one `except` block?
Yes, use a tuple, e.g., `except (ValueError, TypeError): print(\"Error\")`.
325. How do you handle all exceptions?
Use a bare `except` or `except Exception:`, e.g., `except Exception: print(\"Error\")`.
326. What is the `else` block in exception handling?
Runs if no exception occurs, e.g., `try: x
327. What is the `finally` block in exception handling?
Always runs, regardless of exceptions, e.g., `finally: print(\"Cleanup\")`.
328. What is the use of `finally` in file handling?
Ensures resources are closed, e.g., `finally: f.close()`.
329. What is the `raise` keyword in Python?
Manually raises an exception, e.g., `raise ValueError(\"Invalid\")`.
330. How do you re-raise an exception?
Use `raise` in an `except` block, e.g., `except ValueError: raise`.
331. What is a built-in exception in Python?
A predefined error type, e.g., `ValueError`, `TypeError`, `KeyError`.
332. What is the `Exception` class in Python?
The base class for all built-in exceptions, e.g., `ValueError` inherits from it.
333. What is a `ZeroDivisionError`?
Raised when dividing by zero, e.g., `1/0`.
334. What is a `ValueError`?
Raised for invalid values, e.g., `int(\"abc\")`.
335. What is a `TypeError`?
Raised for invalid type operations, e.g., `\"1\" + 1`.
336. What is a `KeyError`?
Raised for missing dictionary keys, e.g., `d[\"missing\"]`.
337. What is an `IndexError`?
Raised for invalid list indices, e.g., `lst[10]` for a 5-element list.
338. What is a `FileNotFoundError`?
Raised when a file is not found, e.g., `open(\"missing.txt\")`.
339. What is a `NameError`?
Raised for undefined variables, e.g., `print(undefined_var)`.
340. What is an `AttributeError`?
Raised for invalid attribute access, e.g., `\"abc\".invalid`.
341. What is a `StopIteration`?
Raised by iterators when exhausted, e.g., `next(iter([]))`.
342. What is an `OverflowError`?
Raised for numeric overflow, e.g., exceeding maximum integer limits.
343. What is a `MemoryError`?
Raised when memory is exhausted, e.g., creating a massive list.
344. How do you create a custom exception?
Define a class inheriting from `Exception`, e.g., `class MyError(Exception): pass`.
345. Give an example of raising a custom exception.
`class MyError(Exception): pass; raise MyError(\"Custom error\")`.
346. How do you add attributes to a custom exception?
Define in `__init__`, e.g., `class MyError(Exception): def __init__(self, msg, code): super().__init__(msg); self.code
347. What is the `BaseException` class?
The root class for all exceptions, e.g., `Exception` inherits from it.
348. What exceptions inherit directly from `BaseException`?
`Exception`, `SystemExit`, `KeyboardInterrupt`, `GeneratorExit`.
349. What is a `SystemExit` exception?
Raised by `sys.exit()`, e.g., `sys.exit(1)`.
350. What is a `KeyboardInterrupt` exception?
Raised when the user presses Ctrl+C.
351. What is the hierarchy of exceptions in Python?
`BaseException` > `Exception` > specific exceptions like `ValueError`.
352. How do you catch a specific exception before a general one?
Order `except` blocks from specific to general, e.g., `except ValueError:` before `except Exception:`.
353. What happens if `except` blocks are in the wrong order?
General exceptions catch everything, making specific ones unreachable.
354. What is an exception’s traceback?
A report of the call stack when an exception occurs.
355. How do you access an exception’s traceback?
Use `traceback` module, e.g., `traceback.print_exc()`.
356. What is the `sys.exc_info()` function?
Returns `(type, value, traceback)` of the current exception.
357. How do you print an exception’s message?
Use `str(e)`, e.g., `except ValueError as e: print(str(e))`.
358. What is the `as` keyword in an `except` block?
Binds the exception to a variable, e.g., `except ValueError as e:`.
359. How do you log exceptions in Python?
Use `logging`, e.g., `import logging; logging.exception(\"Error occurred\")`.
360. What is the `assert` statement in Python?
Raises `AssertionError` if a condition is false, e.g., `assert x > 0`.
361. What is an `AssertionError`?
Raised by failed `assert` statements, e.g., `assert False`.
362. How do you disable assertions in Python?
Run with `-O` or `-OO` flags, e.g., `python -O script.py`.
363. What is the `try` block’s scope in exception handling?
Only code within `try` is monitored for exceptions.
364. Can you nest `try-except` blocks?
Yes, e.g., `try: try: x
365. What is exception chaining in Python?
Linking exceptions, e.g., `raise ValueError from TypeError`.
366. How do you access the chained exception?
Use `__cause__` or `__context__`, e.g., `e.__cause__`.
367. What is the `from` keyword in `raise`?
Sets the cause of an exception, e.g., `raise ValueError(\"Error\") from exc`.
368. What is the `__context__` attribute of an exception?
Stores the previous exception in implicit chaining.
369. What is the `__cause__` attribute of an exception?
Stores the explicit cause set by `raise ... from`.
370. What is the `warnings` module in Python?
Handles warning messages, e.g., `warnings.warn(\"Deprecated\")`.
371. What is a `Warning` exception?
A base class for warnings, e.g., `DeprecationWarning`.
372. How do you suppress warnings in Python?
Use `warnings.filterwarnings(\"ignore\")`.
373. What is a `DeprecationWarning`?
Warns about deprecated features, e.g., old functions.
374. What is a `RuntimeWarning`?
Warns about runtime issues, e.g., ambiguous operations.
375. How do you catch warnings as exceptions?
Use `warnings.catch_warnings()`, e.g., `with warnings.catch_warnings(record
376. What is the `traceback` module in Python?
Provides tools to format and print exception stack traces.
377. How do you format a traceback?
Use `traceback.format_exc()`, e.g., `print(traceback.format_exc())`.
378. What is the `logging.exception()` function?
Logs an exception with a stack trace, e.g., `logging.exception(\"Error\")`.
379. What is the difference between `Exception` and `BaseException`?
`Exception` is for catchable errors; `BaseException` includes `SystemExit`, etc.
380. Why should you avoid catching `BaseException`?
It catches system-level exits like `SystemExit`, disrupting program flow.
381. What is the `contextlib.suppress` function?
Suppresses specified exceptions, e.g., `with suppress(FileNotFoundError): open(\"file.txt\")`.
382. How do you create a custom exception hierarchy?
Define subclasses, e.g., `class MyBaseError(Exception): pass; class MySpecificError(MyBaseError): pass`.
383. What is the `errno` module in exception handling?
Provides system error codes, e.g., `errno.ENOENT` for file not found.
384. What is an `OSError`?
Raised for system-related errors, e.g., file access issues.
385. What is an `IOError`?
An alias for `OSError`, used for I/O-related errors.
386. What is a `PermissionError`?
Raised for access-denied errors, e.g., writing to a read-only file.
387. What is a `TimeoutError`?
Raised for operations exceeding time limits, e.g., network timeouts.
388. How do you handle multiple exceptions with different actions?
Use separate `except` blocks, e.g., `except ValueError: print(\"Value\") except TypeError: print(\"Type\")`.
389. What is the `try-except` performance impact?
Minimal overhead unless an exception is raised, then costly due to stack unwinding.
390. What is stack unwinding in exception handling?
Reversing the call stack to find an exception handler.
391. How do you debug exceptions in Python?
Use `traceback.print_exc()` or a debugger like `pdb`.
392. What is the `pdb` module in exception handling?
A debugger to inspect exceptions, e.g., `pdb.post_mortem()`.
393. What is the `except ... as e` syntax benefit?
Allows access to exception details, e.g., `e.args` for error message.
394. What is the `args` attribute of an exception?
A tuple of arguments passed to the exception, e.g., `ValueError(\"msg\").args`.
395. What is the `__traceback__` attribute of an exception?
Stores the traceback object, e.g., `e.__traceback__`.
396. How do you create an exception with a custom message?
Pass a message, e.g., `raise ValueError(\"Custom message\")`.
397. What is the `with` statement’s role in exception handling?
Manages resources and handles exceptions, e.g., `with open(\"file.txt\"):`.
398. What is a `try-finally` block used for?
Ensures cleanup without handling exceptions, e.g., `try: x
399. Can you combine `try-except` and `try-finally`?
Yes, e.g., `try: x
400. What is the `contextlib` module in exception handling?
Provides utilities like `suppress` and `ExitStack` for exception management.
401. What is the `ExitStack` class in `contextlib`?
Manages multiple context managers, e.g., `with ExitStack() as stack:`.
402. How do you test exception handling in Python?
Use `unittest` or `pytest`, e.g., `with self.assertRaises(ValueError): int(\"abc\")`.
403. What is the `unittest.TestCase.assertRaises` method?
Tests if an exception is raised, e.g., `self.assertRaises(ValueError, int, \"abc\")`.
404. What is a bare `raise` statement?
Re-raises the current exception, preserving its context.
405. What is the `sys.excepthook` function?
Handles uncaught exceptions, e.g., `sys.excepthook
406. How do you customize exception printing?
Override `sys.excepthook`, e.g., `def custom_hook(type, value, tb): print(\"Custom error\")`.
407. What is the `warnings.catch_warnings` context manager?
Captures warnings, e.g., `with catch_warnings(record
408. What is a `SyntaxError`?
Raised for invalid Python syntax, e.g., `print(\"hi\"`.
409. What is an `IndentationError`?
Raised for incorrect indentation, e.g., mismatched indent levels.
410. What is a `TabError`?
Raised for inconsistent use of tabs and spaces.
411. What is a `UnicodeError`?
Raised for Unicode encoding/decoding issues, e.g., invalid UTF-8.
412. What is a `ResourceWarning`?
Warns about unclosed resources, e.g., unclosed files.
413. How do you suppress specific exceptions without handling them?
Use `contextlib.suppress`, e.g., `with suppress(KeyError): d[\"missing\"]`.
414. What is the `exceptiongroup` in Python 3.11+?
Allows raising multiple exceptions, e.g., `ExceptionGroup(\"errors\", [ValueError(), TypeError()])`.
415. How do you handle an `ExceptionGroup`?
Use `except*`, e.g., `try: raise ExceptionGroup(...) except* ValueError: print(\"Caught\")`.
416. What is the `atexit` module in exception handling?
Registers cleanup functions on program exit, e.g., `atexit.register(cleanup)`.
417. What is the `signal` module in exception handling?
Handles system signals, e.g., `signal.signal(signal.SIGINT, handler)` for Ctrl+C.
418. What is the difference between errors and exceptions?
Errors are issues (syntax or runtime); exceptions are runtime errors you can handle.
419. How do you handle exceptions in a loop without breaking?
Place `try-except` inside the loop, e.g., `for i in lst: try: print(1/i) except: pass`.
420. What is the `threading.excepthook` in Python?
Handles uncaught exceptions in threads, e.g., `threading.excepthook
421. What is a function in Python?
A reusable block of code that performs a specific task, defined using `def`.
422. What is the syntax to define a function?
`def function_name(parameters): block`.
423. What is the purpose of a function?
To modularize code, improve reusability, and reduce redundancy.
424. What is a function call?
Invoking a function using its name and arguments, e.g., `my_func()`.
425. What are parameters in a function?
Variables defined in the function signature to accept input values.
426. What are arguments in a function?
Actual values passed to a function during a call, e.g., `my_func(5)`.
427. How do you call a function with no parameters?
Use empty parentheses, e.g., `def hello(): print(\"Hi\"); hello()`.
428. What is the `return` statement used for?
Exits a function and sends a value back to the caller.
429. What happens if a function has no `return` statement?
It returns `None` by default.
430. Can a function return multiple values?
Yes, using a tuple, e.g., `return x, y`.
431. Give an example of a function returning multiple values.
`def add_sub(a, b): return a + b, a - b; sum, diff
432. What is a docstring in a function?
A triple-quoted string describing the function’s purpose, e.g., `\"\"\"Adds two numbers.\"\"\"`.
433. How do you access a function’s docstring?
Use `function.__doc__`, e.g., `print(my_func.__doc__)`.
434. What is a default parameter in a function?
A parameter with a default value, used if no argument is provided.
435. Give an example of a function with a default parameter.
`def greet(name
436. What happens if you omit an argument for a default parameter?
The default value is used, e.g., `greet()` uses `\"Guest\"`.
437. What is a required parameter?
A parameter without a default value, requiring an argument.
438. What is the order of parameters in a function definition?
Required parameters, then default parameters, e.g., `def func(a, b
439. What are keyword arguments?
Arguments passed by parameter name, e.g., `my_func(x
440. Give an example of a function call with keyword arguments.
`def add(a, b): return a + b; add(b
441. What is the advantage of keyword arguments?
Improves readability and allows arguments in any order.
442. What are positional arguments?
Arguments passed in the order of parameters, e.g., `add(5, 3)`.
443. Can you mix positional and keyword arguments in a function call?
Yes, but positional arguments must come before keyword arguments.
444. What is `*args` in a function definition?
Collects extra positional arguments into a tuple.
445. Give an example of a function using `*args`.
`def sum_all(*args): return sum(args); sum_all(1, 2, 3)` returns `6`.
446. What is `**kwargs` in a function definition?
Collects extra keyword arguments into a dictionary.
447. Give an example of a function using `**kwargs`.
`def print_info(**kwargs): print(kwargs); print_info(name
448. What is the order of parameters with `*args` and `**kwargs`?
Required, default, `*args`, `**kwargs`, e.g., `def func(a, b
449. Can a function have both `*args` and `**kwargs`?
Yes, `*args` collects positional, `**kwargs` collects keyword arguments.
450. What is a lambda function?
An anonymous function defined using `lambda`, e.g., `lambda x: x * 2`.
451. What is the syntax of a lambda function?
`lambda arguments: expression`.
452. Give an example of a lambda function.
`double
453. What is the limitation of a lambda function?
Restricted to a single expression, no statements or multiple lines.
454. Where are lambda functions commonly used?
In functions like `map()`, `filter()`, or `sorted()`.
455. Give an example of a lambda with `map()`.
`list(map(lambda x: x * 2, [1, 2, 3]))` returns `[2, 4, 6]`.
456. What is a recursive function?
A function that calls itself to solve a problem.
457. Give an example of a recursive function.
`def factorial(n): return 1 if n <
458. What is the base case in recursion?
The condition that stops recursion, e.g., `n <
459. What is the recursive case?
The part where the function calls itself, e.g., `n * factorial(n - 1)`.
460. What happens without a base case in recursion?
Causes a `RecursionError` due to infinite recursion.
461. What is the maximum recursion depth in Python?
Default is 1000, adjustable via `sys.setrecursionlimit()`.
462. What is tail recursion?
Recursion where the recursive call is the last operation.
463. Does Python optimize tail recursion?
No, Python does not perform tail call optimization.
464. What is a higher-order function?
A function that takes or returns other functions, e.g., `map()`.
465. Give an example of a higher-order function.
`def apply(func, x): return func(x); apply(lambda x: x * 2, 5)` returns `10`.
466. What is a closure in Python?
A function that retains access to variables from its enclosing scope.
467. Give an example of a closure.
`def outer(x): def inner(y): return x + y; return inner; f
468. What is a decorator in Python?
A function that modifies another function’s behavior, e.g., `@decorator`.
469. What is the syntax of a decorator?
`@decorator` above a function, or `func
470. Give an example of a decorator.
`def deco(func): def wrapper(): print(\"Start\"); func(); print(\"End\"); return wrapper; @deco def say(): print(\"Hi\")`.
471. What is the purpose of a decorator?
To add functionality, e.g., logging, timing, or access control.
472. Can decorators take arguments?
Yes, using a decorator factory, e.g., `def deco(arg): def wrapper(func): ...`.
473. What is the `@wraps` decorator from `functools`?
Preserves the metadata of the original function in a decorator.
474. Give an example using `@wraps`.
`from functools import wraps; def deco(func): @wraps(func) def wrapper(): return func(); return wrapper`.
475. What is function overloading?
Defining multiple functions with the same name but different parameters.
476. Does Python support function overloading?
No, but you can use default parameters or `*args`/`**kwargs`.
477. What is function overriding?
Redefining a function in a subclass, relevant in OOP.
478. What is a pure function?
A function with no side effects, returning the same output for the same input.
479. Give an example of a pure function.
`def add(a, b): return a + b` (no external state changes).
480. What is a side effect in a function?
A change to external state, e.g., modifying a global variable.
481. What is a first-class function?
A function treated as a variable, e.g., assigned or passed as an argument.
482. Give an example of a first-class function.
`f
483. What is a function signature?
The name and parameters of a function, e.g., `add(a, b)`.
484. What is the `global` keyword in a function?
Declares a variable as global, e.g., `global x; x
485. What is the `nonlocal` keyword in a function?
Refers to a variable in the enclosing scope, e.g., `nonlocal x`.
486. Give an example of `nonlocal`.
`def outer(): x
487. What is a function’s scope?
The region where a variable is accessible, e.g., local or global.
488. What is the LEGB rule in Python?
Lookup order: Local, Enclosing, Global, Built-in.
489. What is a local variable in a function?
A variable defined inside a function, accessible only within it.
490. What is a global variable?
A variable defined outside a function, accessible globally.
491. How do you modify a global variable inside a function?
Use `global`, e.g., `global x; x
492. What is a built-in function?
A function provided by Python, e.g., `print()`, `len()`.
493. What is function composition?
Combining functions where one’s output is another’s input, e.g., `f(g(x))`.
494. Give an example of function composition.
`def square(x): return x * x; def double(x): return x * 2; double(square(3))` returns `18`.
495. What is a generator function?
A function using `yield` to produce values one at a time.
496. Give an example of a generator function.
`def gen(): yield 1; yield 2; for x in gen(): print(x)` prints `1`, `2`.
497. What is the `yield` keyword?
Pauses a function and yields a value, resuming on the next call.
498. What is the advantage of a generator function?
Memory-efficient for large datasets, yielding one item at a time.
499. What is a function annotation?
Optional metadata for parameters and return types, e.g., `def add(a: int) -> int`.
500. Give an example of a function annotation.
`def greet(name: str) -> str: return f\"Hello, {name}\"`.
501. What is the purpose of function annotations?
To improve code readability and support type checking.
502. How do you access function annotations?
Use `__annotations__`, e.g., `add.__annotations__`.
503. What is the `callable()` function used for?
Checks if an object is callable, e.g., `callable(len)` returns `True`.
504. What is a method in Python?
A function defined inside a class, e.g., `def my_method(self)`.
505. What is the difference between a function and a method?
A method is bound to a class or object; a function is standalone.
506. What is the `sorted()` function with a key parameter?
Sorts using a function, e.g., `sorted(lst, key
507. Give an example of `sorted()` with a key function.
`sorted([\"Apple\", \"banana\"], key
508. What is the `filter()` function?
Selects items based on a function, e.g., `filter(lambda x: x > 0, lst)`.
509. Give an example of `filter()` with a function.
`list(filter(lambda x: x % 2
510. What is the `map()` function?
Applies a function to each item, e.g., `map(lambda x: x * 2, lst)`.
511. Give an example of `map()` with a function.
`list(map(lambda x: x ** 2, [1, 2, 3]))` returns `[1, 4, 9]`.
512. What is a partial function?
A function with some arguments pre-filled, from `functools.partial`.
513. Give an example of a partial function.
`from functools import partial; add5
514. What is a memoization decorator?
Caches function results to avoid recomputation.
515. Give an example of memoization with `functools.lru_cache`.
`from functools import lru_cache; @lru_cache def fib(n): return n if n <
516. What is the `functools` module?
Provides tools for working with functions, e.g., `partial`, `lru_cache`.
517. What is a function
Share this protal to share friends and complete unlimited tests here. You can also make friends on our protal also start mutual competition tests with your firends easily.