Basic Overview:

  • We create a list of numbers: [1, 2, 3, 4, 5].
  • A for loop iterates over each item in the list.
  • The loop prints each item in the list.

What’s Happening:

In this lesson, we learn how to iterate over a list using loops. A list is a collection of items, and a loop allows us to access each item one by one. In this example, we use a for loop to iterate over a list of numbers, and the loop prints each number from the list. The same concept can be applied to any collection, such as a list of favorite foods, which you can display using a loop.

# Pseudocode:
# numbers ← [1, 2, 3, 4, 5]
# FOR EACH number IN numbers:
#     DISPLAY number
# END FOR

# Python Code:
numbers = [1, 2, 3, 4, 5]
for number in numbers:
    print(number)

#Problem: Looping Through a List
#Create a list of your three favorite foods. Write a loop to display each food item in the list.

1
2
3
4
5

Homework Problem:

You are tasked with writing a simple Python script that uses a for loop to iterate through a list of numbers and print each number.

Requirements:

Write a for loop to iterate through the given list of numbers. Print each number as you iterate through the list. Input: Use the list of numbers: [1, 2, 3, 4, 5]

Expected Output: You should print each number from the list.

#Sample Answers:

numbers = [1, 2, 3, 4, 5]
for number in numbers:
    print(number)

1
2
3
4
5

Additional Notes:

  • Lists: A list is a sequence of items stored together in a single variable. You can store numbers, strings, or even other lists inside a list.
  • For Loop: The for loop is commonly used to iterate over elements in a collection, such as a list. This loop automatically moves through the collection, one item at a time, until all items have been processed.
  • Use Case: Iterating over a list is helpful when you need to perform the same operation on each item, like printing, modifying, or checking conditions.