# The while loop in Python is used to repeat a block of code as long as a condition is True.
# It’s great when you don’t know ahead of time how many times you need to repeat something.
# 4 steps
i = 1 # initialization
while i <= 7: # condition check
print(i, end = " ") # body of the loop; end is for not adding a new line
i += 1 # incrementation
1 2 3 4 5 6 7
# decreasing while loop
i = 7
while i > 0:
print(i, end = " ")
i -= 1
7 6 5 4 3 2 1
i = 1
while i < 11:
if i == 10: # not to add -- after 10
print(i)
else:
print(i, end = "--")
i += 1
1--2--3--4--5--6--7--8--9--10
# Common Mistake: Infinite Loop
while True:
print("♾️") # If the condition never becomes False, the loop will run forever
# while with break
i = 1
while i <= 10:
print(i)
if i == 5:
break # exits the loop
i += 1
1 2 3 4 5
# while with else - while else suite
x = 1
while x < 4:
print(x)
x += 1
else:
print("Loop finished!")
1 2 3 Loop finished!
# continue in a while loop
i = 0
while i < 10:
i += 1
if i % 3 == 0:
continue # skip the iteration when i is a multiple of 3
print(i, end= " ")
1 2 4 5 7 8 10
# Using input() to control the loop
while True:
name = input("Enter your name (or type 'exit'): ")
if name == 'exit':
break
print(f"Hello, {name}!")
else:
print("Not executed") # when the break statement gets executed; this else is skipped
print("Out of loop")
Enter your name (or type 'exit'): Dhoni Hello, Dhoni! Enter your name (or type 'exit'): Raina Hello, Raina! Enter your name (or type 'exit'): exit Out of loop
# Simulating countdowns or timers
import time
count = 7
while count > 0:
print(f"Countdown: {count}")
time.sleep(1) # pauses for 1 second
count -= 1
print("Hip Hip Hurray!")
Countdown: 7 Countdown: 6 Countdown: 5 Countdown: 4 Countdown: 3 Countdown: 2 Countdown: 1 Hip Hip Hurray!
# Waiting for a condition to be met
password = ""
while password != "python123":
password = input("Enter password: ")
print("Access granted!")
Enter password: Python Enter password: 123 Enter password: Python 123 Enter password: python123 Access granted!
# Useful in games, simulations, or retry logic
secret = 7
guess = 0
while guess != secret:
guess = int(input("Guess the number: "))
print("You guessed it!")
Guess the number: 1 Guess the number: 5 Guess the number: 7 You guessed it!
# Number Guessing Game
import random
secret_number = random.randint(1, 10)
attempts = 0
max_attempts = 3
print("Welcome to the Number Guessing Game!")
print("Guess a number between 1 and 10.")
print(f"You have only {max_attempts} chances!")
while attempts < max_attempts:
guess = int(input("\nYour guess: "))
attempts += 1
if guess == secret_number:
print("🎉 Correct! You guessed the number.")
break
elif guess < secret_number:
print("Too low!")
else:
print("Too high!")
if attempts < max_attempts:
print(f"You have {max_attempts - attempts} tries left.")
else:
print(f"\n😢 Out of chances! The correct number was {secret_number}.")
Welcome to the Number Guessing Game! Guess a number between 1 and 10. You have only 3 chances! Your guess: 5 Too high! You have 2 tries left. Your guess: 3 Too low! You have 1 tries left. Your guess: 4 🎉 Correct! You guessed the number.
# Billing - Super Market
print("Express Counter at the Supermarket...")
name = input("Enter the name: ")
address = input("Enter the address: ")
ch = int(input("Are you sure that you have items less than or equal to 10? Type 1 for Yes or 2 for No: "))
if ch == 1:
ctr = 0
total_price = 0
item_id = 1
while ctr <= 10:
print(f"\nEnter the price of item {item_id}")
price = float(input("₹ "))
if price <= 0:
print("Invalid price. Please enter a valid price.")
continue # Skip to the next iteration without incrementing ctr
total_price += price
item_id += 1
ctr += 1 # Only increment ctr and item_id if the price is valid
print(f"Your bill so far for {ctr} items is ₹ {total_price}.")
choice = input("\nEnter 'q' to quit or press 'Enter' to continue..")
if choice == 'q':
break
print("\n----- BILL -----")
print(f"Customer Name: {name}")
print(f"Customer Address: {address}")
print(f"\nYou have purchased {ctr} item(s).")
print(f"Total Bill: ₹ {total_price:.2f}")
print("------------------")
else:
print("Please check the other counter.")
Express Counter at the Supermarket... Enter the name: Sakshi Enter the address: Ranchi Are you sure that you have items less than or equal to 10? Type 1 for Yes or 2 for No: 1 Enter the price of item 1 ₹ 100 Your bill so far for 1 items is ₹ 100.0. Enter 'q' to quit or press 'Enter' to continue.. Enter the price of item 2 ₹ 50 Your bill so far for 2 items is ₹ 150.0. Enter 'q' to quit or press 'Enter' to continue.. Enter the price of item 3 ₹ -25 Invalid price. Please enter a valid price. Enter the price of item 3 ₹ 25 Your bill so far for 3 items is ₹ 175.0. Enter 'q' to quit or press 'Enter' to continue.. Enter the price of item 4 ₹ 0 Invalid price. Please enter a valid price. Enter the price of item 4 ₹ 10 Your bill so far for 4 items is ₹ 185.0. Enter 'q' to quit or press 'Enter' to continue..q ----- BILL ----- Customer Name: Sakshi Customer Address: Ranchi You have purchased 4 item(s). Total Bill: ₹ 185.00 ------------------