Search code examples
if-statementlanguage-agnosticstructure

How can I structure this code to avoid repetition?


I have two conditions, a and b. One block of code should execute if a is true, then another if either a or b is true. Is there a better way to structure the code than the following - can I avoid the repeated test of a?

if a or b:
    if a:
        <block 1>
    <block 2>

Solution

  • It is not possible without the repeated test. To verify this, just write down the truth table.

    However you could avoid the nesting of your if statements:

    if a:
        <block 1>
    if a or b:
        <block 2>
    

    This could make the code more readable.

    I assume here that a is a boolean value and not a placeholder for a more complex expression that might be expensive to evaluate. In the latter case you would of course evaluate the expression only once and assign the result to a boolean value.