Branching in Python (Part 2)

Translating from pseudocode

Pseudocode if a > b return a else if a < b return b else return 0 Indent

Python if a > b: return a elif a < b: return b else: return 0 Indent evenly

There is a slight change when going from pseudocode to Python in that elif is used instead of else if. You still need a colon at the end of the line and you still need to indent.

Python convention

Indent four spaces.


Example: ordinals

To practice handling a situation with more than two cases, we consider how to form an ordinal number, like first, second, or third. The following are the steps required to form an ordinal number.

  • Since we want to produce a string, we start by converting the integer into a string.
  • Next, we determine the letter-suffix ending. There are four cases depending on the last digit:
    • Use "st" if the ending digit is 1.
    • Use "nd" if the ending digit is 2.
    • Use "rd" if the ending digit is 3.
    • Use "th" if the ending digit is none of the above.
  • Concatenate the input number and the appropriate letter-suffix ending.

Each number what we input results in a different course of action. After determining the ending, the branches rejoin for the two parts to be concatenated.


Writing the function

As usual, comments in the code will be used to indicate each step outlined earlier.

def ordinal(num):

We start with the header.


    ## Convert integer to a string
    root = str(num)

The str function converts the integer to a string.


    ## Determine the ending
    if num % 10 == 1:
        ending = "st"
    elif num % 10 == 2:
        ending = "nd"
    elif num % 10 == 3:
        ending = "rd"
    else:
        ending = "th"

To distinguish among the four cases, we use remainder on division by 10. Another option would have been to examine the last character in root. Either is fine. We use three conditions to distinguish among four cases and fill in the courses of action for each case.


    ## Concatenate the two parts
    return root + ending

Finally, return the result.


print(ordinal(21))
print(ordinal(642))
print(ordinal(53))
print(ordinal(21325))

We use some possible inputs for testing.


Here are all parts of our function put together:

def ordinal(num):
    ## Convert integer to a string
    root = str(num)

    ## Determine the ending
    if num % 10 == 1:
        ending = "st"
    elif num % 10 == 2:
        ending = "nd"
    elif num % 10 == 3:
        ending = "rd"
    else:
        ending = "th"

    ## Concatenate the two parts
    return root + ending

print(ordinal(21))
print(ordinal(642))
print(ordinal(53))
print(ordinal(21325))

We get the following output when the code is run:

21st
642nd
53rd
21325th

Example: car safety

As a more complex example, let's determine safe seating given weight, height, and age. First, we need to consider the regulations for use of seat belts, boosters, and car seats. Assuming that our parameter names are weight, height, and age, we can translate the condition for seat belts as follows:

  • Use seat belt if at least 36 kg, at least 145 cm, or at least 8 years.
  • Use booster seat if at least 18 and less than 36 kg, under 145 cm, and under 8 years.
  • Use forward-facing car seat if at least 9 and less than 18 kg.
  • Use backward-facing car seat if under 9 kg.

Similarly, here are the conditions for each case:

  • For seat belts: weight >= 36 or height >= 145 or age >= 8
  • For booster seats: 18 <= weight < 36 and height < 145 and age < 8
  • For forward-facing car seats: 9 <= weight < 18
  • For backward-facing car seats: weight < 9

Simplifying the conditions

We clearly won't need to use all four conditions to distinguish among the four cases.

  • For seat belts: weight >= 36 or height >= 145 or age >= 8
  • For booster seats: 18 <= weight < 36 and height < 145 and age < 8
  • For forward-facing car seats: 9 <= weight < 18
  • For backward-facing car seats: weight < 9

I'll give you the code first and explain it afterwords:

def car_safety(weight, height, age):
    if weight >= 36 or height >= 145 or age >= 8:
        return("Seat belt")
    elif 18 <= weight:
        return("Booster")
    elif 9 <= weight:
        return("Forward-facing car seat")
    else:
        return("Backward-facing car seat")

Once we know that all of the first three conditions are False, we know that the last condition is True. We can use this same idea to simplify the other conditions. For the second condition, we already know that the first condition is False, hence weight < 36, height < 145, and age < 8. Similarly, for the third condition, we already know that the second condition is False and hence weight < 18. In the last case, we know that the third condition is False, and hence weight < 9.


Example: determining if a string is a question

As our next example, suppose we want to know if an input string is asking a question.

def is_question(entry):

We write the header.


    if len(entry) > 0:

We want to check the last character to see if it is a question mark, but only if the string is nonempty. We divide the cases into two groups: nonempty and empty.


        if entry[-1] == "?":
            return "Question"
        else:
            return "Statement"

Once we know that the condition len(entry)>0 is true, it is safe to use an index on the input. We return the string "Question" when the last character is a question mark and the string "Statement" when it is not.


    else:
        return "Statement"

We also return the string "Statement" when the input string is empty.


print(is_question("cat"))
print(is_question("cat?"))
print(is_question(""))

Now we write some test cases.


Here's our function when all the parts are put together:

def is_question(entry):
    if len(entry) > 0:
        if entry[-1] == "?":
            return "Question"
        else:
            return "Statement"
    else:
        return "Statement"

print(is_question("cat"))
print(is_question("cat?"))
print(is_question(""))

We get the following output when the code is run:

Statement
Question
Statement

Another option is to “flatten” the nesting by listing the three cases using if, elif, and else.

def is_question(entry):
    if len(entry) == 0:
        return "Statement"
    elif entry[-1] == "?":
        return "Question"
    else:
        return "Statement"

Here we've made the first condition be that the string is empty. That way we can safely check the last character in the second condition: because the first condition is False, the string is guaranteed to be nonempty.