Lesson 1 of 3
Make programs take decisions with if, elif and else, understand indented blocks, and combine conditions.
About 25 minutes
if, elif and else statementsand, or and notUntil now, every program has run every line from top to bottom. Real programs need to react to data: classify a material as a conductor or an insulator, flag a measurement outside the expected range, or warn when an input makes no sense. Control flow statements decide which lines run, and how many times. This module covers the two main kinds: conditional statements (this lesson) and loops (the next two).
An if statement runs a block of code only when a condition is True. The condition is any expression that gives a Boolean, usually a comparison such as temperature > 1000.
temperature = 1200 # °Cmelting_point = 1085 # copperif temperature > melting_point: print("Copper is molten at this temperature.") print("Use a ceramic crucible.")print("Check complete.")Notice the structure. The if line ends with a colon. The lines that belong to the if are indented by four spaces; together they form a block. When the condition is False, Python skips the whole block and continues with the first line that isn't indented. Change temperature to 900 and run the example to see the difference.
Indentation matters in Python
Tab). A missing or inconsistent indent causes an IndentationError, or a block that silently does the wrong thing.else gives a block to run when the if condition is False. elif (short for else if) adds more conditions to check in order. Python runs the block for the first condition that is True and skips the rest; if none are true, it runs the else block (if there is one).
ph = 8.3if ph < 7: print("acidic")elif ph == 7: print("neutral")else: print("basic")Because only the first true branch runs, the order of elif conditions matters. Put the most specific or most restrictive tests first.
A material's band gap determines how it conducts electricity: metals have no gap, semiconductors a small one, and insulators a large one.
material = "Gallium arsenide"band_gap = 1.42 # eVif band_gap == 0: category = "conductor"elif band_gap < 3: category = "semiconductor"else: category = "insulator"print(f"{material} is a {category}.")Use and, or and not to build more complex conditions, as you saw in the Operators lesson. Python also lets you chain comparisons the way you would write them in maths: 0 < x < 10 means x is between 0 and 10.
density = 4.51 # g/cm³, titaniummelting_point = 1668 # °Cif density < 5 and melting_point > 1500: print("Light and heat resistant: a candidate for aerospace parts.")if not (2.0 <= density <= 20.0): print("Check the density: it is outside the usual range for metals.")The in operator from the Data Structures module makes natural conditions. An empty list, string, dictionary or set also counts as False in a condition, and a non-empty one as True, so if measurements: means if there are any measurements.
alloy = ["Fe", "Cr", "Ni", "Mo"]measurements = []if "Mo" in alloy: print("Contains molybdenum: improved corrosion resistance.")if measurements: print("Mean:", sum(measurements) / len(measurements))else: print("No measurements recorded yet.")An if statement can sit inside another one. The inner block is indented one more level. Nesting is useful when the second question only makes sense after the first has been answered, but deep nesting is hard to read, so combine conditions with and where you can.
is_metal = Truedensity = 19.3 # g/cm³if is_metal: if density > 10: print("Heavy metal") else: print("Light or medium metal")else: print("Not a metal")Conditions are how a program protects itself from bad data. Before calculating, check that the values make physical sense and report a clear message if they don't.
mass = float(input("Mass (g): "))volume = float(input("Volume (cm³): "))if volume <= 0: print("Volume must be greater than zero.")elif mass < 0: print("Mass can't be negative.")else: print(f"Density: {mass / volume:.2f} g/cm³")With a volume of 0 the program prints a message instead of crashing with a ZeroDivisionError. Try it with other values in the Program input box.
Choose an answer and press Check answer. You can retry as often as you like.