Bytes

While Loop in Python

Last Updated: 29th September, 2024

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.

While loop in Python

What is While Loop in Python?

"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 Loop Syntax in Python

while condition:
    statements
  • A while loop in Python repeats a code block while an expression is true.
  • The while keyword starts the Loop.
  • An expression follows that evaluates to true or false.
  • The indented statement after the expression is the loop body.
  • The body repeats while the expression is true.
  • The expression checks the loop condition.
  • The body contains the code that runs on each iteration of the Loop.

Working of While Loop:

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.

Example of Python While Loop

# 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.

While Loop with Else

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.

Syntax

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.

Single Statement While Loop in Python

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

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.

Sentinel-Controlled while Loop

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.

Example:  While Loop with User Input Validation

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.

While Loop with Boolean Values

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.

Control Statements in Python with Examples

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.

1. Python While Loop with a Break Statement

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

2. Python While Loop with a Continue Statement

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

3. Python While Loop with an Else Statement

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.

While Loop with Python Lists

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.

Example: Iterating Through a List

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.

Example: Modifying List Elements with a While Loop

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.

Common Pitfalls with While Loops

  1. Infinite Loops: Forgetting to update the loop variable can result in an infinite loop.
  2. Incorrect Use of continue: If used improperly, continue can cause unintended skips in loop execution.

Use Cases for While Loops

  • Data Validation: Prompting a user for input until a valid response is provided.
  • Game Loops: Maintaining game logic that continues running until an exit condition is met.
  • Monitoring Processes: Checking the status of a background process until it completes.

Conclusion

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 🔁.

Key Takeaways

  1. A while loop executes a code block repeatedly until a specified condition is met.
  2. The Loop continues until the condition becomes false.
  3. While loops can iterate over lists, strings, collections, and more.
  4. If the condition is initially false, the loop body will not execute.
  5. Using a proper condition in the while loop is essential to avoid an infinite loop.

Quiz

  1. What is the purpose of a while loop? 
    1. To iterate multiple times through a loop 
    2. To evaluate a condition before proceeding 
    3. To execute a block of code until the condition is false 
    4. To repeat a set number of times

Answer: C. To execute a block of code until the condition is false.

  1. How is a while loop entered in a program?
    1. By typing the keyword “while” 
    2. By calling the loop function 
    3. By setting a condition 
    4. By defining a loop variable

Answer: A. By typing the keyword “while”.

  1. When does a while loop stop executing?
    1. When the condition is false 
    2. When the condition is true 
    3. When a break statement is encountered 
    4. When the loop is exited

Answer: A. When the condition is false.

  1. What is the output of the following code?
Loading...

a. [1, 4, 9] 

b. [1, 2, 3] 

c. [2, 4, 6] d. [1, 3, 5]

Answer: A. [1, 4, 9]

Module 3: Loops and Iterations in PythonWhile Loop in Python

Top Tutorials

Related Articles

  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

Š 2024 AlmaBetter