Previous Lecture Lecture 5 Next Lecture

Lecture 5, Tue 01/23

Boolean Expressions, Conditions / Branching

Recorded Lecture: 1_23_24

Boolean Type

x = True
y = False

print(x)
print(type(x))
print(y)
print(type(y))

Relational Operators

print(4 < 6) # True
print(4 == 4) # True
print(4 != 4) # False
print(4 >= 5) # False
print(4 <= 4) # True

Branching with if Statements

Syntax:
if BOOLEAN_EXPRESSION:
	STATEMENT(S) # note these statements are tab indented
milesDriven = 250
print("Should you pull over and fill up your gas tank?")

if milesDriven > 200:
	print("Yes, you need gasoline") # indented (part of the if block)

print("Drive safe") # not part of if block since not indented

Branching With if-else Statements

Syntax:
if BOOLEAN_EXPRESSION:
	STATEMENT(S) #1
else:
	STATEMENT(S) #2
milesDriven = 50
print("Should you pull over and fill up your gas tank?")
if milesDriven > 200:
	print("Yes, you need gasoline")
else:
	print("No, you can keep driving")
print("Drive safe")
if int(input("Enter your age (in years): ")) >= 21:
	print("You can drink alcohol, but do so responsibly")
else:
	print("Can’t drink alcohol yet ... how about some OJ?")

print("Enjoy the party!")

Multi-branch / elif Statements

numUnits = int(input("Enter number of units: "))

if numUnits < 50:
	print("Freshman status")
else:
	if numUnits < 90:
		print("Sophomore status")
	else:
		if numUnits < 135:
			print("Junior status")
		else:
			print("Senior status")
print("Done!")
numUnits = int(input("Enter number of units: "))

if numUnits < 50:
	print("Freshman status")
elif numUnits < 90:
	print("Sophomore status")
elif numUnits < 135:
	print("Junior status")
else:
	print("Senior status")

print("Done!")

Logical Operators

Detecting Numberical Ranges with Logical Operators

x = 10
print((x >= 10) and (x < 15)) # True
print((x < 10) and (x < 15)) # False
print((x < 4) or (x <= 10)) # True
print((x < 15) or (x <= 10)) # True