PCEP Using `sep=` and `end=` in `print()` 2 — Questions and Answers
Question 1: What is the output of `print('a', 'b', 'c', sep='-')`?
- a-b-c (Correct answer)
- a b c
- -a-b-c-
- abc
Correct answer: a-b-c
The `sep='-'` argument places a hyphen between each argument passed to print.
Question 2: What does `print('Hello', end='')` do differently than `print('Hello')`?
- Suppresses the trailing newline (Correct answer)
- Adds an extra newline
- Prints nothing
- Raises a TypeError
Correct answer: Suppresses the trailing newline
By default `end='\n'`, so passing `end=''` removes the newline that would follow the output.
Question 3: What is printed by: ``` print(1, 2, 3, sep=', ', end='!') ```
- 1, 2, 3! (Correct answer)
- 1 2 3!
- 1,2,3!
- 1, 2, 3 !
Correct answer: 1, 2, 3!
`sep=', '` joins the numbers with comma-space, and `end='!'` replaces the newline with `!`.
Question 4: Which call produces the output `Hello World` (no newline at the end)?
- print('Hello World', end='')
- print('Hello World', sep='')
- print('Hello', 'World', end='')
- Both A and C (Correct answer)
Correct answer: Both A and C
Both `print('Hello World', end='')` and `print('Hello', 'World', end='')` suppress the newline (the latter also uses default `sep=' '`).
Question 5: What is the output of: ``` for i in range(3): print(i, end=' ') ```
- 0 1 2 (Correct answer)
- 0\n1\n2\n
- 012
- 0 1 2
Correct answer: 0 1 2
Each iteration prints the number followed by a space instead of a newline, resulting in `0 1 2 ` with a trailing space.
Question 6: What is the output of `print('x', 'y', sep='', end='\n')`?
- xy (Correct answer)
- x y
- x\ny
- xy\n
Correct answer: xy
`sep=''` places nothing between 'x' and 'y', producing 'xy', and `end='\n'` is the default so a newline follows.
Question 7: What happens when you call `print(sep='|')` with no positional arguments?
- Prints an empty line (Correct answer)
- Prints a single |
- Raises a TypeError
- Prints nothing at all
Correct answer: Prints an empty line
With no positional arguments, there are no items to separate, so only the `end` value (default newline) is printed, producing a blank line.
What is the output of `print('a', 'b', 'c', sep='-')`?