Concepts / Introduction to Conditional Statements

Introduction to Conditional Statements

A conditional statement lets a program choose a path based on an input or situation.

  • Programming
Interactive lab

Try it: if / elif / else

How Python tests if / elif conditions from the top, runs only the first true branch, and how and / or stop evaluating as soon as the answer is known (short-circuiting).

How it works

  1. Python evaluates the if condition first.
  2. If it is False, it tries each elif in order; the first True one runs and the rest are skipped without being tested.
  3. If none is True, the else branch runs.
  4. and stops at the first False, or stops at the first True — the right side may never be evaluated.

Default run (5 steps): score = 84; A = 90, B = 80, C = 70. Python tests the conditions from the top. … print(grade) shows B.

Educational simulation

Loading the simulation…

Interactive lab

Try it: Validate Input Before Processing

How a program reads untrusted text with input() and checks it in order (empty line, conversion with try / except, allowed range) before it computes anything, re-prompting after each rejected line. Switch a check off, or run the range check before converting, to see which bad input slips through or crashes the program.

How it works

  1. input() always returns a str, even when the user types digits.
  2. Check 1: an empty line (line.strip() == "") is rejected first; the loop prints a message and continue goes back to input().
  3. Check 2: float(line) / int(line) inside try; a non-numeric line raises ValueError and the except block recovers instead of crashing.
  4. Check 3: a converted number outside the allowed range is still invalid and is rejected (the range check must come after the conversion: comparing the str itself raises TypeError).
  5. The first line that passes every check breaks out of the loop and is processed: overtime pay (1.5x only for hours above 40), ordered grade bands, or a ticket total.

Default run (21 steps): The overtime pay program is ready. 4 input lines are queued for input(). … print shows Pay: 475.0.

Simplified: Three fixed programs (you change the input lines and switch the checks, never the code); the lab implements their Python semantics itself and nothing is executed as Python. Every combination was run in CPython 3.12 with the same inputs and the lab reproduces its output and error messages. input() returns the lines you type, one per call (the prompt is not printed), and raises EOFError when they run out. Input is printable ASCII only.

Educational simulation

Loading the simulation…

When the Path Changes

A conditional statement lets a program choose a path based on an input or situation. The important idea is not just writing an if statement; it is designing the program so that each possible input reaches the correct outcome. Overtime pay, invalid user input, and grade assignment all require the program to make a decision and then execute only the appropriate branch.

Overtime at the Threshold

The overtime problem has a clear decision point at 40 hours. When the number of hours is 40 or less, the regular-pay path is used. When the number is greater than 40, only the hours above 40 receive the 1.5x multiplier. The first 40 hours remain on the regular-pay path.

Hours workedMore than 40?Regular payAll hours at regular rateOvertime payExtra hours at 1.5x ratePay components40 regular hours plusovertime hoursevaluatenoyesmultiply extra hours
How does the calculation path change when hours worked are greater than 40, and how is the 1.5x multiplier applied only to the overtime hours?
Worked example

Tracing 45 hours

Assume a worker earns a regular rate of 20 per hour and works 45 hours. Apply the overtime rule that hours above 40 receive a 1.5x multiplier.

  1. 1
    Check the threshold

    45 is greater than 40, so the overtime branch is selected.

  2. 2
    Separate the hours

    The regular portion is 40 hours. The overtime portion is 45 minus 40, which is 5 hours.

  3. 3
    Apply the multiplier

    The 5 overtime hours use the regular rate multiplied by 1.5. The first 40 hours use the regular rate.

Result

The calculation is 40 times 20 plus 5 times 20 times 1.5, giving 950.

Code walkthrough
hours = 45
rate = 20

if hours > 40:
    regular_hours = 40
    overtime_hours = hours - 40
    pay = regular_hours * rate + overtime_hours * rate * 1.5
else:
    pay = hours * rate

print(pay)
  1. 1
    hours is 45, so hours > 40 is true.
  2. 2
    regular_hours becomes 40.
  3. 3
    overtime_hours becomes 5.
  4. 4
    The calculation combines regular pay with overtime pay.
  5. 5
    print displays 950.0.
  • The condition tests whether hours exceed the threshold.
  • The overtime branch separates regular hours from overtime hours.
  • Only overtime_hours is multiplied by 1.5.
  • The else branch handles hours of 40 or less.
Output
950.0

Protecting Input Conversion

User input may not be numeric when the program expects a number. A try block can contain the conversion and processing steps, while an except block provides a graceful response when the conversion cannot handle the supplied input. This keeps the program from simply failing at the point where the unexpected input appears.

User inputtryConvert inputNumeric valueContinue processingInvalid inputexceptRespond gracefullyreceivedconversion succeedsconversion failshandle input
What happens to program control when user input cannot be converted to a number, and how does the except block handle the error?
python

Validating Before Processing

Range validation adds another decision after input has been converted. The program first determines whether the value is within the accepted range. Valid input continues to the conditional processing, while invalid input receives an invalid-input response. This prevents values outside the intended range from being treated as normal cases.

ScoreValid range0.0 through 1.0Grade checksCompare thresholdsGradeCorrect outcomeInvalid inputcheckvalidout of rangematch threshold
How does input move from validation to either accepted processing or an invalid-input response?

