Previous Lecture Lecture 12 Next Lecture

Lecture 12, Thu 02/15

More on loops

Recorded Lecture: 2_15_24

Accumulator Pattern Example

def countCapitalWords(listOfString):
	''' Returns the number of strings in listOfString that start
		with a capital letter (A - Z)'''
	counter = 0
	for s in listOfString:
		if len(s) > 0:
			if ord(s[0]) >= 65 and ord(s[0]) <= 90: # str.isupper() works too
				counter += 1
	return counter

assert countCapitalWords([]) == 0
assert countCapitalWords([""]) == 0
assert countCapitalWords(["1", "A1"]) == 1
assert countCapitalWords(["A", "b", "C"]) == 2

Nested Loops

for i in range(3):
	for j in range(10, 12):
		print(i, j)
def countVowels(strList):
	vowels = "AEIOUaeiou"
	numVowels = 0
	for s in listOfStrings: # s is an element in listOfStrings
		for c in s: # c is a character in s
			if c in vowels:
				numVowels += 1
	return numVowels

listOfStrings = "This is a list of strings".split()
assert countVowels(listOfStrings) == 6

break and continue

x = 0
while True:
	x = x + 1
	print("Start of while body, x =", x)
	if x > 3:
		break
	print("End while body, x =", x)
print("outside while loop")
x = 0
while True:
	x = x + 1
	print ("Start of while body, x =", x)
	if x % 2 == 0: # if x is even
		continue
	if x >= 5:
		break
	print("End of while body, x =", x)
print("Outside while loop")
for i in range(5):
	print("i at start of iteration:", i)
	if i % 2 == 1:
		continue
	print("i at end of iteration (even):", i)
print("Done with loop")

Loop else

i = 0 # change this to 4 to see else statements execute

while i < 10:
	print("i =", i)
	if i == 3:
		break
	i += 1
else:
	print("only see this if break was not executed")

print("Continue execution")
numbers = [1,2,3]

for i in numbers:
	print("i =", i)
	if i == 2: 	# change this to 4 to see else statements execute
		break
else:
	print("only see this if break was not executed")

print("Continue execution")

Enumerate

element1, element2 = ["A", "Z"]
print(element1) # A
print(element2) # Z
letters = ["A", "B", "C"]
for (index, value) in enumerate(letters):
	print("index = ", index, ", value = ", value, sep="")
letters = {"A", "B", "C", "D", "E"}
for (index, value) in enumerate(letters):
	print("index = ", index, ", value = ", value, sep="")

A Number Guessing Game Example

magicNumber = 40
guess = input("Guessing Game!\nPlease enter an int between 0 - 100 \
(type 'exit' to end game): ")

while True:
	if guess == "exit":
		print("Game over!")
		break
	number = int(guess)
	if number < 0 or number > 100:
		guess = input("Invalid number. Please try again: ")
		continue
	if number < magicNumber:
		guess = input("Too small. Please try again: ")
		continue
	if number > magicNumber:
		guess = input("Too big. Please try again: ")
		continue
	if number == magicNumber:
		print("Winner winner chicken dinner! You guessed", magicNumber)
		break
print("Done.")