fbpx

For Loops

Iteration

Iteration is a technique used to sequence through a block of code repeatedly until a specific condition either exists or no longer exists, allowing us to make repetitive blocks of code more efficient. We commonly use loops in order to create iteration in a program.

For Loops

We have seen before how we can print out individual elements in a list. For instance:

				
					students = ["Luke", "Leia", "Han", "Chewie", "Lando"]

print(students[0]) 
print(students[1])
print(students[2])
print(students[3])
print(students[4])
# the above statements will print each name on a different line
				
			

While this code is above is very short, it is also very repetitive. Imagine if we had 100 students in the list: it wouldn’t be practical to copy and paste the same line of code 100 times. 

Loops help us solve this problem by making a task like printing out elements in a list more repetitive. Look at the following:

				
					students = ["Luke", "Leia", "Han", "Chewie", "Lando"]

for s in students:
    print(s)
# the above statement will print each name on a different line
				
			

Notice how much more efficient the above example is. All we need to do is specify a variable name for each individual element (in this case we use s), and the list which we want to iterate through. 

We can also iterate through an individual string using a for loop. For example:

				
					name = "John Sample"

for letter in name:
    print(letter)

# Output:
# J
# o
# h
# n 
#
# S
# a
# m
# p
# l
# e
				
			

We can also iterate through dictionaries or other data types. For example:

				
					jerseyNumbers = {"Jordan": 23, "Pippen": 33, "Rodman": 91, "Harper": 9, "Kukoc": 7}

for lastName in jerseyNumbers:
    print(lastName, "wore number", jerseyNumbers[lastName])

# Output:
# Jordan wore number 23
# Pippen wore number 33
# Rodman wore number 91
# Harper wore number 9
# Kukoc wore number 7
				
			

Replit Practice

Loading...