For enquiries call:

Phone

+1-469-442-0620

April flash sale-mobile

HomeBlogProgrammingPython While Loop Explained With Examples

Python While Loop Explained With Examples

Published
05th Sep, 2023
Views
view count loader
Read it in
12 Mins
In this article
    Python While Loop Explained With Examples

    In Python programming, loops are an essential construct for repetitive tasks. One of the loop types available in Python is the while loop. In this article, you will learn about the while loop in Python, understand its syntax, and see various examples to grasp its usage and applications.

    If you’re looking to explore the Python programming language, you can consider enrolling in the Python Programming training course offered by KnowledgeHut.

    What Is a While Loop in Python? 

    A while loop is a control flow statement that allows you to repeatedly execute a block of code as long as a specific condition is true. It is commonly used when you don't know the exact number of iterations in advance and need to keep executing the code until the condition becomes false.

    What Is the Syntax for a While Loop in Python?

    The syntax of while loop in Python is as follows:

    while condition:
    # code block to be executed

    The condition is a boolean expression that determines whether the loop should continue executing or not. As long as the condition evaluates to True, the code block inside the while loop will be executed repeatedly.

    The while loop in Python does not initialize or increase the value of the loop variable, as the for loop does. You must state it explicitly in the code, e.g., "i = i + 1". If you somehow miss this, the loop may lead to an infinite loop.

    How To Implement While Loops in Python? 

    To implement a while loop in Python, you need to follow these steps: 

    1. To start with, you need to declare a variable that will be used inside the loop as a counter or condition-checker. For example, you can declare an "i" variable and initialize it with 1 as: 

    i = 1

    2. Next, you need to determine the condition that will be checked before each iteration of the loop. For example, if you want the loop to execute five times, you can write a condition like "i <= 5". This condition indicates that the loop will execute as long as the "i" variable is less than or equal to 5.

    3. Next, you will need to write the loop body that will be executed if the loop condition evaluates to true. For this, first, you have to indent the code and then write the body. For example, if you want to write a print statement inside the loop body, you can write it as below:

    i = 1
    while i <= 5:
        print("KnowledgeHut by upGrad")

    4. Finally, you also need to write the terminating condition, else the loop will become an infinite loop. In this example, you just need to increment the value of the "i" variable. Hence, you can add the "i = i+1" statement in the body of the loop as below:

    i = 1
    while i <= 5:
        print("KnowledgeHut by upGrad")
        i = i + 1

    When you run the above code, the loop will execute multiple iterations based on the condition.

    • Iteration 1: i = 1; i <= 5 returns True; "KnowledgeHut by upGrad" is printed.
    • Iteration 2: i = 2; i <= 5 returns True; "KnowledgeHut by upGrad" is printed.
    • ...
    • Iteration 5: i = 5; i <= 5 returns True; "KnowledgeHut by upGrad" is printed.
    • Iteration 6: i = 6; i <= 5 returns False; Loop exits.

    Output:

    KnowledgeHut by upGrad
    KnowledgeHut by upGrad
    KnowledgeHut by upGrad
    KnowledgeHut by upGrad
    KnowledgeHut by upGrad

    Note that if the loop body consists of a single statement, you can write the while loop and the statement on a single line, separated by a colon:

    while condition: single_statement

    Infinite While Loop in Python 

    An infinite while loop is a loop that continues indefinitely because its condition never becomes false. When a condition never becomes false, the program keeps executing the loop body over and over again, and the loop never ends. Although it may seem undesirable, infinite loops can be useful in certain scenarios, such as running a server or waiting for user input.

    The following example demonstrates an infinite while loop in Python:

    i = 0
    while i >= 0:
        print("This is an infinite loop")

    In the above Python while loop example, the variable "i" is initialized with 0. The loop condition "i >= 0" will always evaluate as True because there is no change in the value of "i" inside the loop. Hence, the loop will continue to execute indefinitely until it is manually interrupted. 

    To prevent an infinite loop, you can include a statement inside the loop body to modify the loop variable "i" and eventually make the condition false, thereby exiting the loop.

    i = 0
    while i >= 0:
        print("This is not an infinite loop")
        i -= 1

    In the above code, the statement "i -= 1" decreases the value of "i" from 0 to -1. As a result, the loop condition "i >= 0" evaluates to False. Thus, the loop body is executed only once.

    To exit out of an infinite loop, you can also use the break statement, as you will see later.

    Flowchart for Python While Loops 

    The while loop in Python flowchart is as follows:

    The flowchart starts with the evaluation of the condition. If the condition is true, the loop body gets executed. Afterward, the condition is evaluated again. If it is still true, the loop continues, and the process repeats. If the condition becomes false, the loop terminates, and the program moves on to the next statement after the while loop.

    Do While Loop in Python 

    Do While loop is yet another type of control flow construct. In a do-while loop, the code executes at least once before the condition is checked. If the condition is true, the loop body will continue to execute, and the process repeats. If the condition is false, the loop terminates, and the program continues with the next line of code.

    The general syntax of a do-while loop is:

    do {
        // Code block to be executed
    } while (condition);

    Unlike some other programming languages, Python doesn’t have a built-in do-while loop. However, the same behavior can be achieved using a while loop by adding an initial check before the loop. Here's an example:

    # Initialize the variable
    i = 0
    # Execute the loop at least once
    while True:
        # Perform the desired action
        print("Executing the loop body")
        # Increment the variable
        i += 1
        # Check the condition
        if i >= 5:
            break  # Exit the loop
    # Continue with the rest of the code
    print("Loop completed")

    In this example, you start with an infinite while loop (while True) to ensure that the loop body is executed at least once. Inside the loop, you perform the desired action and increment the variable "i". Then, you check if the condition "i >= 5" evaluates to True. If it does, you use the break statement to exit the loop.

    Output:

    Executing the loop body
    Executing the loop body
    Executing the loop body
    Executing the loop body
    Executing the loop body
    Loop completed

    If you’re looking to enhance your programming knowledge, you can consider enrolling in the Programming training Course offered by KnowledgeHut. You can pick one language out of several and enhance your knowledge of it.

    While true in Python 

    The while True condition in Python helps you declare an infinite loop that runs until it encounters a break statement or is interrupted.  

    Here's an example of a while True loop in Python that keeps taking the user’s input printing the cumulative sum:

    sum = 0
    while True:
       number = int(input("Enter a number (or 0 to exit): "))
       if number == 0:
            break
       sum += number
    print("Cumulative sum:", sum)
    print("Exiting the program.")

    In the above while loop program in Python, you initialize a sum variable with 0, to hold the cumulative sum of numbers entered by the user. The while loop is set to run indefinitely as the condition True is always true. Inside the loop, the user is asked to enter a number. If the number entered is 0, the loop is terminated using the break statement. Otherwise, the entered number is added to the sum variable using the += shorthand operator and printed. This process continues as the loop keeps prompting the user for numbers and updating the cumulative sum until the user enters 0. At that point, the loop is exited, and the program displays the message "Exiting the program."

    Output:

    Enter a number (or 0 to exit): 1
    Cumulative sum: 1
    Enter a number (or 0 to exit): 5
    Cumulative sum: 6
    Enter a number (or 0 to exit): 8
    Cumulative sum: 14
    Enter a number (or 0 to exit): 0
    Exiting the program.

    Else With the While Loop in Python 

    You can also use the else clause with the while loop in Python. The code inside the else block is executed only when the while loop condition becomes false. 

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

    Output:

    1
    2
    3
    4
    5
    Loop completed successfully!

    In the above example, when the while loop condition evaluates to True, the value of "count" is printed. When "count" becomes 6, the while loop condition becomes False, and hence the else block is executed. 

    It is important to note that the else block is skipped if the loop is terminated by a break statement.

    count = 1
    while count <= 5:
        print(count)
        count += 1
        if count == 3:
            break
    else:
        print("Loop completed successfully!")

    Output:

    1
    2

    Python While Loop Interruptions 

    Sometimes, you don’t want the loop to execute completely. For those cases, Python provides you with two statements to interrupt the execution of the while loop - break and continue.

    Break Statements in While Loop

    The break statement is used to exit the loop prematurely. When the while loop encounters a break statement inside the loop body, the program immediately exits the loop, and the control flow continues with the next statement after the loop.

    count = 1
    while count <= 5:
        if count == 3:
            break
        print(count)
        count += 1
    print("Outside the loop!")

    Output:

    1
    2
    Outside the loop!

    In the above while loop example in Python, when the value of the "count" variable becomes 3, the loop terminates and executes the print statement outside the loop.

    Continue Statements in While Loop

    The continue statement is used to skip the rest of the code block inside the loop body and move on to the next iteration. When the loop encounters a continue statement, the program jumps back to the beginning of the loop and re-evaluates the condition.

    count = 0
    while count < 5:
        count += 1
        if count == 3:
            continue
        print(count)

    Output:

    1
    2
    4
    5

    In the above example, when the value of the "count" variable becomes 3, the loop skips the iteration and the program goes back to the beginning of the loop. Thus, 3 is skipped in the output of the program.

    Number Pattern Program in Python Using While Loop 

    You might have seen problems where you’re required to print number patterns such as below:

    These problems are nothing but Python while loop exercises. For example, the above pattern can be printed using the following code:

    n = 1
    while n <= 5:
        print(str(n) * n)
        n += 1

    In this code, you first initialize the variable n to 1. The while loop runs as long as n is less than or equal to 5. Inside the loop, you use the print statement to print the value of n repeated n times by multiplying it with the string representation of n. Then, you increment the value of n by 1 in each iteration.

    Similarly, you can also print the below shown right triangle star pattern using while loops:

    rows = 7
    current_row = 1
    while current_row <= rows:
        print("*" * current_row)
        current_row += 1

    In the above example, the loop prints rows of asterisks, starting from one asterisk in the first row and increasing by one asterisk in each subsequent row.

    Factorial Program in Python Using While Loop 

    Another common example that can be implemented with a while loop is finding a number's factorial. A non-negative integer's factorial is the sum of all positive integers from 1 to n.

    The following code shows how you can use the while loop in Python to calculate the factorial of a number:

    number = 5
    factorial = 1
    while number > 0:
        factorial *= number
        number -= 1
    print("Factorial:", factorial)

    Output:

    Factorial: 120

    In the above code, while the "number" variable is greater than 0, the "factorial" variable is continuously multiplied by the "number" variable. In each iteration, the number variable is also decremented by 1. 

    What Are the Common Uses of a While Loop in Python? 

    While loops are useful in various scenarios, including:

    1. Repeating a block of code until a specific condition is met.
    2. Iterating over elements in a collection until a specific element is found.
    3. Implementing interactive programs that wait for user input until a specific condition is satisfied.
    4. Processing data until a certain criterion or error condition is encountered.

    What Is the Difference Between a while Loop and a for Loop in Python? 

    The main difference between a for and while loop in Python is the way they iterate. A while loop continues executing as long as a condition remains true, whereas a for loop iterates over a predefined sequence or collection of elements.

    While loops are typically used when the number of iterations is not known in advance or when a condition needs to be continuously monitored. On the other hand, for loops are suitable for iterating over a known sequence, such as a list or a range of numbers.

    Wrapping Up 

    In this article, you explored the concept of a while loop in Python. You learned about the while loop syntax in Python, discussed different while loop in Python examples, and saw how to use the break and continue statements to control the loop's flow. While loops provide a powerful mechanism for repetitive tasks and offer flexibility when the exact number of iterations is uncertain. By understanding the while loop, you can enhance your ability to solve problems and write efficient Python code.

    Remember to practice writing and experimenting with while loops to strengthen your understanding and make the most out of this valuable construct in Python programming.

    If you want to dig deeper into the world of Python, you can enroll in KnowledgeHut’s Python Programming training course. This comprehensive course offers in-depth training and certification in Python programming, equipping you with the knowledge.

    Frequently Asked Questions (FAQs)

    1How do you use a while loop to create a countdown in Python?

    To create a countdown using a while loop in Python, you can start with an initial value and decrement it with each iteration of the while loop. The loop continues until the countdown reaches a specified end condition. For example, you can use a while loop with a variable "countdown" initialized to a certain value and decrease it by 1 in each iteration until it reaches 0.

    2How do you practice while loops in Python?

    To practice while loops in Python, you can start by understanding the syntax and basic concepts of while loops. Then, you can solve coding challenges or work on small projects that require repetitive execution based on a condition. Practice writing different while loop scenarios, such as input validation, data processing, or list iteration, to strengthen your understanding and proficiency with while loops.

    3What is the time limit of a while loop in Python?

    The time limit of a while loop in Python is determined by the condition specified in the loop. As long as the condition evaluates to true, the loop will continue executing. It is essential to ensure that the condition eventually becomes false to prevent an infinite loop, which can lead to the program freezing or crashing.

    4How do you break out of a while loop in Python?

    To break out of a while loop in Python, you can use the "break" statement. When a certain condition is met within the loop, you can include the "break" statement, which immediately terminates the loop and continues with the execution of the subsequent code outside the loop. This allows you to control the flow of the program and exit the loop prematurely if necessary.

    Profile

    Ashutosh Krishna

    Author

    Ashutosh is an Application Developer at Thoughtworks. Apart from his love for Backend Development and DevOps, he has a keen interest in writing technical blogs and articles. 

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Programming Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon