HomepageTeaching PageResearch PageResources Page

Homework: Nested and Chained Conditionals

Read sections 5.6 and 5.7 in the book and do the examples.

I'd like to fix last time's function to give a bit more description when the initial condition fails. I'd like the output to look like this:

>>> positive_and_divisible_by_3(123)
Yes, 123 is divisible by 3 and positive.
>>> positive_and_divisible_by_3(-1231)
No, -1231 is not positive.
>>> positive_and_divisible_by_3(37)
No, 37 is not divisible by 3.
>>> positive_and_divisible_by_3(-6)
No, -6 not positive.
>>> positive_and_divisible_by_3(0)
No, 0 not positive.
        

Here's how I can use nested conditionals to make this happen:

def positive_and_divisible_by_3(x):
    """Prints whether x is divisible by 3 and positive."""
    if (x % 3 == 0) and (x > 0):
        print("Yes,", x, "is divisible by 3 and positive.")
    else:
        #at this point, we know that x is either not positive or not divisible by 3
        if x <= 0:
            print("No,", x, "is not positive.")
        else:
            print("No,", x, "is not divisible by 3.")
        

Alternatively, I could write an equivalent function with a chained conditional instead of the nested one:

def positive_and_divisible_by_3(x):
    """Prints whether x is divisible by 3 and positive."""
    if (x % 3 == 0) and (x > 0):
        print("Yes,", x, "is divisible by 3 and positive.")
    elif x <= 0:
        print("No,", x, "is not positive.")
    else:
        print("No,", x, "is not divisible by 3.")
        

In general, when I am writing a conditional, I try to keep it chained unless one of the cases is really confusing, in which case I will nest things.