More Loops CMSC 201 Overview Today we will learn about: • For loops Motivation A lot of times, we have a pattern like this: a = 0 myList = [1, 2, 3] while a < len(myList): print(myList[a]); a = a +1; This is a way we can iterate over a list. For Loops For loops give us a faster way of doing the same thing! myList = [1, 2, 3] for listItem in myList: print (listItem); For Loops myList = [1, 2, 3] for listItem in myList: print (listItem); In the for loop, we are declaring a new variable called “listItem”. The for loop is going to be changing this for us! The first time through the loop, listItem will be the first element of the list. The second time through the loop, it will be the second element, and so on until the list is done. Example Finding the average using for loops: myList = [1, 2, 3, 4] sum = 0 for listItem in myList: sum = listItem + sum; print(sum / len(myList)) A Downside! What do you think this code does? myList = [1, 2, 3, 4] for listItem in myList: listItem = 4 print(myList) What are the possibilities? A Downside! What do you think this code does? myList = [1, 2, 3, 4] for listItem in myList: listItem = 4 print(myList) Prints: [1, 2, 3, 4] A Downside! What do you think this code does? myList = [1, 2, 3, 4] for listItem in myList: listItem = 4 print(myList) Changing listItem DOES NOT CHANGE THE ORIGINAL LIST! listItem is just a copy of each element. For Loop Trick Frequently we want to do something like this: a = 0 while a < 10: print(a) a = a + 1 A lot of times, we want loops that count. For Loop Trick There is a built in python function that gives you a list of numbers! a = range(0, 10) print(a) Prints: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] The range function gives you a list of numbers between the first number (inclusive) and the second number (exclusive) For Loop Trick a = range(0, 10) print(a) So now we can create a list of numbers. Any ideas what we can do with that? For Loop Trick for num in range(0, 10): print(num) An easier way to make a counting loop! Prints: 0 1 2 3 4 5 6 7 8 9 For Loop Trick We can even count by whatever number we want! for num in range(0, 10, 2): print(num) Prints: 0 2 4 5 6 8 Exercise Take in five numbers and find the lowest. Exercise Take in five numbers and find the lowest. SIZE = 5 def main(): myList =[] for i in range(SIZE): myList.append(int(input("Value: "))) #assume myList[0] is min theMin = myList[0] for i in range(SIZE): if myList[i] <theMin: theMin = myList[i] print ("The min is", theMin) main() Summary: For loops: • Use for iterating over lists • Also use in situations where we want loops to count. While loops: • Use when we have some condition that doesn’t fall into the previous two categories.