Aug 31

Lecture Overview

Booleans

b1 = True
b2 = False
b3 = b1 and b2
b4 = b1 or b2
b5 = not b1
b6 = (b1 and b2) or (b4 and b3)
print(b1, b2, b3, b4, b5, b6)

We can also create booleans as the result of comparison operators.

x = 4
y = 10
z = 18
b1 = x < y
b2 = x > y
b3 = x >= y
b4 = x >= x
b5 = z <= z
b6 = z <= x
b7 = x == x
b8 = x == y
print(b1, b2, b3, b4, b5, b6, b7, b8)
x = "Hello"
y = "Goodbye"
z = "Goodman"
print(x == y)
print(x == x)
print(x < y)
print(x > y)
print(y >= z)

The if statement

In python, the most important use of booleans is in an if statement. Section 4.1 that I linked to describes it pretty well. Any expression which produces a boolean can appear after the if and the value of the boolean determines which block of code is executed. The else and elif parts are optional.

name = input("Enter a name: ")

# Lower case letters are sorted after upper case letters, so the
# dictionary ordering will place any string which starts with
# an upper case letter as smaller than "a".
if name >= "a":
    print("You did not capitalize your name!")
    print("What gives?")

if name == "John" or name == "Jon":
    print("That's my name")
    x = 20
elif name > "R":
    print("Hello, ", name)
    x = 55
else:
    print("Hi, ", name)
    x = 104

print(x)

Exercises