The Principle of 'while' Loops
Condition-Based Repetition: Unlike for loops that iterate over a sequence, while loops keep executing a block of code repeatedly as long as a certain condition remains true.
Check Before Entering: The condition is evaluated before each iteration of the loop. If it's false from the beginning, the loop's body will never run.
Basic Syntax
Python
condition:
# Code to be executed while the condition is True
Example: Countdown Timer
Python
counter = 5
while counter > 0:
print(counter)
counter -= 1 # Decrement the counter
print("Blastoff!")
How It Works
Initialization: You usually initialize a variable before the loop (like counter in the example).
Condition Check: The condition (counter > 0) is evaluated.
Loop Body: If the condition is True, the code within the loop runs.
Update: It's crucial to update something within the loop that affects the condition. Otherwise, your loop may run forever (an infinite loop)!
Back to the Top: The process repeats from step 2 until the condition becomes False.
Key Points
Indentation: Just like for loops, the indented code block defines the body of the while loop.
Infinite Loops: Be cautious! If the condition never becomes False, your program will get stuck in an infinite loop. Always ensure there's a way for the condition to change.
When to Use 'while' Loops
Unknown Iterations: Use while loops when you don't know beforehand how many times you need to loop (unlike for loops, which often work with sequences of known length).
User Input: while loops are great for handling repeated logic until the user enters a specific value to stop.
Situational conditions: Looping based on complex or changing conditions is often well-suited to while loops.
Example: Guessing Game
Python
import random
number = random.randint(1, 10)
guess = None
while guess != number:
guess = int(input("Guess a number between 1 and 10: "))
if guess > number:
print("Too high!")
elif guess < number:
print("Too low!")
print("You guessed it!")
Example 1: Factorial Calculation
Python
num = int(input("Enter a number: "))
factorial = 1
i = 1
while i <= num:
factorial *= i
i += 1
print(f"Factorial of {num} is: {factorial}")
Example 2: Menu-Driven Program
Python
choice = ''
while choice != 'Q': # Loop until user enters 'Q'
print("Menu:")
print("1. Add numbers")
print("2. Subtract numbers")
print("Q. Quit")
choice = input("Enter your choice: ").upper()
# ... (Add logic to handle choices 1 and 2 here)
Example 3: Verifying User Input
Python
valid_input = False
while not valid_input:
age = int(input("Enter your age: "))
if age > 0:
valid_input = True
else:
print("Invalid age. Please enter a positive number.")
Example 4: Simulating Rolling Dice
Python
import random
roll_again = 'y'
while roll_again == 'y':
print("Rolling the dice...")
die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
print(f"You rolled {die1} and {die2}")
roll_again = input("Roll again? (y/n): ").lower()
No comments:
Post a Comment
Note: only a member of this blog may post a comment.