Conditionals and Modules

In this lecture, we will continue our discussion of conditionals in Python.

Last lecture, we looked at some simple if-else conditional statements. Note that the else block is optional.

Today we will discuss the logical operators and, or, and not in Python to construct more complicated Boolean expressions, in addition to nested conditionals.

Logical operators: and, or, not

The logical operators and, or and not in Python are used to combine Boolean values and write more complex Booleans expressions.

and

boolExp1 and boolExp2 evaluates to True iff both boolExp1 and boolExp2 evaluate to True.

or

boolExp1 or bool Exp2 evaluates to True iff at least one of boolExp1 and boolExp2 evaluate to True.

not

not boolExp evaluates to True iff boolExp evaluates to False.

Let us try these out.

Example 1. Check if a number is divisible by 5 and is odd.

Example 2. Ask the user to enter a lowercase letter. Check if it is a vowel or consonant.

Some takeways.

Example 3. Write a function divide that takes two numbers num1 and num2 as input, and returns the result of num1/num2 as long as num2 is not zero. If num2 is zero, print "Cannot divide by zero" and return None.

Nested Conditionals

Sometimes, we may encounter a more complicated conditional structure. Consider the following example.

Write a function weather that takes as input a temperature temp value in Fahrenheit.

Question. How can we organize this using if-else statements?

Attempt 1: Nested If Else

Does the following work?

Attempt 2: Only Ifs

The above function is hard to read with so many indented blocks. What if we used only ifs? What is the trade off?

Class Discussion

Chained if, elif, else Conditionals

If we only need to execute one out of several conditional branches, we can use chained (or multi-branch) conditionals with if, elif, and else to execute exactly one of several branches.

If Else Statement Syntax

if (boolean expression a):
       statement 1
      ...
elif (boolean epression b):
       statement 2
      ...
else:
       statement 3
statement 4

Takeway

Exercise: leapYear function.

Using Functions in Different Files

Especially when we're using larger amounts of code, we'll want to use functions in different files than the one it's defined in To do this, we use the following syntax:

from name-of-file-without-extension> import name-of-function-w/o-arguments