Introduction to Python Programming. Section 10. Conditions

10 Conditions

10.1 Objectives

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.

10.2 Why learn about conditions?

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.

10.3 Boolean values, operators, and expressions

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.

10.4 Using conditions without the keyword if

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

if A then B else C
is identical with the truth table of the expression
(A and B) or ((not A) and C)
This means that any language which defines Boolean operations automatically provides a way to handle if-then-else conditions, even when the keyword if is not used (such as for example in Prolog).

10.5 The if statement

In Python, the simplest way to conditionally execute code is to make it part of an if statement:

  if <boolean_expression>:
      <do_something>

Note the indentation and the mandatory colon : after the Boolean expression. As an example:

  if x > 0:
      print(’The value of x is’, x)

This code has several possible outputs. First, if x is positive (for example 1.5):

  The value of x is 1.5

Second, if x is non-positive (for example 0):

  

Third, if x is of incompatible type:

  TypeError: ’>’ not supported between ’str’ and ’int’

And last, if x is undefined:

  NameError: name ’x’ is not defined

10.6 Types of values accepted by the if statement

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 value:

  if True:
      print(’This will always be printed.’)

or

  if False:
      print(’This will never be printed.’)

One can use a Boolean variable:

  if flag:
      print(’This will be printed if flag is True.’)

Boolean expressions are admissible as well,

  if ’A’ in txt:
      print(~This will be printed if string txt contains ’A’.~)

and so are Boolean functions:

  if isinstance(n, int):
      print(’This will be printed if n is an integer.’)

The keyword if can be followed by a number (integer, float or complex):

  if v:
      print(’This will be printed if v is not zero.’)

One can use a text string:

  if txt:
      print(’This will be printed if string txt is not empty.’)

Even a list, tuple or a dictionary can be used:

  if L:
      print(’This will be printed if list L is not empty.’)

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:

  if len(L) != 0:
      print(’This will be printed if list L is not empty.’)

10.7 The optional else branch

The keyword else is optional and can be used for code to be evaluated when the condition is not satisfied:

  if <boolean_expression>:
      <do_something>
  else:
      <do_something_else>

Here is an example:

  invitations = [’Eli’, ’Elsa’, ’Eva’]
  name = ’Anna’
  if name in invitations:
      print(name +  was invited.’)
  else:
      print(name +  was not invited.’)

  Anna was not invited.

10.8 The full if-elif-else statement

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 general,

  if <boolean_expression_1>:
      <do_action_1>
  elif <boolean_expression_2>:
      <do_action_2>
  else:
      <do_action_3>

means exactly the same as

  if <boolean_expression_1>:
      <do_action_1>
  else:
      if <boolean_expression_2>:
          <do_action_2>
      else:
          <do_action_3>

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.

10.9 Example – five boxes of apples

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:

  def box(weight):
      if weight < 5:
          return A
      elif weight < 10:
          return B
      elif weight < 15:
          return C
      elif weight < 20:
          return D
      else:
          return E

Here is the same code without the elif statement:

  def box(weight):
      if weight < 5:
          return A
      else:
          if weight < 10:
              return B
          else:
              if weight < 15:
                  return C
              else:
                  if weight < 20:
                      return D
                  else:
                      return E

In summary, the elif statement simplifies conditions with multiple cases.

10.10 Conditional (ternary) expressions

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 form

value_1 if boolean_expression else value_2
Unlike the if, if-else or if-elif-else statements, conditional expressions are not statements. This means that they can be inserted into formulas and text strings, lists, tuples, dictionaries, etc. In the following example, a conditional expression is used in a price calculation:

  discount = True
  percent = 20
  base = 1000
  final_price = base * (1 - percent / 100) if discount else base
  print(’Your price is’, final_price)

  Your price is 800.0

And,

  discount = False
  percent = 20
  base = 1000
  final_price = base * (1 - percent / 100) if discount else base
  print(’Your price is’, final_price)

  Your price is 1000

In this example, a conditional expression is used within a text string:

  name = ’Zoe’
  age = 16
  txt = name + ( is a child.’ if age < 18 else  is an adult.’)
  print(txt)

  Zoe is a child.

And,

  name = ’Nathan’
  age = 21
  txt = name + ( is a child.’ if age < 18 else  is an adult.’)
  print(txt)

  Nathan is an adult.

10.11 Nested conditional expressions

Conditional expressions can be nested, which makes it possible to handle situations with more than two options:

  name = ’Mark’
  age = 14
  txt = name + ( is a child.’ if age < 13 else \
  ( is a teenager.’ if age < 18 else  is an adult.’))
  print(txt)

  Mark is a teenager.

Using parentheses is desirable. Here is what happens when we remove them:

  name = ’Mark’
  age = 14
  txt = name +  is a child.’ if age < 13 else \
   is a teenager.’ if age < 18 else  is an adult.’
  print(txt)

   is a teenager.

10.12 Famous workarounds

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:

  name = ’Zoe’
  age = 16
  txt = name + ( is an adult.’,  is a child.’)[age < 18]
  print(txt)

  Zoe is a child.

And here is Nathan who with 21 years is an adult:

  name = ’Nathan’
  age = 21
  txt = name + ( is an adult.’,  is a child.’)[age < 18]
  print(txt)

  Nathan is an adult.

To understand how this works, notice that True works as 1 and False as 0 when used as an index:

  L = [’A’, ’B’]
  print(L[False])

  A

and

  L = [’A’, ’B’]
  print(L[True])

  B

If you insisted on calling this a dirty trick, we would probably not object.


Table of Contents

Created on August 6, 2018 in Python I,   Python II.
Add Comment
0 Comment(s)

Your Comment

By posting your comment, you agree to the privacy policy and terms of service.