Python Core Syntax 5 — Questions and Answers
Question 1: What happens when you use `*args` in a function definition?
- It requires exactly one argument
- It collects extra positional arguments into a tuple (Correct answer)
- It collects extra keyword arguments into a dict
- It marks arguments as optional
Correct answer: It collects extra positional arguments into a tuple
`*args` collects all extra positional arguments passed to the function into a tuple.
Question 2: What is the output of `print('ab' * 3)`?
- 'ababab' (Correct answer)
- 6
- 'ab3'
- TypeError
Correct answer: 'ababab'
Multiplying a string by an integer repeats it that many times, so `'ab' * 3` produces `'ababab'`.
Question 3: Which statement about Python indentation is correct?
- Indentation is optional but recommended
- Indentation must use exactly 4 spaces
- Indentation defines code blocks and is syntactically required (Correct answer)
- Indentation is only required inside classes
Correct answer: Indentation defines code blocks and is syntactically required
Python uses indentation to delimit code blocks; incorrect or inconsistent indentation causes an `IndentationError`.
Question 4: What does the `\t` escape sequence represent in a Python string?
- A backslash followed by t
- A tab character (Correct answer)
- A newline
- The end of a string
Correct answer: A tab character
`\t` is the escape sequence for a horizontal tab character in Python strings.
Question 5: Which of the following will raise a `TypeError` in Python?
- '3' * 3
- '3' + '3'
- '3' + 3 (Correct answer)
- int('3') + 3
Correct answer: '3' + 3
You cannot concatenate a string and an integer directly; `'3' + 3` raises a `TypeError` because the operands are of incompatible types.
Question 6: What is the purpose of the `__name__ == '__main__'` guard in a Python script?
- It renames the module
- It runs code only when the script is executed directly, not imported (Correct answer)
- It restricts access to class members
- It marks the entry point for compiled binaries
Correct answer: It runs code only when the script is executed directly, not imported
When a module is imported, `__name__` is set to the module name; when run directly, it is `'__main__'`, so this guard prevents code from running on import.
Question 7: What is the result of `sorted([3, 1, 2], reverse=True)`?
- [1, 2, 3]
- [3, 2, 1] (Correct answer)
- [2, 1, 3]
- The original list sorted in-place
Correct answer: [3, 2, 1]
`sorted()` returns a new sorted list; with `reverse=True` it sorts in descending order, yielding `[3, 2, 1]`.
What happens when you use `*args` in a function definition?