Python while
Loop – Complete Guide with Examples
The while
loop in Python is a fundamental control structure used to execute a block of code repeatedly as long as a given condition is True. It is particularly useful when the number of iterations is not known in advance.
๐ Syntax of while
Loop
while condition:
# code block to execute repeatedly
Note: The condition
is evaluated before each iteration. If it's True
, the code block runs. If it's False
, the loop ends.
1️⃣ Example: Basic Counter
counter = 1
while counter <= 5:
print("Counter is:", counter)
counter += 1
Output:
Counter is: 1
Counter is: 2
Counter is: 3
Counter is: 4
Counter is: 5
๐ง Explanation:
counter = 1
initializes the loop.counter <= 5
is the condition being checked.print()
displays the current count.counter += 1
increases the value by 1 each loop.
๐ Important: Always ensure that the condition eventually becomes false, or you’ll create an infinite loop!
2️⃣ Example: while
with User Input
password = ""
while password != "admin123":
password = input("Enter password: ")
print("Access granted!")
Output:
Enter password: guest
Enter password: pass123
Enter password: admin123
Access granted!
๐ง Explanation:
- The loop runs until the user types
admin123
. input()
reads user input during each iteration.
๐ก Note: This is a basic way to create login-style checks using while
loops.
3️⃣ Example: Skipping Iteration with continue
i = 0
while i < 7:
i += 1
if i == 4:
continue
print("Number:", i)
Output:
Number: 1
Number: 2
Number: 3
Number: 5
Number: 6
Number: 7
⚠️ Caution: When i == 4
, the continue
skips the print statement and moves to the next iteration.
4️⃣ Example: Stopping Loop Early with break
x = 10
while x > 0:
print("Value:", x)
if x == 6:
break
x -= 1
Output:
Value: 10
Value: 9
Value: 8
Value: 7
Value: 6
๐ง Explanation:
- When
x
becomes 6,break
stops the loop immediately.
๐ Note: Usebreak
to exit loops when a condition is met, even if the main condition is stillTrue
.
5️⃣ Example: Infinite Loop (⚠️ Use with Care)
while True:
user_input = input("Type 'exit' to stop: ")
if user_input == "exit":
break
print("You typed:", user_input)
Output: (runs until "exit" is typed)
Type 'exit' to stop: hello
You typed: hello
Type 'exit' to stop: test
You typed: test
Type 'exit' to stop: exit
⚠️ Caution:while True
creates an infinite loop unless you addbreak
to stop it.
๐ Common Use Cases of while
Loop
- Running code until user input is valid
- Creating loading screens or animations
- Game loops and server processes
- Polling or repeated checking of conditions
๐ ️ Example: Menu-Based Program
choice = ""
while choice != "3":
print("\nMenu:")
print("1. Say Hello")
print("2. Show Info")
print("3. Exit")
choice = input("Choose an option: ")
if choice == "1":
print("Hello there!")
elif choice == "2":
print("Python is powerful.")
elif choice == "3":
print("Exiting...")
else:
print("Invalid choice.")
✅ Tip: You can use while
loops to build simple interactive CLI apps like this.
๐ Summary
while
loop is used when the number of iterations is not known beforehand.- Use
break
to exit early from a loop. - Use
continue
to skip a particular iteration. - Infinite loops should always have a breaking condition to avoid freezing the program.
๐ฌ Practice Challenge: Write a program that asks users to guess a number between 1 and 10 using a while
loop. Give hints like "Too low!" or "Too high!" until the correct number is guessed.
๐งช Extra Practice Examples
Example: Print Even Numbers from 2 to 10
num = 2
while num <= 10:
print(num)
num += 2
Example: Sum of Numbers Until 0 is Entered
total = 0
while True:
n = int(input("Enter number (0 to stop): "))
if n == 0:
break
total += n
print("Total sum:", total)
๐ Practice Questions:
๐ Related Topics:
- ➤ Python Arithmetic Operators
- ➤ Basic String Functions
- ➤ Advanced String Functions
- ➤ Basic List Functions
- ➤ Advanced List Functions : Part-1
- ➤ Advanced List Functions : Part-2
- ➤ Basic Tuple Functions
- ➤ Advanced Tuple Functions
- ➤ Basic Dictionary Functions
- ➤ Advanced Dictionary Functions
- ➤ Conditional Statements : if-elif-else
- ➤ Python 'for' Loop
- ➤ Python 'while' Loop
- ➤ Difference between 'for' loop and 'while' loop
- ➤ Introducing Python Functions
๐ Bookmark this blog or follow for updates!
๐ Liked this post? Share it with friends or leave a comment below!