The Python While Loop đ repeatedly executes a block of statements  until a specified condition :thinking: becomes false. Once the condition becomes false, the first line after the Loop executes.
A while loop is a type of indefinite iteration . The while loop continues looping  as long as the condition remains true. When the condition becomes false, the Loop terminates and the first statement after executing the loop body.
"A while loop in Python is a control flow statement that allows a block of code to be executed repeatedly based on a given Boolean condition. In other words, the while loop will keep iterating and running the code block inside of it until the specified condition evaluates to False.â
while condition:
statements
A while loop in Python continually executes a code block if a specified condition is true. The Loop will run the code block repeatedly until the condition becomes false. Once the condition is false, the program exits the while loop and continues.
The condition for the Loop can be any expression that evaluates to true or false. True is any non-zero value. The Loop can also be terminated early using the break statement. While loops are a helpful control structure that allows a program to execute a set of statements multiple times. They run the code block within the Loop repeatedly until the defined condition is no longer met.
# Initialize counter
counter = 0
# While loop
while counter < 10:
print(counter)
# Increment counter
counter += 1
This code is an example of Python while Loop. The code initializes a counter variable to 0, then prints the counter value and increments the counter by 1 until the counter is no longer less than 10. The output of this code will be a list of numbers from 0 to 9.
Let's further discuss while Loop with else. Let's check the syntax. A while loop with else executes a block of code as long as a given condition is true. Once the condition becomes false, the else block of code is executed. The else block of code is executed only if the condition is false. This is useful for ensuring that certain code is executed at least once or after the while loop ends.
while <condition>:
<code to execute>
else:
<code to execute>
Example:
i = 0
while (i <= 100 and i % 7 != 0):
i += 1
else:
if (i % 7 == 0):
print("The first number divisible by 7 is", i)
else:
print("No number is divisible by 7")
This code uses a while loop with an else statement to find the first number divisible by 7 between 0 and 100. The while loop checks if the value of i is less than or equal to 100 and is not divisible by 7, and if it is not, then it increments the value of i by 1. The else statement checks if the value of i is divisible by 7; if it is, then it prints the value of i. If the while loop fails to find any number divisible by 7, then the else statement prints that no number is divisible by 7.
while condition:
statement
Example:
i=0
while i < 5:
print(i)
i += 1
This while loop will execute the print(i) statement repeatedly if the condition i < 5 evaluates to True. On each iteration of the Loop, the value of i is incremented by 1 using the i += 1 statement. The Loop will continue printing the value of i and incrementing it until i reach the value of 5. At this point, the condition i < 5 will become False, and the Loop will exit, proceeding to the first statement after the while loop. In summary, this while loop will print the numbers 0 through 4, and then the Loop will terminate.
The infinite while loop in Python continuously executes the code inside the Loop until the user stops it. This Loop runs endlessly unless the user explicitly ends the Loop or an error occurs. The Loop can perform tasks that need constant looping, like checking for user input or monitoring a system.
Example:
while True:
print("Data scientists are like artists, except instead of paint and canvas, they use data and algorithms to create a masterpiece.")
An infinite while loop continually executes in Python until a specified condition is met. For example, the Loop below will print "Hello World" repeatedly until the Loop is manually stopped. This Loop is useful when code needs to run until certain criteria are satisfied, such as continually accepting user input.
AÂ sentinel-controlled loop runs until it encounters a specific value, known as the sentinel value, which signals the loop to terminate. This is particularly useful when the number of iterations is not known in advance.
The while loop is particularly useful when you want to keep prompting a user until they provide valid input. This is a common use case for interactive programs.
# Initialize the sum and count
total = 0
count = 0
# Get the first input from the user
number = int(input("Enter a number (-1 to stop): "))
# Sentinel-controlled while loop
while number != -1:
total += number
count += 1
# Prompt the user to enter another number
number = int(input("Enter another number (-1 to stop): "))
# Display the result
if count != 0:
print("Total sum:", total)
print("Average:", total / count)
else:
print("No numbers were entered.")
# Output (Sample Run):
Enter a number (-1 to stop): 10
Enter another number (-1 to stop): 20
Enter another number (-1 to stop): 30
Enter another number (-1 to stop): -1
Total sum: 60
Average: 20.0
In this case, the loop continues until the sentinel value -1 is entered, signaling the end of input.
You can use Boolean values directly as conditions for while loops, allowing them to run based on logical True or False states.
Example:
keep_running = True
while keep_running:
user_input = input("Type 'exit' to stop: ").lower()
if user_input == 'exit':
keep_running = False
else:
print("You typed:", user_input)
print("Loop has ended.")
In this example, the loop continues as long as keep_running is True. When the user inputs "exit," the keep_running variable is set to False, causing the loop to terminate.
Loop control statements alter the normal flow of execution. When execution exits a scope, all automatically created objects within that scope are destroyed.
You can control the flow of while loops using break, continue, and else statements.
The break statement is used to exit a loop prematurely, even if the loop's condition is still True.
number = 1
while number <= 10:
print("Number:", number)
if number == 5:
print("Breaking the loop as number reached 5")
break
number += 1
# Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Breaking the loop as number reached 5
The continue statement skips the remaining code inside the loop for the current iteration and moves on to the next iteration.
number = 0
while number < 5:
number += 1
if number == 3:
print("Skipping number 3")
continue
print("Number:", number)
# Output:
Number: 1
Number: 2
Skipping number 3
Number: 4
Number: 5
The else clause can be attached to a while loop and executes when the loop condition becomes False.
number = 1
while number <= 3:
print("Number:", number)
number += 1
else:
print("Loop ended. Number is now greater than 3.")
# Output:
Number: 1
Number: 2
Number: 3
Loop ended. Number is now greater than 3.
You can also use while loops to iterate through the elements of a list. This can be useful when you want to perform operations on list items based on certain conditions or to process the list dynamically.
Hereâs an example that uses a while loop to print each element in a list until all elements have been processed.
# Initialize a list of fruits
fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry']
# Initialize the index
index = 0
# While loop to iterate through the list
while index < len(fruits):
print("Fruit:", fruits[index])
index += 1
# Output:
Fruit: apple
Fruit: banana
Fruit: cherry
Fruit: date
Fruit: elderberry
In this example, the loop continues until index is equal to the length of the list, allowing you to access each fruit by its index.
You can also modify elements in a list while iterating through it using a while loop.
# Initialize a list of numbers
numbers = [1, 2, 3, 4, 5]
# Initialize the index
index = 0
# While loop to double each number in the list
while index < len(numbers):
numbers[index] *= 2
index += 1
print("Doubled numbers:", numbers)
# Output:
Doubled numbers: [2, 4, 6, 8, 10]
In this example, each number in the list is doubled as the loop iterates through the list.
This lesson provides an overview of Python while Loop, which repeatedly executes a code block until a specified condition becomes false. The lesson covers the syntax đđ of the while loop, how it works, and provides examples đ of its use, including while loops with else statements đ¤, single statement while loops, and infinite while loops đ.
Answer: C. To execute a block of code until the condition is false.
Answer: A. By typing the keyword âwhileâ.
Answer: A. When the condition is false.
Loading...
a. [1, 4, 9]Â
b. [1, 2, 3]Â
c. [2, 4, 6] d. [1, 3, 5]
Answer: A. [1, 4, 9]
Top Tutorials
Related Articles