Stage 1 · 25 min · Free
Conditional statements if / elif / else
Let a program make decisions: comparisons, if, elif, else, the and/or/not operators and indentation rules.
Objectives
- Use the comparison operators ==, !=, <, >, <=, >=
- Write if / elif / else
- Combine conditions with and, or, not
- Indent correctly
Why learn this
A smart program has to branch: enough points means pass, too few means fail; the right password lets you in, the wrong one shows an error.
Concept
if condition: runs the indented block below when the condition is true.
elif (else if) checks another condition when the previous ones were false. else runs when all of them are false. Python stops at the FIRST true branch.
Equality uses ==, while = is assignment. Combine conditions with and (both true), or (either true), not (negation).
After the colon you must start a new line indented by 4 spaces. Lines in the same block must be indented equally.
Syntax
if dieu_kien_1:
lenh
elif dieu_kien_2:
lenh
else:
lenh
Example
diem = float(input())
if diem >= 8:
print("Giỏi")
elif diem >= 5:
print("Đạt")
else:
print("Chưa đạt")Input:
6.5
Output:
Đạt
Line-by-line explanation
- Line 1: reads the score 6.5.
- Line 2: 6.5 >= 8 is false, so line 3 is skipped.
- Line 4: 6.5 >= 5 is true, so line 5 runs and prints Đạt.
- Lines 6-7: don't run, because a true branch was already found.
Common mistakes
if x = 5:= is assignment; comparison needs ==.
if x == 5:if x > 3
print(x)Missing colon at the end of the if line.
if x > 3:if x > 3:
print(x)The block after if must be indented: IndentationError.
Thêm 4 dấu cách trước print(x).Summary
- if / elif / else for branching.
- == compares, = assigns.
- and, or, not combine conditions.
- The colon and 4-space indentation are required.
Write code right in the browser; the grader runs real Python and points to the exact line that's wrong.
Practice for free