2. Which of the following is the correct Python syntax to define a function named generate_code?
easy
A. generate_code def():
B. function generate_code()
C. def generate_code[]:
D. def generate_code():
Solution
Step 1: Recall Python function syntax
Python functions start with def, followed by name and parentheses, then colon.
Step 2: Check each option
def generate_code(): matches correct syntax; A, B and D have syntax errors (A wrong order, B JavaScript style, D brackets).
Final Answer:
def generate_code(): -> Option D
Quick Check:
Python function = def name(): [OK]
Hint: Python functions start with def and parentheses [OK]
Common Mistakes:
Using JavaScript function keyword in Python
Missing parentheses after function name
Using brackets instead of parentheses
3. What will be the output of this Python code generated by AI?
def add_numbers(a, b):
return a + b
result = add_numbers(3, 4)
print(result)
medium
A. 7
B. 34
C. TypeError
D. None
Solution
Step 1: Understand function behavior
The function adds two numbers and returns the sum.
Step 2: Calculate add_numbers(3, 4)
3 + 4 equals 7, so result is 7 and printed.
Final Answer:
7 -> Option A
Quick Check:
3 + 4 = 7 [OK]
Hint: Adding numbers returns their sum [OK]
Common Mistakes:
Thinking + concatenates numbers as strings
Expecting error from simple addition
Confusing return value with print output
4. Identify the error in this AI-generated Python code:
def multiply(x, y):
return x * y
print(multiply(2, 3))
medium
A. Missing indentation for return statement
B. Wrong function name
C. Missing parentheses in print
D. Using * instead of + operator
Solution
Step 1: Check Python indentation rules
Python requires the return line inside function to be indented.
Step 2: Identify error in code
Return is not indented, causing IndentationError; other options are incorrect.
Final Answer:
Missing indentation for return statement -> Option A
Quick Check:
Python needs indented blocks [OK]
Hint: Indent inside functions in Python [OK]
Common Mistakes:
Ignoring indentation errors
Thinking print needs no parentheses in Python 3
Confusing operators without context
5. You want to generate Python code that creates a dictionary from a list of keys ["a", "b", "c"] with values as their lengths. Which code snippet correctly uses dictionary comprehension?
It uses curly braces with key:value pairs inside a for loop.
Step 2: Check each option
result = {k: len(k) for k in ["a", "b", "c"]} correctly creates dict with keys and their lengths; B uses list brackets wrongly; C swaps key and value; D uses comma instead of colon.
Final Answer:
result = {k: len(k) for k in ["a", "b", "c"]} -> Option C
Quick Check:
Dict comprehension = {key: value for item} [OK]
Hint: Dict comprehension uses {key: value for item} [OK]