Python Crash Course

For Loops

Loops are used to control how many times a sequence of code needs to run. There are two types of loops in Python:

  1. for Loops
  2. while Loops

In this article, you will use the for loop to iterate through an iterable. An iterable is anything that you can iterate through. This includes:

  • Lists
  • Dictionaries
  • Tuples
  • Strings.

The skeleton for a for loop is as follows:

for element in list_of_elements: //iterates through each element

Iterating through a list

You will start by iterating through a list of months

months = ['January', 'February', 'March']

Using a for loop, print each month in the months list.

for month in months: print(month)




Once again, the body of code must be properly indented within the for loop. The for loop iterates through months 3 times. At each iteration, it prints the respective month.

As an extra resource, the Python visualizer can be accessed here.

Iterating through a range

A range is just a list of numbers. In the Slicing article, you created a list from a range of numbers. You can iterate through a range of numbers using the same for loop notation.

for number in range(0, 100): print(number)






The code performs 100 iterations. At each iteration, it prints the respective number within the range.

Updating elements in a list

A practical use case of for loops is to update elements in a list. Take for example this list of names

names = ['hillary', 'diana', 'brian']

To update elements in the names list, the first step is to print the index of each element. Recall that each element in a list is identified by an index.

To print the index of each element in the names list, you have to iterate through a range that goes from 0 to the length of names .

for index in range(0, len(names)):print(index)




Alternatively, you can omit the 0 and declare only the stop index len(names). Python by default will assume that your range goes from 0 to the stop index.

for index in range(len(names)):print(index)




You can use the index variable to locate each element in the list and print it.

for index in range(len(names)):print(names[index])




Finally, you can update each element in the list by setting it equal to its capitalized form.

for index in range(len(names)): names[index] = names[index].title() print(names[index])




That covers it for looping through lists! The for loop can be used to loop through many more data types. As you will see in the next article, the syntax is exactly the same!

Feedback Summary
8 students





Written Reviews
There are no written reviews yet.