Python Diaries ….. Day 8

While loop

Nishitha Kalathil
4 min readSep 18, 2023

--

Welcome to Day 8 of Python Diaries! Today, we’re diving into the world of loops, specifically the “while” loop. While loops are used to repeatedly execute a block of code as long as a certain condition is true. They are powerful tools for automating repetitive tasks and controlling the flow of your programs.

What is a While Loop?

A while loop in Python allows you to execute a block of code repeatedly as long as a specified condition remains true. Unlike “for” loops that iterate over a sequence, while loops are controlled solely by a condition.

Syntax of a While Loop

Here’s the basic syntax of a while loop:

while condition:
# Code to be executed while the condition is true

The loop begins by evaluating the condition. If the condition is true, the code block inside the loop is executed. Afterward, the condition is checked again, and if it’s still true, the code block is executed again. This process continues until the condition becomes false.

Example: Counting from 1 to 5

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

In this example, we start with count equal to 1. The while loop continues as long as count is less than or equal to 5. With each iteration, count is incremented by 1, and the current value of count is printed. The loop terminates when count becomes greater than 5.

Infinite Loops

Be cautious when working with while loops. If the condition within the loop never becomes false, you’ll end up with an infinite loop, which can cause your program to hang or crash.

# This is an infinite loop
while True:
print("This will run forever!")

To avoid infinite loops, make sure your condition will eventually become false based on the logic within your code.

Using a While Loop to Control Program Execution

While loops are often used to control the execution of a program. For example, you can use a while loop to implement a menu system where the user can choose different options and continue until they decide to exit.

while True:
print("1. Option 1")
print("2. Option 2")
print("3. Exit")

choice = input("Enter your choice: ")

if choice == "1":
print("You selected Option 1.")
elif choice == "2":
print("You selected Option 2.")
elif choice == "3":
print("Exiting the program.")
break # Exit the loop
else:
print("Invalid choice. Try again.")

In this example, the program displays a menu and keeps running until the user selects option 3 to exit.

Using else with a While Loop

Similar to if statements, you can also have an else block associated with a while loop. The code in the else block is executed when the condition becomes false.

count = 1
while count <= 5:
print(count)
count += 1
else:
print("Loop completed successfully.")

In this example, after the while loop finishes executing (because count becomes greater than 5), the else block is executed, printing "Loop completed successfully."

Nested While Loops

Just like with condition statements, you can also have nested while loops. This means one while loop can be inside another while loop.

i = 1
while i <= 3:
j = 1
while j <= 3:
print(f"({i}, {j})")
j += 1
i += 1

This code will print combinations of i and j for i ranging from 1 to 3 and j ranging from 1 to 3.

Using break and continue

You can use break and continue statements within a while loop to control its behavior.

count = 1
while count <= 5:
if count == 3:
break # Exit the loop when count is 3
print(count)
count += 1

In this example, the loop will exit when count reaches 3 due to the break statement.

count = 1
while count <= 5:
if count == 3:
count += 1
continue # Skip the rest of the loop and continue with the next iteration
print(count)
count += 1

In this example, when count is 3, the continue statement is executed. This skips printing 3 and continues with the next iteration.

While loops are essential for creating dynamic and interactive programs. They allow you to automate repetitive tasks and control program flow based on conditions. Understanding how to use while loops effectively is a valuable skill in Python programming.

You can access the other topics in this tutorial series right here:

In Day 9, we’ll explore the concept of for loops. Keep up the great work! Happy coding!

--

--