An if statement runs a block only when its condition is true.
temperature = 31
if temperature > 30:
print("It is hot outside.")The indented line belongs to the if. Python uses indentation instead of curly braces, so consistent spacing is part of the syntax. Four spaces is the standard.
Adding alternatives#
score = 87
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(grade)elif is checked only when every previous condition was false. The else block runs when none matched. Conditions are tested from top to bottom, so order matters.
Nested conditions#
age = 20
has_ticket = False
if age >= 18:
if has_ticket:
print("Entry allowed")
else:
print("Buy a ticket first")
else:
print("Entry requires an adult")Nesting is useful when the inner condition only makes sense after the outer one. Avoid deep nesting; extract a function or combine conditions with and when it stays readable.
Conditional expressions#
For a short either/or value, use a conditional expression:
number = 7
label = "even" if number % 2 == 0 else "odd"
print(label)This is an expression, not a statement. Use it when each branch is a single simple value.
Common mistakes#
- Using
=instead of==in a comparison. - Forgetting the colon at the end of
if,elif, orelse. - Mixing tabs and spaces. Configure your editor to insert spaces.
- Leaving an empty block. Use
passas a temporary placeholder. - Writing
if x == 1 or 2:. This is always true; writeif x == 1 or x == 2:orif x in (1, 2):.
A complete example#
username = "ada"
password = "python123"
if not username:
print("Username is required")
elif len(password) < 8:
print("Password must contain at least 8 characters")
elif username == password:
print("Username and password must differ")
else:
print("Credentials look valid")Practice#
Write a program that reads a score from 0 to 100 and prints a grade. Handle invalid scores separately. Then extend it to print a message for a perfect score.
