For Loops#

In Python, count-controlled loops are written using a for statement and are called for loop. A for loop iterates over each value in a group of values- the lines of code nested under the initial statement run for each iteration.

for loops let us iterate through a definite set of objects. In each iteration through the for loop, Python will:

  • Extract one element from the dataset

  • Execute the body of the for loop using the item bound to the element

  • Go back to the first step

  • Keep iterating through the loop until reaching the end of the dataset

The basic syntax in a for loop:

# sample for loop syntax
for item in dataset:
 statement(s)

In this syntax, item is a placeholder for each element in dataset. We can replace item with another word or letter character.

# sample for loop syntax
for i in dataset:
	statement(s)

In this syntax, dataset stands for the group of items we want Python to iterate over. That group of items could be a list, a list variable, string, string variable, etc.

Python Examples#

Let’s look at a few examples in Python, starting by iterating over items in a list.

# list of numbers
numbers = [1, 3, 5, 7, 9, 11, 13, 15, 17]

# sample for loop that iterates over items in list and outputs each number
for number in numbers:
 print(number)

We can also nest if-then-else logic in a for loop:

# list of numbers
numbers = [1, 3, 5, 7, 9, 11, 13, 15, 17]

# for loop that iterates over numbers
for number in numbers:
  if number < 10:
    print(str(number) + " is less than 10")
  elif number > = 10 and number < 15:
    print(str(number) + " is greater than or equal to 10 and less than 15")
  else:
    print(str(number) + " is greater than 15")

Comprehension Check#

Clipboard icon Python For Loops Comprehension Check

Application#

Q5: Let’s return to the previous question’s program. How would you modify your program to use a for loop instead of a while loop? Answer to this question includes program + comments that document process and explain your code.

As a reminder, your output might look like the following:

1 Python
2 Python
3 Python
4 Python
5 Python
6 Python
7 Python
8 Python
9 Python
IS FUN!

Q6: An earlier application question asked you to modify the program below to search for the characters q and u in the string turquoise.

# assign string variable
color = "turquoise"

# get index number of t character
index_number = color.index("t")

# show index number as part of print statement
print ("The index number for the letter t within the word " + color + " is " + index_number)

Write a program that uses a for loop to return all instances of q and u in the string, not just the first occurrence. Answer to this question includes program + comments that document process and explain your code.