So far every line has run, one after another. Real programs make choices. The if statement runs some code only when a condition is true.
marks = 55
if marks >= 40:
print("You passed")
Output:
You passed
Indentation is part of the language
The lines inside the if are pushed in by four spaces (indented). That is how Python knows which lines belong to the decision. The line with if ends with a colon :.
else and elif
marks = 35
if marks >= 40:
print("Pass")
else:
print("Fail")
Output:
Fail
For more than two outcomes use elif (short for "else if"). Python checks from the top and stops at the first true condition.
marks = 83
if marks >= 80:
grade = "Distinction"
elif marks >= 60:
grade = "First division"
elif marks >= 40:
grade = "Pass"
else:
grade = "Fail"
print(grade)
Output:
Distinction
Combining conditions in an if
age = 17
has_citizenship = True
if age >= 18 and has_citizenship:
print("You can vote")
else:
print("Not yet")
Output:
Not yet
Common mistakes
- Forgetting the colon
:at the end of theifline. - Using
=instead of==to compare. - Mixing tabs and spaces. Use four spaces everywhere.
Try it yourself
- Write a program that prints "even" or "odd" for a number.
- Add a grade to the marks program for 90 and above.
- Ask for a person's age and print whether they are a child (under 13), a teenager (13 to 19) or an adult.
Next lesson: repeating work with loops.

Comments
Loading comments…