Python while Loop

0 0
Read Time:2 Minute, 9 Second

What is a while loop?

Imagine you have a task you need to do repeatedly until a certain condition is met. A while loop in Python automates this repetition. It continuously executes a block of code as long as a specific condition remains true.

How does it work?

  1. Initialization: You set up a variable that will control the loop’s execution.
  2. Condition: The loop checks if the condition involving the variable is true.
  3. Code Block: If the condition is true, the code within the loop runs.
  4. Update: After each execution, the variable is updated to move closer to the ending condition.
  5. Loop Back: The loop checks the condition again with the updated variable. This cycle continues until the condition becomes false.

Example – Printing numbers 1 to 5:

i = 1  # Initialize variable i
while i <= 5:  # Check if i is less than or equal to 5
  print(i)  # Print the current value of i
  i += 1  # Update i by adding 1

# Loop continues printing 1, 2, 3, 4, 5

Explanation:

  1. We start with i = 1 to keep track of the numbers.
  2. The while statement checks if i is less than or equal to 5 (i <= 5).
  3. If true, print(i) displays the current value of i.
  4. i += 1 increments i by 1, bringing it closer to the ending condition.
  5. The loop goes back to step 2 and repeats until i becomes 6 (no longer less than or equal to 5).

The break Statement

With the break statement we can stop the loop even if the while condition is true:

Example

Exit the loop when i is 3:

i = 1
while i < 6:
  print(i)
  if i == 3:
    break
  i += 1

"""
Output:
1
2
3
"""

The continue Statement

With the continue statement we can stop the current iteration, and continue with the next:

Example

Continue to the next iteration if i is 3:

i = 0
while i < 6:
  i += 1
  if i == 3:
    continue
  print(i)

"""
Output:
1
2
4
5
"""

The else Statement

With the else statement we can run a block of code once when the condition no longer is true:

Example

Print a message once the condition is false:

i = 1
while i < 6:
  print(i)
  i += 1
else:
  print("i is no longer less than 6")

"""
Output:
1
2
3
4
5
i is no longer less than 6
"""
Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %