Python while Loops
gocourse.in Maintenance

We'll be back soon

Our CDN (cdn.gocourse.in) is currently unreachable. Some images, JavaScript, or CSS files may not load properly.

Estimated downtime: ~30 minutes

Python while Loops

Kishore V


Python while Loops

Loops in Python

Loops allow you to execute a block of code repeatedly. Python provides two primary looping constructs:

  • while loop – repeats as long as a condition remains true
  • for loop – iterates over a sequence (like a list, range, or string)

This section focuses on the while loop.

The while Loop

A while loop runs a block of code as long as a specified condition evaluates to True.

Syntax:

while condition:
    # code to execute

Example: Counting Numbers

Count value: 0 Count value: 1 Count value: 2 Count value: 3 Count value: 4
  • The loop runs while count < 5
  • count += 1 is essential to avoid an infinite loop

Note: Always update the condition variable inside the loop.

Preparing the Loop Variable

Before a while loop starts, the variable used in the condition must be initialized.

Attempt number 1 Attempt number 2 Attempt number 3

Without initializing attempts, Python would raise an error.

The break Statement

The break statement terminates the loop immediately, even if the condition is still true.

Example: Stop When a Match Is Found

1 2 3 4 5 Number found, exiting loop
  • Loop stops as soon as number becomes 6
  • Remaining iterations are skipped

The continue Statement

The continue statement skips the current iteration and moves directly to the next one.

Example: Skip a Specific Value

Current value: 1 Current value: 2 Current value: 3 Current value: 5 Current value: 6 Current value: 7
  • When value is 4, printing is skipped
  • Loop continues normally afterward

The else Block in a while Loop

The else block executes once, when the loop condition becomes false naturally (not via break).

Example: Loop Completion Message

Step 1 Step 2 Step 3 All steps completed successfully
  • The else block runs after the loop finishes
  • Useful for success messages or cleanup tasks

Important Note About break

If a while loop is terminated using break, the else block will not execute.

1 2

Note: "Loop finished" is not printed because the loop exited early.

Common Use Cases of while Loops

  • Repeating tasks until user input is valid
  • Running background checks
  • Implementing retry mechanisms
  • Reading data until a condition is met

Our website uses cookies to enhance your experience. Learn More
Accept !