while Loop in Python

A while loop in Python is a control flow structure that is used to execute a block of code repeatedly until some specified condition is evaluated as True. It continues to execute the code within the loop until the condition becomes False.

The basic syntax of a while loop in Python is as follows:

while condition:
    # Code to be executed repeatedly until the condition becomes false

Here's an explanation of how the while loop works in Python:

  • The while loop starts by evaluating the condition first. If the condition is initially False, the code inside the code block of the loop will not run at all.
  • If the condition is initially True, the code inside the code block is executed.
  • After the code inside the code block is executed, the loop condition is checked again. If the condition is still True, the code inside the code block is executed again. This continues until the condition becomes False.
  • The while loop is terminated, when the condition becomes False and the execution of program continues with the code after the while loop.

Examples:

Here's a simple example of a while loop in Python that counts from 1 to 10:

count = 1
while count <= 10:
    print(count)
    count += 1

In this example, the count variable is initialized to 1. The while loop checks if the count value is less than or equal to 10. If the condition is true, the code inside the code block prints the value of count and increments it by 1. The loop continues to execute until count becomes 11 (which is when the condition becomes False), and then the loop terminates.

The output of the above code is as follows:

1
2
3
4
5
6
7
8
9
10

Terminating the while Loop

In Python, you can use the break statement to terminate the loop before the looping through all items is complete.

Example:

fruits = ["grapes", "mango", "apple", "pineapple", "banana"]
count = 0
while count < len(fruits):
    #go to next loop if the current value of i is apple
    if(fruits[count] == "apple"):
        print("Current loop element is %s. Terminating the loop." % (fruits[count]))
        break
    print(fruits[count])
    count += 1
print("End of program")

In this example, we define a list called fruits containing five fruit names. We initialize a variable count to 0. This variable will be used as an index to access elements in the fruits list. The while loop is used to iterate through the elements of the fruits list. It continues looping as long as the count is less than the length of the fruits list (len(fruits)). Inside the loop, there is an if statement that checks if the current fruit (accessed by fruits[count]) is equal to "apple". If the current fruit is "apple", the code prints a message indicating that the loop is terminating because it encountered "apple" and then it breaks out of the loop using the break statement. If the current fruit is not "apple", it prints the name of the fruit, and then count is incremented by 1 to move to the next element in the list. The loop continues to iterate through the list until it encounters "apple" or until it reaches the end of the list. After the loop completes, it prints "End of program" to indicate that the program has finished.

Output:

grapes
mango
Current loop element is apple. Terminating the loop.
End of program

Skipping in a while Loop

In Python, you can use the continue statement to skip the current loop and continue with the next loop.

Example:

fruits = ["grapes", "mango", "apple", "pineapple", "banana"]
count = 0
while count < len(fruits):
    if(fruits[count] == "apple"):
        print("Skipping current element %s " %(fruits[count]))
        count += 1
        continue
    print(fruits[count])
    count += 1
print("End of program")

In this example, we define a list called fruits containing five fruit names. We initialize a variable count to 0. This variable will be used as an index to access elements in the fruits list. The while loop is used to iterate through the elements of the fruits list. It continues looping as long as the count is less than the length of the fruits list (len(fruits)). Inside the loop, there is an if statement that checks if the current fruit (accessed by fruits[count]) is equal to "apple". If the current fruit is "apple", the code prints a message indicating that it is skipping the current element ("apple") and increments the count by 1 using count += 1. Then, it uses the continue statement to skip the rest of the loop's current iteration and move to the next iteration of the loop. If the current fruit is not "apple", it prints the name of the fruit, and then count is incremented by 1 to move to the next element in the list. The loop continues to iterate through the list, but whenever it encounters "apple", it skips printing it and proceeds to the next fruit. After the loop completes, it prints "End of program" to signify the end of the program.

Output:

grapes
mango
Skipping current element apple
pineapple
banana
End of program