Course Content
Python Indentation, Comments and Variables
0/2
Object Oriented Programming in Python
0/1
Exception Handling in Python
0/1
Sending emails with Python
0/1
Unit test in python programming
0/1
Python programming (zero to advance!!!)
About Lesson

A `while` loop in Python is used to execute a block of code repeatedly as long as a specified condition is true. The loop continues iterating until the condition evaluates to false. The syntax of a `while` loop in Python is as follows:

“`python
while condition:
      # Execute this block of code as long as the condition is true
      # Indentation is crucial in Python
      # Code here
“`

Here’s a breakdown of the components:
– `condition`: This is the expression that is evaluated before each iteration of the loop. If the condition evaluates to `True`, the loop continues; otherwise, it terminates.

The `while` loop continues executing the block of code as long as the condition remains true. If the condition becomes false at any point during the execution, the loop terminates, and control passes to the next statement after the loop.

Here are a few examples illustrating the use of `while` loops in Python:

### Example 1: Counting from 1 to 5

“`python
num = 1
while num <= 5:
    print(num)
    num += 1
“`
Output:
“`
1
2
3
4
5
“`

### Example 2: Summing Numbers Until a Threshold

“`python
total = 0
num = 1
while total < 10:
     total += num
     num += 1
     print(“Sum of numbers until the total exceeds 10:”, total)
“`
Output:
“`
Sum of numbers until the total exceeds 10: 10
“`

### Example 3: User Input Validation

“`python
password = input(“Enter your password: “)
while len(password) < 8:
      print(“Password must be at least 8 characters long.”)
      password = input(“Enter your password again: “)
      print(“Password set successfully!”)
“`

In this example, the loop continues prompting the user to enter a password until the length of the password is at least 8 characters.

`while` loops are useful for situations where the number of iterations is not known beforehand and depends on some condition. However, be cautious to avoid infinite loops by ensuring that the condition eventually becomes false during execution.

Join the conversation