You are on page 1of 4

The While Loop

In this section, you will learn about loop statements that repeatedly execute instructions until a
goal has been reached.

Let’s solve the investment problem. You put $10,000 into a bank account that earns 5 percent
interest per year. How many years does it take for the account balance to be double the original
investment?

In Python, the while statement implements such a repetition. It has the form

while condition :

statements

Here's how a while loop works:

1. The condition is evaluated. If the condition is true, the code inside the loop is executed.
If the condition is false from the beginning, the code inside the loop will not run at all.
2. After executing the code inside the loop, the program returns
to the beginning of the loop and re-evaluates the condition.
3. If the condition is still true, the code inside the loop is
executed again. This process continues until the condition
becomes false.
4. Once the condition becomes false, the loop terminates, and
the program continues with the code that follows the loop.

As long as the condition remains true, the statements inside the


while statement are executed. This statement block is called the
body of the while statement.
In our case, we want to increment the year counter and add interest while the balance is less
than the target balance of $20,000:

while balance < TARGET :

year = year + 1

interest = balance * RATE / 100

balance = balance + interest

A while statement is an example of a loop. If you draw a flowchart, the flow of execution loops
again to the point where the condition is tested.

Here's an
example of a
while loop
that counts from 1 to 5:
count = 1
while count <= 5:
print(count)
count += 1
In this example, the loop continues to execute as long as count is less than or equal to 5. The loop
prints the value of count and then increments it by 1 in each iteration. When count becomes 6, the
condition becomes false, and the loop terminates.

Example:
Here is an interesting example of a while loop that simulates a simple guessing game where the user
needs to guess a random number:
import random
# Generate a random number between 1 and 100
secret_number = random.randint(1, 100)

# Initialize variables
guess = None
attempts = 0

print("Welcome to the Guess the Number Game!")


print("I'm thinking of a number between 1 and 100.")

while guess != secret_number:


guess = int(input("Take a guess: "))
attempts += 1

if guess < secret_number:


print("Try a higher number.")
elif guess > secret_number:
print("Try a lower number.")
else:
print(f"Congratulations! You've guessed the number {secret_number} in
{attempts} attempts!")

print("Game over. Thanks for playing!")

In this example:

1. A random number between 1 and 100 is generated, which the user needs to guess.
2. The program then enters a while loop that continues until the user correctly guesses the
secret number.
3. Inside the loop, the user is prompted to input their guess, and the program provides
feedback about whether the guess is too high or too low.
4. When the user guesses the correct number, the loop terminates, and the program displays
a congratulatory message along with the number of attempts it took.

This example provides an interactive and fun game where the user can play a guessing game
with the computer, demonstrating how while loops can be used to create engaging and
interactive programs.

You might also like