8 – For Loops

Now that you’ve learned about conditional statements, let’s move on to loops, which allow us to repeat blocks of code. Python has two kinds, for loops and while loops. Let’s first take a look at the for loop, which we can use to iterate over an iterable. An iterable is an object that can return one of its elements at a time. This can include sequence types such as strings, lists, and tuples as well as non-sequenced types such as dictionaries and files. You can define objects within iter method to allow them to be used as an iterable, which you can find more information on in the notes below. Consider this for loop that iterates through a list of cities, capitalizes each one, and prints it. The for keyword signals that this is a for loop. Cities is the iterable and city is the loop’s iteration variable. That is the variable that represents the element in the iterable that the loop is currently processing. So, in the first iteration, city would be New York City. In the second iteration, it would be Mountain View,and so on. We can use the city variable to refer to an element within the indented body of a for loop during any iteration. This indented body is executed once for each element in cities. You can name iteration variables however you like though this example demonstrates a common pattern. The name of the list cities is the plural form of city, the name of the iteration variable. Naming lists and iteration variables in this style makes it easier for other programmers to understand the purpose of each variable. So far, the loops we’ve written extract information from lists. We can also use for loops to create lists and to modify lists. To create a new list, we can start with an empty list, and then use the append method to add new items. This for loop iterates through each city and cities and appends it to capitalized cities. Modifying a list is a bit more involved and requires a use of a new function, range. Range is a built in function used to create immutable sequences of numbers. It has three arguments which must all be integers; start, stop, and step. Start is the first number of the sequence. Stop is one above the last number of the sequence. And step is the difference between the numbers in the sequence. If unspecified, start defaults to zero and step defaults to one. Calling range with one integer will make that the stop argument and return a sequence of numbers from zero to that integer minus one. So, range four returns zero through four minus one, which is three. Calling range with two integers will make those the start and stop, and return a sequence of numbers from the first number to the second number minus one. Range two, six returns a sequence from two to five. Calling range with three integers will return a sequence of numbers from the first to the second minus one separated by the third. So, range 1, 10, 2 returns a sequence from one to nine incremented by two. Notice in these examples, we adopt range in a list before printing it. This is because printing just the output of range only shows you a range object. You can view the values in the range object by converting it to a list or iterating through it in a for loop. Back in our cities example, we can use the range function to generate the indices of each value in the cities list. This let’s us access the elements of the list with cities bracket index. So, that we can modify the values in the cities list in place. Let’s go through one iteration of this to show exactly how all these pieces work together. Len cities provides four, so the list will be a range from zero to three. The index will take on each of these values one at a time. So, in this first iteration, we’ll have an index of zero. This part here will then index the first city, New York City, capitalize it using title, then place it back in place of the original New York City spot. This same process would then occur for each of the additional cities. We can use print to see the change in the cities list at each iteration. By getting a list of indices with the range function, we were able to index into each element of a list in a for loop to apply a change. While this modification is one application of the range function, that isn’t the only thing it’s useful for. You will frequently use range to repeat an action a certain number of times.

Dr. Serendipity에서 더 알아보기

지금 구독하여 계속 읽고 전체 아카이브에 액세스하세요.

Continue reading