For a score represented between 0.0 and 1.0, values such as 1.5 and -0.1 should be treated as out of range. Boundary values deserve special attention because they test whether comparisons include or exclude the exact threshold.

Chaining Grade Decisions

A multi-branch conditional checks several possible ranges in sequence. The illustrative grading logic below first rejects scores outside 0.0 through 1.0. It then checks the highest threshold first and continues through lower thresholds until one matches. The final else branch handles the remaining valid scores.

Score0.0 to 1.0Range validationAAt least 0.9BAt least 0.8CAt least 0.7DAt least 0.6FRemaining valid scoresInvalidOutside rangecheckvalidinvalidbelow 0.9at least 0.9below 0.8at least 0.8below 0.7at least 0.7below 0.6at least 0.6
How does a numeric score move through multiple range checks to determine the correct grade?
python
Output
For a score of 0.85, the output is B. For a score of 1.5, the output is Invalid score. For text that cannot be converted to a number, the except branch prints Please enter a numeric score.
Worked example

Tracing a score of 0.85

Use the illustrative grade thresholds to determine the result for a score of 0.85.

  1. 1
    Validate the range

    0.85 is between 0.0 and 1.0, so processing continues.

  2. 2
    Check the first threshold

    0.85 is below 0.9, so the A branch is skipped.

  3. 3
    Check the next threshold

    0.85 is at least 0.8, so the B branch is selected.

  4. 4
    Stop at the matching branch

    The later branches are not needed after the matching branch is reached.

Result

The illustrative grade is B.

Testing Every Boundary

Conditional logic should be tested with normal inputs, boundary values, edge cases, and intentionally bad input. For overtime, test fewer than 40 hours, exactly 40 hours, and more than 40 hours. For exception handling, test numeric input, text, negative values, and very large values. For grading, test the threshold values 0.9, 0.8, 0.7, and 0.6, values between them, and out-of-range values such as 1.5 and -0.1.

  • Common mistake

    Applying the 1.5x multiplier to all hours

    What it looks like

    Multiplying the entire hours value by the overtime rate when the hours exceed 40

    Why it fails

    The multiplier applies only to hours above 40, not to the first 40 hours.

    Do this instead

    Separate regular hours from overtime hours before applying the multiplier.

  • Common mistake

    Testing only ordinary values

    What it looks like

    Testing overtime with 45 hours but never testing exactly 40

    Why it fails

    A conditional can appear correct while mishandling the threshold itself.

    Do this instead

    Test values below the threshold, exactly at the threshold, and above it.

  • Common mistake

    Treating non-numeric input as a valid number

    What it looks like

    Attempting numeric processing without a try and except structure

    Why it fails

    Text supplied where a number is expected may prevent the intended processing path.

    Do this instead

    Place the conversion in try and provide a graceful response in except.

  • Common mistake

    Skipping range validation

    What it looks like

    Assigning a grade to 1.5 without first checking whether the score is valid

    Why it fails

    An input can be numeric but still outside the accepted range.

    Do this instead

    Validate the range before running the grade thresholds.

  • Common mistake

    Debugging the result without checking the branch

    What it looks like

    Looking only at the final output after an unexpected grade or pay amount

    Why it fails

    The error may be that a different conditional path was selected.

    Do this instead

    Print the input and log which branch was taken immediately after each condition.

Practice the Paths

MEDIUM

Write a program that asks for hours worked and a regular hourly rate. If the hours are greater than 40, calculate regular pay for the first 40 hours and apply the 1.5x multiplier only to the remaining hours. Otherwise, calculate pay using the regular rate. Test the program with fewer than 40 hours, exactly 40 hours, more than 40 hours, text input, a negative number, and a very large number.

Hints
  • Start by checking whether the hours value is greater than 40.
  • When the overtime branch is selected, calculate overtime hours by subtracting 40 from the total hours.
  • Use try and except around numeric conversion so non-numeric input receives a graceful response.
  • Record which branch executes during testing.
MEDIUM

Write a second program that accepts a score from 0.0 through 1.0. Reject values outside that range, handle non-numeric input with try and except, and use the thresholds 0.9, 0.8, 0.7, and 0.6 to assign the illustrative grades A, B, C, D, or F. Test every threshold exactly, values between thresholds, 1.5, -0.1, and text.

Hints
  • Perform range validation before the grade comparisons.
  • Check the highest threshold first.
  • Use an else branch for the remaining valid scores.
  • Trace the score and the branch selected when a result is unexpected.

Conditional Logic Checklist

  1. 1
    A conditional statement routes an input to a particular processing path.
  2. 2
    For overtime pay, the 40-hour threshold separates regular processing from overtime processing, and only hours above 40 receive the 1.5x multiplier.
  3. 3
    A try and except structure lets a program respond gracefully when input cannot be converted to a number.
  4. 4
    Range validation should happen before further conditional processing when only a specific input range is valid.
  5. 5
    Boundary values, edge cases, and intentionally bad input reveal whether every branch works as intended.

Key Takeaways

  • Conditional logic determines which block of code executes for a particular input.
  • Overtime calculations diverge at 40 hours, with the 1.5x multiplier applied only to hours above that threshold.
  • Try and except blocks provide a graceful path for non-numeric input.
  • Range validation and ordered multi-branch checks route valid values to the correct outcome.
  • Testing thresholds, edge cases, and bad input is essential for reliable conditional programs.

Related concepts

More concepts starting with I