Story – Python For Loops

After mastering the while loop, Alex was excited to learn about another type of loop in Python – the for loop. They realized that for loops were another way to iterate over a sequence of values and perform a block of code on each value in the sequence.

To better understand for loops, Alex decided to create a simple program that would print each letter in the word “Python” on a separate line.

# Program to print each letter in "Python"
# Author: Alex
# Date: 2/25/2023

# Iterating over each character in the word "Python"
for letter in "Python":
    print(letter)

In this code, Alex used a for loop to iterate over each character in the string “Python” and print it on a separate line. They realized that the for keyword was followed by a variable name (in this case, letter) that would be assigned to each value in the sequence, and the code block below the for statement would be executed for each value in the sequence.

Alex was impressed by how concise and readable the for loop syntax was. They realized that for loops could be used to solve a variety of problems, such as iterating over the elements in a list or tuple.

# Program to calculate the sum of a list of numbers
# Author: Alex
# Date: 2/25/2023

# Initializing the list of numbers
numbers = [1, 2, 3, 4, 5]

# Initializing the sum variable
sum = 0

# Iterating over each number in the list
for number in numbers:
    sum += number

print("The sum of the numbers is:", sum)

In this code, Alex used a for loop to iterate over each number in the list numbers and add it to the sum variable. Once the loop finished iterating over all the numbers in the list, the program printed the final value of the sum variable.

Alex was excited to use for loops in their future programs. They realized that for loops were a powerful tool for iterating over a sequence of values and performing a block of code on each value in the sequence.