Conditions: if, else, else if

Running one block or another depending on a condition: if, if-else, else-if chains, nested tests and multi-way selection, with the logic errors that come up most.

  • 28 cards
  • 7 topics
  • Free

The outline, topic by topic

Each topic is weighted the way the exam weighs it.

  1. Concepts
  2. Questions
  3. Sort and link
  4. Scenarios
  5. Understand
  6. Line by line
  7. Tap what fits

A few cards from the deck

  • Conditional statement: what is it?

    Show the answer

    A statement that runs a block only if a test is true and, optionally, another block otherwise.

    In Python: if, then else for the other case. At each pass, only one of the two blocks runs.

  • What does this program print?

    ```python
    t = 25
    if t > 10:
    print("mild")
    elif t > 20:
    print("hot")
    else:
    print("cold")
    `

    • mild
    • hot
    • mild then hot
    • cold
    Show the answer

    mild

    25 satisfies t > 10: the first branch is taken and the chain stops there. The branch elif t > 20 is unreachable; test the highest threshold first.

  • In Python, … marks out the block of an if; in C and Java, … do.

    Show the answer

    In Python, indentation marks out the block of an if; in C and Java, braces do.

    A line that returns to the level of the if no longer belongs to its block: it runs in every case.