Using while Loops in Python

2023

In this project, we will discuss two Python code snippets that demonstrate the usage of while loops to iterate over a range of numbers. We'll explain each step of the code and provide the final working code at the end.


Example 1: Incrementing Values with a while Loop

In this example, we will use a while loop to increment a variable from 0 to 5 and print the current value at each iteration.

a = 0
while a < 5:
    a = a + 1
    print(a)

In this code, we initialize the variable a to 0. The while loop runs as long as the value of a is less than 5. Inside the loop, we increment the value of a by 1 using the statement a = a + 1 and then print the current value of a using the print() function.

The loop continues executing until the condition a < 5 is no longer true. Therefore, the numbers 1, 2, 3, 4, and 5 are printed as output.

Example 2: Decrementing Values with a while Loop

In this example, we will use a while loop to decrement a variable from 6 to 1 and print the current value at each iteration.

a = 6
while a > 1:
    a = a - 1
    print(a)

In this code, we initialize the variable a to 6. The while loop runs as long as the value of a is greater than 1. Inside the loop, we decrement the value of a by 1 using the statement a = a - 1 and then print the current value of a using the print() function.

The loop continues executing until the condition a > 1 is no longer true. Therefore, the numbers 5, 4, 3, 2, and 1 are printed as output.


Final Code

Here's the complete Python code for both examples:

# Example 1: Incrementing Values with a while Loop
a = 0
while a < 5:
    a = a + 1
    print(a)

# Example 2: Decrementing Values with a while Loop
a = 6
while a > 1:
    a = a - 1
    print(a)

That's it! You now have Python code snippets that demonstrate the usage of while loops to iterate over a range of numbers. Feel free to modify the code or use it as a starting point for your own projects. Happy coding!

Back