Welcome back to another Python tutorial! Today, we'll delve into the world of while
loops. This essential control flow construct will help you write more dynamic and powerful code. By the end of this session, you'll be able to:
- Understand the role of while
loops in Python programming
- Implement various use cases of while
loops in your own projects
A while
loop allows a block of code to repeat as long as a specific condition is true. The general syntax looks like this:
while condition:
# Code to be executed while the condition is true
The condition
can be any expression that evaluates to a Boolean value (True or False). As long as the condition remains True, the code within the loop will continue to execute. Let's look at an example:
Suppose we want to write a simple program that calculates the factorial of a number. For this, we can use a while
loop and an accumulator variable to store the product:
n = 5
fact = 1
while n > 0:
fact *= n
n -= 1
print(fact) # Output: 120
In this example, we're using a while
loop to repeatedly multiply the accumulator variable (fact
) by the current value of n
. We keep reducing n
until it becomes zero, at which point the loop stops.
Let's consider another practical use case for while
loops: Guessing a secret number.
Here's a simple game where the computer randomly selects a number between 1 and 100, and the player has to guess it within 6 attempts. We'll use a while
loop to handle the guessing process:
import random
secret_number = random.randint(1, 100)
attempts = 0
guess = int(input("Guess a number between 1 and 100: "))
while attempts < 6:
if guess == secret_number:
print(f"Congratulations! You've guessed the secret number in {attempts + 1} attempts.")
break
elif guess > secret_number:
print("Too high! Try again.")
else:
print("Too low! Try again.")
guess = int(input("Guess a number between 1 and 100: "))
attempts += 1
if attempts == 6:
print(f"You've run out of attempts. The secret number was {secret_number}.")
In this example, we use a while
loop to repeatedly ask the player for their guess and provide feedback on whether it's too high or too low. If the player manages to guess the correct number before running out of attempts, the loop breaks using the break
statement.
What causes it:
while True:
print(answer) # Undeclared variable 'answer'
Error message:
UnboundLocalError: local variable 'answer' referenced before assignment
Solution:
answer = None
while True:
answer = input("Enter something: ")
print(answer)
Why it happens: The error occurs because the variable answer
is not defined before we try to access its value within the loop. To avoid this, make sure you initialize all variables before using them in a loop.
What causes it:
while "apples" > "oranges":
print("Apples are greater than oranges.") # Comparing strings as if they were numbers
Error message:
TypeError: '>=' not supported between instances of 'str' and 'str'
Solution:
while "apples" > "oranges" or "apples" < "oranges": # Use appropriate comparison operators for numbers or strings
print("This is an error message.")
Why it happens: The >
and <
operators compare numbers, not strings. To fix this error, use the correct comparison operators (either >
, <
, ==
, etc.) based on whether you're comparing numbers or strings.
break
statementwhile
loop allows you to repeat a block of code as long as a specific condition is truewhile
loop, the condition should be carefully chosen to ensure that the loop terminates at some pointwhile
loops in various scenarios to solidify your understanding of this important control flow constructAs always, keep coding, learning, and having fun! See you next time.