Python while
Loop
The while
loop in Python is used to repeatedly execute a block of code as long as a given condition is True
. It’s ideal when you don’t know in advance how many times the loop should run.
Basic Syntax
while condition:
# Code block to execute repeatedly
condition
: A Boolean expression that evaluates toTrue
orFalse
.- The loop runs as long as the condition evaluates to
True
. It stops once the condition becomesFalse
.
Example: Simple Counter
counter = 1
while counter <= 5:
print("Count:", counter)
counter += 1 # Increment the counter
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Using a while
Loop with User Input
The while
loop is commonly used for tasks like validating user input or performing repetitive actions based on user commands.
Example: User Input Validation
number = int(input("Enter a positive number: "))
while number <= 0:
print("That's not a positive number. Try again!")
number = int(input("Enter a positive number: "))
print("You entered:", number)
while
with Break Condition
You can use the break
statement to exit a while
loop prematurely when a specific condition is met.
Example: Breaking a Loop
i = 1
while i <= 10:
if i == 5:
print("Breaking the loop at", i)
break
print(i)
i += 1
Output:
1
2
3
4
Breaking the loop at 5
Using continue
in a while
Loop
The continue
statement skips the rest of the code in the current iteration and moves to the next iteration.
Example: Skipping a Number
i = 0
while i < 10:
i += 1
if i == 5:
print("Skipping", i)
continue
print(i)
Output:
1
2
3
4
Skipping 5
6
7
8
9
10
while-else
in Python
The else
block in a while
loop runs only if the loop condition becomes False
naturally (i.e., without encountering a break
statement).
Example: Without break
n = 1
while n <= 3:
print("Inside loop, n =", n)
n += 1
else:
print("Loop ended naturally!")
Output:
Inside loop, n = 1
Inside loop, n = 2
Inside loop, n = 3
Loop ended naturally!
Example: With break
n = 1
while n <= 3:
print("Inside loop, n =", n)
if n == 2:
break
n += 1
else:
print("Loop ended naturally!") # This will not execute
Output:
Inside loop, n = 1
Inside loop, n = 2
Advanced Example: Password Checker
Here’s an example of combining a while
loop with else
for a simple password check program:
password = "pythonforall"
attempts = 3
while attempts > 0:
user_input = input("Enter the password: ")
if user_input == password:
print("Access granted!")
break
else:
attempts -= 1
print("Incorrect password. Attempts left:", attempts)
else:
print("Too many failed attempts. Access denied.")
Try It Yourself
Problem 1: Multiplication Table
Write a program using a while
loop to display the multiplication table of a given number.
Show Code
num = int(input("Enter a number: "))
i = 1
while i <= 10:
print(num, "x", i, "=", num * i)
i += 1
Problem 2: Sum of Digits
Write a program to calculate the sum of digits of a given number using a while
loop.
Show Code
number = int(input("Enter a number: "))
total = 0
while number > 0:
digit = number % 10
total += digit
number //= 10
print("Sum of digits:", total)
Problem 3: Number Guessing Game
Write a program where the user has to guess a randomly generated number. They get unlimited attempts, but the loop stops when they guess correctly.
Show Code
import random
target = random.randint(1, 100)
guess = 0
while guess != target:
guess = int(input("Guess the number (1-100): "))
if guess < target:
print("Too low!")
elif guess > target:
print("Too high!")
else:
print("Correct! The number was", target)
Key Takeaways
Feature | Description | Example |
---|---|---|
Basic while | Repeats a block of code while a condition is True . | while x > 0: |
while-else | Executes else if the loop ends naturally. | else: print("Done!") |
break | Exits the loop prematurely. | if x == 5: break |
continue | Skips the rest of the current iteration. | if x == 5: continue |