Lesson · Python for Beginners
Conditions and comparisons
A condition lets a program choose a path based on the values it has at runtime.
What you will learn
- Write an if/else block
- Compare values
- Combine conditions with and/or
A branch begins with if
Python evaluates the expression after if and enters its indented block when the result is true. Indentation is part of Python syntax: statements in the block must line up consistently. A colon ends the condition line and introduces the block that belongs to it.
Choose among outcomes
Use elif for another condition that should be checked only when earlier conditions were false, and use else for the remaining case. Python tests these branches in order and runs at most one of them. Order specific boundaries carefully so that values at an edge are assigned to the intended case.
Compare and combine
Equality uses two equals signs, while a single equals sign assigns a value. Operators such as <, <=, >, and >= compare ordered values. The words and and or combine boolean expressions; parentheses can make a longer condition easier to read. Avoid comparing text and numbers as if they had the same meaning.
Explain the rule
A useful condition mirrors a clear rule in ordinary language. In the example, a score of 40 qualifies because the comparison includes the boundary. Testing one value below, exactly at, and one above a boundary is a simple way to catch mistakes in a branching rule.
Check edges, not just typical values
When a rule uses a boundary, write down examples on both sides and at the exact boundary. A pass mark of 40, for instance, should be tested with 39, 40, and 41. This catches accidental use of > where >= was intended. Also consider whether the input can be missing or the wrong type before comparing it.
score = 40
if score >= 40:
print('Pass')
else:
print('Try again')
Expected output
Pass
Practice exercise
Print 'adult' for an age of 18 or more, and 'under 18' otherwise.
Show a hint
Use >= and put each message in its own branch.
Show one possible solution
age = 17; if age >= 18: print('adult'); else: print('under 18') selects the second message.
Quick check
Two equals signs compare values; one equals sign assigns a value to a name.