codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🐍

Python Programming

17 / 68 topics
14Python if...else Statement15Python Match Statement16Python for Loop & range()17Python while Loop18Python break, continue, and pass
Tutorials/Python Programming/Python while Loop
🐍Python Programming

Python while Loop

Updated 2026-05-15
15 min read

Python while Loop

In this tutorial, you'll learn how to use the while loop in Python. The while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. It's particularly useful when you don't know beforehand how many times the loop should run.

Introduction

The while loop is one of the fundamental constructs in programming, allowing for repeated execution of a block of code as long as a specified condition remains true. Unlike the for loop, which iterates over a sequence, the while loop continues to execute as long as its condition evaluates to True.

Core Content

While Loop Syntax

The basic syntax of a while loop in Python is:

Python
1while condition:
2 # code block to be executed
  • condition: A Boolean expression that is evaluated before each iteration. If the condition is True, the loop body executes; if it's False, the loop terminates.

Example 1: Basic While Loop

Let's create a simple program that counts down from 5 to 1 using a while loop.

countdown.py
1counter = 5
2while counter > 0:
3 print(counter)
4 counter -= 1
Output
5
4
3
2
1

In this example, the loop continues to execute as long as counter is greater than 0. After each iteration, the value of counter is decremented by 1.

Condition-Based Looping

The while loop is ideal for situations where you need to perform an action repeatedly until a certain condition changes. This makes it suitable for tasks like reading input from the user or processing data until a specific result is achieved.

Example 2: User Input Validation

Suppose we want to ask the user to enter a positive integer and keep prompting them until they provide valid input.

input_validation.py
1while True:
2 try:
3 number = int(input("Enter a positive integer: "))
4 if number > 0:
5 print(f"You entered {number}.")
6 break
7 else:
8 print("Please enter a positive integer.")
9 except ValueError:
10 print("Invalid input. Please enter a valid integer.")
Output
Enter a positive integer: -5
Please enter a positive integer.
Enter a positive integer: abc
Invalid input. Please enter a valid integer.
Enter a positive integer: 7
You entered 7.

In this example, the loop continues indefinitely until the user enters a positive integer. The break statement is used to exit the loop when valid input is received.

Infinite Loops

An infinite loop occurs when the condition of a while loop always evaluates to True, causing the loop to run indefinitely. While intentional infinite loops are sometimes useful (e.g., in server applications), they can also be accidental and lead to program crashes if not properly managed.

Example 3: Intentional Infinite Loop

Here's an example of an intentional infinite loop that simulates a simple server:

simple_server.py
1while True:
2 request = input("Server received a request. Process? (yes/no): ")
3 if request.lower() == 'no':
4 print("Shutting down the server.")
5 break
6 else:
7 print("Processing request...")
Output
Server received a request. Process? (yes/no): yes
Processing request...
Server received a request. Process? (yes/no): no
Shutting down the server.

In this example, the loop runs indefinitely until the user types 'no', at which point it breaks out of the loop.

Tip: To stop an infinite loop during execution, you can use keyboard interrupts (Ctrl+C in most environments).

While...Else Construct

The while loop can also include an optional else clause. The else block is executed when the loop condition becomes false, but not if the loop was terminated with a break statement.

Example 4: Using while...else

Let's modify the countdown example to use a while...else construct:

countdown_with_else.py
1counter = 5
2while counter > 0:
3 print(counter)
4 counter -= 1
5else:
6 print("Countdown finished!")
Output
5
4
3
2
1
Countdown finished!

In this example, the else block is executed after the loop completes normally. If the loop had been terminated with a break, the else block would not execute.

Loop Control with Counters

Using counters is a common technique in loops to keep track of iterations or conditions. This can be useful for tasks like limiting the number of attempts or processing a fixed number of items.

Example 5: Using Counters

Suppose we want to read a file line by line, but only process up to 10 lines:

process_lines.py
1with open('example.txt', 'r') as file:
2 count = 0
3 while count < 10 and (line := file.readline()):
4 print(line.strip())
5 count += 1
6 else:
7 if line == '':
8 print("Reached the end of the file.")
9 else:
10 print("Processed 10 lines.")
Output
Line 1
Line 2
...
Line 9
Line 10
Processed 10 lines.

In this example, the loop processes up to 10 lines from a file. The else block is executed if the loop completes normally (i.e., it processed 10 lines), or if it reaches the end of the file.

Practical Example

Let's create a complete program that simulates a simple guessing game. The computer randomly selects a number between 1 and 10, and the user has to guess it. The game continues until the user guesses correctly.

guessing_game.py
1import random
2
3def main():
4 secret_number = random.randint(1, 10)
5 attempts = 0
6 guessed_correctly = False
7
8 print("Welcome to the Guessing Game!")
9 while not guessed_correctly:
10 try:
11 guess = int(input("Guess a number between 1 and 10: "))
12 attempts += 1
13 if guess < secret_number:
14 print("Too low. Try again.")
15 elif guess > secret_number:
16 print("Too high. Try again.")
17 else:
18 guessed_correctly = True
19 except ValueError:
20 print("Invalid input. Please enter a valid integer.")
21
22 print(f"Congratulations! You guessed the number in {attempts} attempts.")
23
24if __name__ == "__main__":
25 main()
Output
Welcome to the Guessing Game!
Guess a number between 1 and 10: 5
Too low. Try again.
Guess a number between 1 and 10: 8
Too high. Try again.
Guess a number between 1 and 10: 7
Congratulations! You guessed the number in 3 attempts.

In this example, the while loop continues until the user guesses the correct number. The program keeps track of the number of attempts using a counter.

Summary

ConceptDescription
While Loop SyntaxExecutes code repeatedly while a condition is true.
Condition-BasedSuitable for tasks where the loop runs until a specific condition changes.
Infinite LoopsOccur when the loop condition always evaluates to True.
While...ElseThe else block executes if the loop completes normally, not with a break.
Loop ControlUsing counters helps manage iterations and conditions effectively.

What's Next?

In the next tutorial, you'll learn about controlling loops using break, continue, and pass statements. These statements provide more control over the flow of execution within loops, allowing for more complex logic and efficient code.

Stay tuned!


PreviousPython for Loop & range()Next Python break, continue, and pass

Recommended Gear

Python for Loop & range()Python break, continue, and pass