~/learn/Python · Fundamentals
Making decisions with if and else
Choose what happens next and learn why colons and indentation matter.
why this matters
Real programs need different outcomes for different inputs. Correct boundaries and indentation keep those decisions reliable.
An if statement runs a group of instructions only when its condition is true. The colon ends the condition line. The indented lines below it belong to that group, called a block. Use four spaces consistently; a line moved back to the left is outside the block.
Try it: Set score to 40. Which line still prints?
Follow the flow
score >= 60? True → print Passed and Keep practising False → skip those two lines Both paths → print Score checked
else supplies the alternative when the condition is false. elif means else if: test another condition when earlier ones failed. In one if / elif / else chain, only the first matching branch runs. Put stricter thresholds first.
Try it: Try scores 80, 60 and 59 separately. Predict the label at each boundary.
Two separate if statements are different from a chain: both can run if both conditions are true. Use a chain for mutually exclusive results, such as one score label. Use separate if statements for independent checks, such as showing two warnings.
Try it: Change is_raining to False while keeping temperature at 30.
Three common mistakes
Do not forget the colon. Do not mix tabs and spaces. Use == for an equality condition, not =. Indentation is part of Python's meaning, not just decoration.
key takeaways
- End a condition line with a colon and indent its block.
- An if / elif / else chain runs only its first matching branch.
- Separate if statements can both run.
- Test values exactly at your thresholds.
check your understanding
score = 60 if score >= 80: print("Excellent") elif score >= 60: print("Passed") else: print("Try again") What prints?
free practice
Build confidence with a question you can solve without Pro.