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.
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.
20 < 13 and 6 == 6
False
20 < 13 or 6 == 6
True
result = (6 == 6)
result
True
not 20 < 13
True
not 6 == 6
False
result = (6 == 6)
# result = True
# Note: no need to test for == True in expression
if (result):
print("true!")
true!
Example 1. Check if a number is divisible by 5 and is odd.
def odd_multiple_five(num):
"Returns true if num is divisible by 5 and odd"
return num % 5 == 0 and num % 2 == 1
odd_multiple_five(55)
True
odd_multiple_five(80)
False
Example 2. Ask the user to enter a lowercase letter. Check if it is a vowel or consonant.
def is_vowel(letter):
"""Takes lowercase letter as input and returns
True if it is a vowel, else returns False"""
# can do an if else or since we are
# returning the truth value of expression,
# can directly return
# this does not work because "e", "i", "o", and "u" are not boolean expressions
# return letter == "a" or "e" or "i" or "o" or "u"
return letter == 'a' or letter == 'e' or letter == 'i' or letter == 'o' or letter == 'u'
is_vowel('b')
False
is_vowel('a')
True
is_vowel('z')
False
Some takeways.
letter == 'a' or 'e' or 'i' or 'o' 'u'
: logical operators take bool
type operands, not strings.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.
def divide(num1, num2):
if not (num2 == 0): # can also write num2 != 0
return num1/num2
else:
print("Cannot divide by Zero")
# do we need to say anything after this?
# if we get here we will implicitly return None
divide(7, 3)
2.3333333333333335
divide(9, 0)
Cannot divide by Zero
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?
Does the following work?
def weather1(temp):
if temp > 80:
print("It is a hot one out there.")
else:
if temp >= 60:
print("Nice day out, enjoy!")
else:
if temp >= 40:
print("Chilly day, wear a sweater.")
else:
print("Its freezing out, bring a winter coat!")
weather1(89)
It is a hot one out there.
weather1(72)
Nice day out, enjoy!
weather1(55)
Chilly day, wear a sweater.
weather1(33)
Its freezing out, bring a winter coat!
The above function is hard to read with so many indented blocks. What if we used only if
s? What is the trade off?
def weather2(temp):
if temp > 80:
print("It is a hot one out there.")
if temp >= 60 and temp <= 80:
print("Nice day out, enjoy!")
if temp <60 and temp >= 40:
print("Chilly day, wear a sweater")
if temp < 40:
print("Its freezing out, bring a winter coat!")
weather2(89)
It is a hot one out there.
weather2(72)
Nice day out, enjoy!
weather2(55)
Chilly day, wear a sweater
weather2(33)
Its freezing out, bring a winter coat!
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
(boolean expression a):
statement 1
...
elif
(boolean epression b):
statement 2
...
else
:
statement 3
statement 4
def weather3(temp):
if temp > 80:
print("It is a hot one out there.")
elif temp >= 60:
print("Nice day out, enjoy!")
elif temp >= 40:
print("Chilly day, wear a sweater.")
else:
print("Its freezing out, bring a winter coat!")
weather3(89)
It is a hot one out there.
weather3(72)
Nice day out, enjoy!
weather3(55)
Chilly day, wear a sweater.
weather3(33)
Its freezing out, bring a winter coat!
if, elif, else
conditional evaluates to True
, using them avoids unnecessary checks incurred by chaining if
statements one after the other.leapYear
function.¶def is_leap(year):
"""Takes a year (int) as input and returns
True if it is a leap year, else returns False"""
# fill in yourself
return True
def is_leap(year):
"""Takes a year (int) as input and returns
True if it is a leap year, else returns False"""
# if not divisible by 4, return False
if year % 4 != 0:
return False
# is divisible by 4 but not divisible by 100
elif year % 100 != 0:
return False
# is divisible by 4 and divisible by 100
# but not divisible by 400, return False
elif year % 400 != 0:
return False
return True
# is divisible by 400 (and also 4, and 100)
# return True
year = 2023
# call isLeap
if is_leap(year):
print(year, "is a leap year!")
else:
print(year, "is not a leap year.")
2023 is not a leap year.
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
# if is_leap is saved in leap.py:
from leap import is_leap