No Widget Added

Please add some widget in Offcanvs Sidebar

Shopping cart

shape
shape

Python While Loops

While loop in python

A while loop in Python repeatedly executes a block of code as long as a given condition is true. The condition is checked before the execution of the loop’s body, and if the condition evaluates to True, the body of the loop is executed. This process continues until the condition evaluates to False.

Here’s a simple example to illustrate how a while loop works:

Example: Printing Numbers from 1 to 5

# Initialize the starting number
number = 1

# Define the while loop condition
while number <= 5:
    print(number)  # Print the current number
    number += 1    # Increment the number by 1

Explanation:

  1. Initialization: The variable number is initialized to 1.
  2. Condition: The loop condition number <= 5 is checked. If the condition is True, the loop’s body executes.
  3. Body of the Loop: Inside the loop:
    • The current value of number is printed.
    • The variable number is incremented by 1 using number += 1.
  4. Reevaluation: After the body of the loop is executed, the condition is checked again. This process repeats until number exceeds 5, at which point the condition evaluates to False and the loop terminates.

Output:

1
2
3
4
5

The loop runs five times, printing the numbers from 1 to 5. When number becomes 6, the condition number <= 5 is False, so the loop stops

Leave A Comment

Your email address will not be published. Required fields are marked *