Conditionals
Basics8 min readLesson 6 of 8
A conditional lets a program choose between paths. Python tests a condition, which produces True or False, and runs an indented block only when the result is True. This is how a program can treat a pass differently from a fail, or show a message only when a password matches.
score = 72
if score >= 50:
print('pass')
else:
print('try again')
print('report complete')Output
pass report complete
6.1 The shape of an if block
An if block starts with the keyword, the condition, and a colon. The next lines are indented, usually by four spaces, and that indentation is part of the syntax.
6.2 Branching further
elifruns another test when the first one fails.elsecatches the remaining case.andrequires both tests to hold.orrequires either test to hold.
Python stops after the first branch that runs.
age = 16
has_ticket = True
if age >= 13 and has_ticket:
print('entry allowed')
else:
print('entry denied')Output
entry allowed
6.3 Common mistake
if mood = 'happy': uses one equals sign and fails as a syntax error. = assigns a value, while == asks whether two values are equal. Keep the indentation consistent inside a block, and remember that the colon belongs to the header line. If a condition is always false, check for a comparison made with the wrong variable or an accidental capital letter.
marks = 68
if marks >= 90:
print('A')
elif marks >= 60:
print('B')Output
B
6.4 Practice
- Set a
marksvariable and print a grade withif,elif, andelse. - Run it with marks at a boundary such as
60, then with a value below60. - Add a condition for attendance and use
andto decide whether the grade is awarded.
