While loops repeat code as long as a condition is True. Unlike for loops (which run a specific number of times), while loops run until the condition becomes False. Be careful of infinite loops! Always ensure the condition will eventually become False.
# While loop examples
# Example 1: Basic counting
print("Example 1: Counting with while loop")
count = 1
while count <= 5:
print(f"Count: {count}")
count += 1 # IMPORTANT: Don't forget to change count!
# Example 2: User input validation
print("\nExample 2: Password checker")
password = ""
while password != "python123":
password = input("Enter password: ")
if password != "python123":
print("Wrong password! Try again.")
print("Access granted!")
# Example 3: Number guessing game
print("\nExample 3: Guessing game")
import random
secret_number = random.randint(1, 10)
guesses = 0
max_guesses = 3
print("I'm thinking of a number between 1 and 10.")
print(f"You have {max_guesses} guesses.")
guess = 0
while guess != secret_number and guesses < max_guesses:
guess = int(input("Your guess: "))
guesses += 1
if guess < secret_number:
print("Too low!")
elif guess > secret_number:
print("Too high!")
remaining = max_guesses - guesses
if guess != secret_number and remaining > 0:
print(f"Guesses remaining: {remaining}")
if guess == secret_number:
print(f"\nCongratulations! You guessed it in {guesses} tries!")
else:
print(f"\nGame over! The number was {secret_number}.")
# Example 4: ATM machine simulation
print("\nExample 4: ATM Simulation")
balance = 1000
while True:
print("\n1. Check Balance")
print("2. Withdraw")
print("3. Deposit")
print("4. Exit")
choice = input("Enter choice (1-4): ")
if choice == "1":
print(f"Your balance: ${balance}")
elif choice == "2":
amount = float(input("Amount to withdraw: $"))
if amount <= balance:
balance -= amount
print(f"Withdrew ${amount}. New balance: ${balance}")
else:
print("Insufficient funds!")
elif choice == "3":
amount = float(input("Amount to deposit: $"))
balance += amount
print(f"Deposited ${amount}. New balance: ${balance}")
elif choice == "4":
print("Thank you for banking with us!")
break
else:
print("Invalid choice!")
# Example 5: Controlled infinite loop
print("\nExample 5: Running total calculator")
total = 0
number = None
print("Enter numbers to add (enter 0 to stop):")
while number != 0:
number = float(input("Enter number: "))
total += number
print(f"\nTotal sum: {total}")