PCEP-30-02 practice question 1 of 35

The following list is given:

Full set: 548 questions

Domain Control Flow – Conditional Blocks and Loops

Answer options
A: net_profit = [-10.5, 4.5, 30.8, -3.5, 14.0]
B: Which of the following code is correct for combining the list comprehension and the conditional statement with the else clause? (select 2)
C: [value if value >= 0 else abs(value) for value in net_profit] Correct answer
D: [value for value in net_profit else 0]
E: [value for value in net_profit if value >= 0 else 0]
F: [value if value >= 0 else 0 for value in net_profit] Correct answer
Correct Answer:
C. [value if value >= 0 else abs(value) for value in net_profit]; F. [value if value >= 0 else 0 for value in net_profit]
Explanation

In Python, a list comprehension can incorporate a conditional statement with an else clause by using the conditional expression (ternary operator) syntax: valueiftrue if condition else valueiffalse. This entire conditional expression must be placed at the beginning of the list comprehension, before the for loop. It defines the value of each new element in the resulting list. Both options C and F correctly follow this syntax, applying a different else value but adhering to the same valid structure.

Why Incorrect

D. [value for value in netprofit else 0] This is a syntax error. An else clause cannot be directly attached to the for...in part of a list comprehension.
E. [value for value in netprofit if value >= 0 else 0] This is a syntax error. The filtering if clause, which comes at the end of the comprehension, does not support an else counterpart.

References

1. Python Software Foundation. (2024). The Python Tutorial, Release 3.12.3. Section 5.1.3. List Comprehensions.

This official tutorial explicitly distinguishes between a filtering if at the end of the comprehension and a conditional expression at the beginning. It states, "The expression can be anything, including another list comprehension," and provides examples of the ... if ... else ... syntax being used as the expression before the for clause.

2. Python Software Foundation. (2024). The Python Language Reference, Release 3.12.3. Section 6.2.10. Displays for lists, sets and dictionaries.

The formal grammar for a list comprehension is defined as [expression compfor]. The expression part can be a conditionalexpression, which is defined as ortest ["if" ortest "else" expression]. This confirms that the if-else structure is part of the initial expression. The filtering if (compif) is a separate part of the grammar that does not include an else.

3. Lutz, M. (2013). Learning Python (5th ed.). O'Reilly Media. Chapter 14: Comprehensions and Generations, pp. 436-438.

This authoritative text explains the syntax, stating: "To use if and else, we have to move the conditional to the expression at the start of the comprehension... This is a ternary expression, not a statement." This directly supports the structure used in answers C and F.

Scroll to Top