While Loop
Enter the realm of while loops, where control and patience are key.
` ˙⋆˖⁺‧₊☽◯☾₊‧⁺˖⋆˙ `
What is a While Loop?
A while loop repeatedly executes a block of code as long as a specified condition is True. The condition is evaluated before each iteration, and if it evaluates to True, the code inside the loop is executed. If it evaluates to False, the loop stops.
#Example: Basic while loop
counter = 0
while counter < 5:
print("Counter is at:", counter)
counter += 1
In this example, the while loop continues to execute as long as the counter is less than 5. The counter is incremented by 1 in each iteration until the condition becomes False.
Infinite Loops
If the condition in a while loop never becomes False, the loop will continue indefinitely. This is called an infinite loop. Be cautious when writing while loops to ensure the condition will eventually be met.
#Example: Infinite loop
while True:
print("This loop will run forever!")
In this example, the condition True always evaluates to True, causing the loop to run indefinitely ().
Breaking Out of a While Loop
You can use the break statement to exit a while loop prematurely. This is useful when you want to stop the loop based on a specific condition that is checked within the loop.
#Example: Using break to exit a loop
counter = 0
while True:
print("Counter is at:", counter)
counter += 1
if counter >= 5:
break
In this example, the loop runs indefinitely until the if condition counter >= 5 is met, at which point the break statement exits the loop.
Continue Statement
The continue statement is used to skip the rest of the code inside the loop for the current iteration and move to the next iteration.
#Example: Using continue in a loop
counter = 0
while counter < 10:
counter += 1
if counter % 2 == 0:
continue
print("Counter is at:", counter)
In this example, the continue statement skips the even numbers, only printing the odd values of the counter.
Practical Application
In the Chamber of Continuity, you will learn to use while loops. These spells allow you to repeat actions until a specific condition is met.
⋆˖⁺‧₊ Write the while loop for the time-travel spell from start_year to finish_year, that prints the past years ₊‧⁺˖⋆
Sample Output:
You are at: 1997
You are at: 1998
You are at: 1999
You are at: 2000
You are at: 2001
The Finish!