PCEP Control Flow and Functions 2 — Questions and Answers
Question 1: What is the output of the following code? for i in range(3): if i == 1: continue print(i)
- 0 1 2
- 0 2 (Correct answer)
- 1 2
- 0 1
Correct answer: 0 2
The `continue` statement skips the rest of the loop body when `i == 1`, so 1 is never printed.
Question 2: Which of the following correctly defines a function that returns the square of a number?
- def square(n): return n * n (Correct answer)
- function square(n): return n ** 2
- def square(n) => n * n
- def square: return n * n
Correct answer: def square(n): return n * n
Python functions are defined with `def`, require a colon, and can use `return` to send back a value.
Question 3: What value does a Python function return if it has no `return` statement?
- 0
- False
- None (Correct answer)
- ''
Correct answer: None
A function without a `return` statement implicitly returns `None`.
Question 4: What is the output of the following? x = 10 if x > 5: print('A') elif x > 8: print('B') else: print('C')
- A (Correct answer)
- B
- A B
- C
Correct answer: A
Once the first `if` condition is True, the `elif` and `else` branches are skipped entirely.
Question 5: How many times does the following loop execute? i = 0 while i < 5: i += 2
- 2
- 3 (Correct answer)
- 5
- 4
Correct answer: 3
i takes values 0, 2, 4 before i becomes 6 which fails the condition, so the loop runs 3 times.
Question 6: What does the `pass` statement do inside a function body?
- Exits the function immediately
- Does nothing; acts as a placeholder (Correct answer)
- Skips to the next iteration
- Raises a SyntaxError
Correct answer: Does nothing; acts as a placeholder
`pass` is a no-op statement used as a placeholder where Python syntax requires a statement but no action is needed.
Question 7: What is the result of calling `range(1, 10, 3)` as a list?
- [1, 4, 7] (Correct answer)
- [1, 3, 6, 9]
- [1, 4, 7, 10]
- [3, 6, 9]
Correct answer: [1, 4, 7]
`range(1, 10, 3)` starts at 1, steps by 3, and stops before 10, yielding 1, 4, 7.
What is the output of the following code?
for i in range(3):
if i == 1:
continue
print(i)