Whether or not a block of code is executed in Python can be controlled using if statements. Coupled with elif and else, you can write code that is executed depending on whether a logical expression is true. For example, water boils into steam if the temperature is greater than the boiling point.

The Python documentation has a guide on if Statements.

Syntax

Conditional statements in Python follow this general structure:

if condition1:
    statements1
elif condition2:
    statements2
else:
    statements3

Each condition is evaluated in order. If condition1 is true, statements1 are executed and the rest are skipped. If condition1 is false but condition2 is true, statements2 are executed. If none of the conditions are true, the else block is executed. The elif and else blocks are both optional, and there can be any number of elif blocks.

Unlike MATLAB or C++, Python does not use an end keyword or curly braces to mark where a block starts and stops. Instead, every line belonging to the same block must be indented by the same amount. The block ends as soon as a line returns to the previous indentation level. The colon : at the end of the if, elif, and else lines is required, and forgetting it is a common source of syntax errors.

Logical Expressions

Conditions are typically logical expressions involving comparison operators (<, >, ==, !=, <=, >=) or logical operators (and, or, not). A condition is true whenever it evaluates to Python’s True value.

temperature = 105  # deg C

print(temperature > 100)
print(temperature == 100)
print(temperature < 100 or temperature == 105)

True
False
True

Example: Material Selection

Question

An engineer is selecting a material for a structural component. The material must have a yield strength above 250 MPa and a density below 8000 kg/m3. Write a Python script to check if a material with yield strength 300 MPa and density 7800 kg/m3 meets these criteria.

Solution

To evaluate the fitness of the material, we use an if statement to check the criteria.

yield_strength = 300  # MPa
density = 7800  # kg/m^3

if yield_strength > 250 and density < 8000:
    print("Material is acceptable.")
elif yield_strength <= 250:
    print("Yield strength is too low.")
else:
    print("Density is too high.")

Material is acceptable.

Compound Conditions

Multiple conditions can be combined using logical operators.

  • and is true only if both sides are true
  • or is true if either side is true
  • not reverses a condition, so not True is False

Both and and or short-circuit, stopping evaluation as soon as the overall result is known. For example, in condition1 and condition2, if condition1 is false, Python does not evaluate condition2, since the result is already determined.

Nested If Statements

You can nest if statements inside other if blocks, to handle more complex logic. Each nested if needs its own consistent indentation, one level deeper than the if it’s nested inside.

x = 5

if x > 0:
    if x < 10:
        print("x is between 0 and 10")
    else:
        print("x is greater than or equal to 10")

x is between 0 and 10

A Few Tips

Writing else if as two words, rather than the single keyword elif, is a common syntax error carried over from other languages. Python does not recognize else if at all. Similarly, using a single = instead of == inside a condition is a frequent mistake. = assigns a value, while == compares two values, and Python will raise a SyntaxError if you try to assign inside an if condition. Finally, if a nested if statement starts to grow several levels deep, it is often clearer to pull that logic out into its own function rather than keep nesting.

Reading Questions

  1. What is the purpose of an if statement in Python?
  2. How does Python know where a block of code inside an if statement starts and ends, since it doesn’t use an end keyword?
  3. What happens if multiple conditions in an if-elif-else block are all true?
  4. What is the difference between = and == in Python?
  5. How would you write a conditional statement that checks if the value x is between 5 and 10, inclusive?

Practice Problem: Runway Length Check

Regulations require a safety margin between the runway length available and the distance an aircraft actually needs to take off. How much margin is left changes with every runway, so it has to be checked before every takeoff.

Your Task

Write a script named runway_check.py that starts from the given values:

runway_length_ft = 5200
required_distance_ft = 4300

Compute:

  1. margin_ft - the difference between the runway length and the required takeoff distance
  2. status - a string classifying margin_ft using an if-elif-else statement:
    • "Go" if margin_ft is 1000 or more
    • "Caution" if margin_ft is at least 500 but less than 1000
    • "No-Go" if margin_ft is less than 500

Your variable names for the two answers above must match exactly (margin_ft, status) so that the checker below can find them.

Checking Your Work

Download check_runway_check.py and save it in the same folder as your runway_check.py script. Open a terminal in that folder and run:

python check_runway_check.py

The checker runs your script and reports whether each of the two values is correct. This is practice, not a graded assignment. If something doesn’t pass, use the feedback to find and fix the issue, then run the checker again.