Story – Python While Loops

Alex was excited to learn about Python’s while loops. They realized that while loops could be used to repeat a block of code until a certain condition was met.

To better understand while loops, Alex decided to create a simple program that would count down from 10 to 1.

# Program to count down from 10 to 1
# Author: Alex
# Date: 2/25/2023

# Initializing the counter
count = 10

# Looping until the counter reaches 0
while count > 0:
    print(count)
    count -= 1

print("Blast off!")

In this code, Alex used a while loop to repeatedly print the current value of count until it reached 0. Once count reached 0, the loop terminated and the program printed “Blast off!“.

Alex was impressed by how easy it was to use a while loop to repeat a block of code until a certain condition was met. They realized that while loops could be used to solve a variety of problems, such as prompting the user for input until they entered valid data.

# Program to prompt the user for a positive integer
# Author: Alex
# Date: 2/25/2023

# Prompting the user for input
number = int(input("Enter a positive integer: "))

# Looping until the user enters a positive integer
while number <= 0:
    number = int(input("Invalid input. Please enter a positive integer: "))

print("You entered:", number)

In this code, Alex used a while loop to repeatedly prompt the user for input until they entered a positive integer. If the user entered an invalid input, the program would continue to loop and prompt the user for input until a valid input was entered.

Alex was excited to use while loops in their future programs. They realized that while loops were a powerful tool for repeating a block of code until a certain condition was met, and that they could be used to solve a variety of programming problems.