Python Crash Course for Beginners | Mastering Python ‘while’ Loop

Python Crash Course for Beginners | Mastering Python ‘while’ Loop

 

Iteration is a core concept in programming, allowing developers to execute a block of code multiple times. While the Python for loop is an excellent tool for iterating over a sequence, the Python while loop offers a different approach for controlling iteration based on a specific condition. In this article, we will delve into the Python while loop, providing coding examples and explanations to help you understand its functionality and usage.

Python while Loop Basics

The while loop in Python is used to execute a block of code repeatedly as long as a specified condition is true.

Syntax

The general syntax for the Python while loop is as follows:

while condition:
    # Code to execute while the condition is true

The ‘condition’ can be any expression that evaluates to a boolean value (True or False). If the condition is true, the code within the ‘while’ block is executed. After executing the block, the condition is checked again, and if it is still true, the block is executed once more. This process repeats until the condition becomes false.

Example 1: Simple while Loop

Let’s start with a simple example to understand the basic usage of the while loop in Python.

count = 0

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

In this example, the variable ‘count’ is initialized with the value 0. The while loop checks if ‘count’ is less than 5. Since the condition is true, the loop prints the value of ‘count’ and increments it by 1. The loop continues until ‘count’ is no longer less than 5. The output will be:

0
1
2
3
4

Python while Loop with else Block

Python allows you to use an optional else block with the while loop. The code within the else block is executed once the while loop has completed its iteration (when the condition becomes false). This can be useful for performing certain actions after the loop is finished.

Syntax

The general syntax for the Python while loop with an else block is as follows:

while condition:
    # Code to execute while the condition is true
else:
    # Code to execute after the while loop has completed its iteration

Example 2: while Loop with else Block

Here’s an example illustrating the use of the else block with a while loop:

count = 1

while count <= 3:
    print(f"Count: {count}")
    count += 1
else:
    print("The loop has completed its iteration.")

In this example, the variable ‘count’ is initialized with the value 1. The while loop checks if ‘count’ is less than or equal to 3. The loop prints the value of ‘count’ and increments it by 1. Once ‘count’ is no longer less than or equal to 3, the code within the else block is executed, and the program prints “The loop has completed its iteration.” The output will be:

Count: 1
Count: 2
Count: 3
The loop has completed its iteration.

Using break and continue in a while Loop

Python provides two useful statements for controlling the flow of a while loop: ‘break’ and ‘continue’. The ‘break’ statement allows you to exit the loop prematurely, while the ‘continue’ statement allows you to skip the remaining code in the loop and proceed to the next iteration.

Example 3: Using break in a while Loop

Let’s look at an example that demonstrates the use of the ‘break’ statement in a while loop.

count = 0

while count < 10:
    count += 1
    if count == 5:
        break
    print(count)

In this example, the while loop checks if ‘count’ is less than 10. Inside the loop, we increment ‘count’ by 1. We use the ‘break’ statement to exit the loop when ‘count’ is equal to 5. The loop will print the value of ‘count’ as long as ‘count’ is not equal to 5. The output will be:

1
2
3
4

Example 4: Using continue in a while Loop

Now let’s examine an example that demonstrates the use of the ‘continue’ statement in a while loop.

count = 0

while count < 10:
    count += 1
    if count % 2 == 0:
        continue
    print(count)

In this example, the while loop checks if ‘count’ is less than 10. Inside the loop, we increment ‘count’ by 1. If ‘count’ is an even number (i.e., divisible by 2), the ‘continue’ statement is executed, skipping the remaining code in the loop and proceeding to the next iteration. The loop will print the value of ‘count’ only if it is an odd number. The output will be:

1
3
5
7
9

Summary

The Python while loop is a versatile tool for controlling the flow of a program through iteration based on a specific condition. By understanding and mastering the basic while loop, while loop with else block, and the use of break and continue statements, you can create more dynamic and responsive applications.

In this article, we explored the Python while loop with examples and explanations to help you comprehend its functionality and usage. With practice, you’ll be able to apply these concepts in your own projects, enhancing your ability to work with conditions and perform repeated tasks.

 

Personal Career & Learning Guide for Data Analyst, Data Engineer and Data Scientist

Applied Machine Learning & Data Science Projects and Coding Recipes for Beginners

A list of FREE programming examples together with eTutorials & eBooks @ SETScholars

95% Discount on “Projects & Recipes, tutorials, ebooks”

Projects and Coding Recipes, eTutorials and eBooks: The best All-in-One resources for Data Analyst, Data Scientist, Machine Learning Engineer and Software Developer

Topics included: Classification, Clustering, Regression, Forecasting, Algorithms, Data Structures, Data Analytics & Data Science, Deep Learning, Machine Learning, Programming Languages and Software Tools & Packages.
(Discount is valid for limited time only)

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.

Learn by Coding: Tutorials on Applied Machine Learning and Data Science for Beginners

Please do not waste your valuable time by watching videos, rather use end-to-end (Python and R) recipes from Professional Data Scientists to practice coding, and land the most demandable jobs in the fields of Predictive analytics & AI (Machine Learning and Data Science).

The objective is to guide the developers & analysts to “Learn how to Code” for Applied AI using end-to-end coding solutions, and unlock the world of opportunities!