Introduction to Python Programming. Section 10. Conditions
Conditions have been mentioned in various contexts in Subsections 4.35, 4.44, 4.45, 4.46, 5.11, 6.13, 6.14, 7.18, 7.30, 7.31, 8.17, 8.24, 8.25, 9.10 and 9.11. Therefore, writing a separate section about them may seem to be somewhat superfluous. Nevertheless, in this text we like to present every important concept of Python programming in a self-contained manner, and therefore we need to include a section on conditions. Feel free to skip it if you know everything about them. If you’ll keep reading, in this section you will review / learn the following:
- About Boolean (logical) values, operators, and expressions.
- That keyword if is not needed to implement conditions.
- About the if statement and types of values it accepts.
- About the optional else branch.
- About the full if-elif-else statement.
- About conditional (ternary) expressions.
Conditions allow computer programs to adapt to various types of events at runtime, ranging from calculated values to user or sensory input. They are part of all programming paradigms including imperative programming, functional programming, event-driven programming, object-oriented programming, etc.
Unless you are already familiar with Boolean values, operators, and expressions, now is the time to visit Section 6 and learn about them. In particular, in Subsection 6.13 we explained that conditions are based on Booleans.
You already know from Section 6 how to create truth tables. Therefore, it should not be hard
for you to verify that the truth table of the Boolean expression
In Python, the simplest way to conditionally execute code is to make it part of an if
Note the indentation and the mandatory colon : after the Boolean expression. As an
This code has several possible outputs. First, if x is positive (for example 1.5):
Second, if x is non-positive (for example 0):
Third, if x is of incompatible type:
And last, if x is undefined:
When the interpreter finds in the code the keyword if, it looks for an expression behind it. If such an expression is not found, it throws an error. Otherwise the expression is evaluated.
It is worthwhile mentioning that not only True and False but also numbers,
text strings, and even lists etc. are accepted as admissible values. Let’s show some
examples, starting with Booleans. The keyword if can be followed by a Boolean
One can use a Boolean variable:
Boolean expressions are admissible as well,
and so are Boolean functions:
The keyword if can be followed by a number (integer, float or complex):
One can use a text string:
Even a list, tuple or a dictionary can be used:
However, using numbers, text strings, lists and such decreases code readability. It takes a
little effort to be more explicit and convert these into Boolean expressions. For example, the
last example can be improved as follows:
The keyword else is optional and can be used for code to be evaluated when the condition
is not satisfied:
Here is an example:
The elif statement can be used to simplify cases with more than two options.
If you think that "elif" sounds a lot like "else if" then you are absolutely right! In
means exactly the same as
Clearly, the latter involves more indentation. Exactly – the purpose of elif is to make complex conditions more flat. This becomes easier to see as the number of cases grows. Let us therefore show an example with five cases.
Imagine that you have five wooden boxes:
- Box A is for apples that weight under 5 ounces.
- Box B is for apples that weight at least 5 but less than 10 ounces.
- Box C is for apples that weight at least 10 but less than 15 ounces.
- Box D is for apples that weight at least 15 but less than 20 ounces.
- Box E is for apples that weight at least 20 ounces.
Your task is to write a function box(weight) that, given the weight of an apple, chooses the
correct box for it and returns the corresponding letter:
Here is the same code without the elif statement:
In summary, the elif statement simplifies conditions with multiple cases.
Python (as well as C/C++ and other languages) supports a flexible way of working with
conditions called conditional (ternary) expressions. In Python, these expressions have the
In this example, a conditional expression is used within a text string:
Conditional expressions can be nested, which makes it possible to handle situations with
more than two options:
Using parentheses is desirable. Here is what happens when we remove them:
Ternary conditional expressions were not present in older versions of Python (below version
2.5). Therefore programmers developed clever tricks that emulate their behavior. These tricks
are not needed today anymore, but you may find the code in older Python programs.
Therefore it’s good to know how they work. Let’s get back to Zoe from Subsection 10.10 who
is 16 years old:
And here is Nathan who with 21 years is an adult:
To understand how this works, notice that True works as 1 and False as 0 when used as an
If you insisted on calling this a dirty trick, we would probably not object.
Table of Contents
- 1. Introduction
- 2. Using Python as a Scientific Calculator
- 3. Drawing, Plotting, and Data Visualization with Matplotlib
- 4. Working with Text Strings
- 5. Variables and Types
- 6. Boolean Values, Functions, Expressions, and Variables
- 7. Lists, Tuples, Dictionaries, and Sets
- 8. Functions
- 9. The ’For’ Loop
- 10. Conditions
- 11. The ’While’ Loop
- 12. Exceptions
- 13. File Operations
- 14. Object-Oriented Programming I – Introduction
- 15. Object-Oriented Programming II – Class Inheritance
- 16. Object-Oriented Programming III – Advanced Aspects
- 17. Recursion
- 18. Decorators
- 19. Selected Advanced Topics