Lesson
Conditions
Choose an action using comparisons and Boolean expressions.
Choosing what to do
A conditional runs instructions only when a condition is true. Comparisons such as <, >, <=, >=, ==, and != produce Boolean values: True or False. Use == to compare two values. A single = assigns a value and does not perform a comparison.
An if block handles the first condition. An elif block checks another condition when the earlier ones were false. An else block handles every remaining case. In one if/elif/else chain, at most one branch runs.
A complete example
Suppose an item costs 12 units and the input is the available budget.
budget = int(input())
if budget > 12:
print("CHANGE")
elif budget == 12:
print("EXACT")
else:
print("NOT_ENOUGH")For input 15, the output is CHANGE. For 12, it is EXACT. For 8, it is NOT_ENOUGH. The three cases cover all integers without overlap.
The colon and indentation tell Python where each branch begins and ends. Instructions after the chain, with no branch indentation, run regardless of which branch was chosen.
Combining conditions
Use and when both conditions must hold, or when either condition is sufficient, and not to reverse a Boolean value. Parentheses make a combined rule easier to read. For example, 1 <= month <= 12 checks that month lies inside an inclusive range.
The remainder operator helps express divisibility. A value n is divisible by 4 exactly when n % 4 == 0. A year is a leap year when it is divisible by 400, or when it is divisible by 4 but not by 100. Write the rule in words before turning it into a Boolean expression.
Check the boundaries
Most conditional errors happen near equality. For the budget example, test 11, 12, and 13. For a sign classifier, test a negative integer, zero, and a positive integer. For leap years, include 1900, 2000, 2023, and 2024. The century cases distinguish the full rule from the tempting but incorrect divisibility-by-four shortcut.
Problem 1414 asks for the larger value of two integers. Equal values are valid and should still produce one answer. The next exercises classify a sign and decide whether a year is leap. Print the exact tokens requested by each statement.
Two separate if blocks are not the same as one if/else chain. If both independent conditions are true, both bodies run. Choose the structure that matches how many results the problem requires.