Previous Lecture Lecture 11 Next Lecture

Lecture 11, Tue 02/13

For Loops, Range Function

Recorded Lecture: 2_13_24

For Loops

SYNTAX:
for VARIABLE in COLLECTION:
	STATEMENT(S)
numList = [10, 20, 30, 40]
for n in numList:
	print(n)
print("Done with loop")
s = "Python"
for char in s:
	print(char)
print("Done with loop")
D = {10:"ten", 20:"twenty"}
for k in D:
	print(k) # keys
	print(D[k]) # values
print("Done with loop")
def hasOddNumber(intList):
	''' Returns True if the list has an odd number.
		Returns False otherwise.
	'''
	for x in intList:
		if (x % 2 != 0):
			return True
	return False		# common mistake. What does if / else: do?

numbers1 = [2,4,5,6,8]
numbers2 = [0,10,20,30]
numbers3 = []
print(hasOddNumber(numbers1))
print(hasOddNumber(numbers2))
print(hasOddNumber(numbers3))

range() Function

# Note that list() converts the range return to a list type to display each element
print(list(range(4))) # [0, 1, 2, 3]
print(list(range(2,5))) # [2, 3, 4]
print(list(range(5, 2))) # []
print(list(range(1, 7, 3))) # [1, 4]
print(list(range(7, 1, -2))) # [7, 5, 3]
# Example: count to 10
for i in range(10):
	print("num =", i+1)

# Also could do
for i in range(1, 11):
	print("num =", i)
# Example: print first odd numbers up to 10
for i in range(1, 11, 2):
	print("num = ", i)

# Also could do
for i in range(11):
	if i % 2 == 1:
    	print("num = ", i)

While Loops vs. For Loops

Accumulator Pattern

def countOddNumbers(listOfNum):
	''' Returns the number of odd integers in listOfNum '''
	counter = 0
	for num in listOfNum:
		if num % 2 == 1:
			counter += 1
	return counter

numbers1 = [2, 4, 5, 6, 8, 9]
numbers2 = [0, 10, 20, 30]
print(countOddNumbers(numbers1)) # 2
print(countOddNumbers(numbers2)) # 0