- The ‘if’ statement
- The ‘if / else’ statement
- The ‘if / elif / else’ statement
- Nested conditionals
- Conditional expressions
When writing a program, sometimes we need to do different things depending on the context: “if this happens, go this way; if that happens, go that way; if none of the above, go this other way”.
The conditional statements
elif (else if) and
else allow us to branch the control flow of a program.
The ‘if’ statement
if statement allows us to run a certain piece of code only if a certain condition is met. A simple example:
isRaining = True if isRaining: print("take your rain coat")
Here we are using the
if statement to check if the variable is set to
True; if it is, we print out some text; otherwise, nothing happens.
The expression after
if can be anything: a comparison, a membership test, a function, an object, etc.
age = 16 if age < 18: print('you cannot get a driver license yet')
The ‘if / else’ statement
else statement allows us to run a different piece of code when the condition defined in the
if statement is not met:
>>> userName = input("user name: ") >>> if userName: ... 'hello ' + userName ... else: ... 'error (no name given)'
The example script above will first prompt the user for a name. If one is given, the program will return a greeting; if the question is escaped (by pressing Enter), it will return an error message.
The ‘if / elif / else’ statement
If we need to handle more than just two conditions, we can use one or more
elif (else if) statements between
hour = 13 if 0 < hour < 12: print("good morning") elif 12 <= hour <= 17: print("good afternoon") else: print("good evening")
Conditionals can be nested and combined with other expressions into larger compound statements:
if font: if font.selectedGlyphs: for glyph in font.selectedGlyphs: glyph.doSomething() else: print('no glyphs selected') else: print('no font selected')
Conditional expressions or ternary operators are a condensed form of conditional statements. They can be used inline to choose one value or another depending on the evaluation of a statement.
When used well, conditional expressions can help to reduce code size and enhance readability. Here’s an example:
sky = 'blue' value = 10 if sky is 'blue' else 100
The corresponding code using
else statements would take four lines:
sky = 'blue' if sky is 'blue': value = 10 else: value = 100