Python Tutorial– While Loop

Python Exercise Lists

In Python, a while loop is similar to an if conditional branch statement, that is, if the condition (expression) is true, the corresponding code block is executed. The difference is that while the condition is true, while will repeatedly execute that block of code.

The syntax of a while statement is as follows:

while conditional expression:
 Code block

The code block here refers to multiple lines of code with the same indentation format, but in the loop structure, it is also called the loop body.

The specific flow of the while statement execution is: first determine the value of the conditional expression. When the value is true, the statement in the code block is executed. After the execution is completed, go back to determine whether the value of the conditional expression is re-determined. True, if it is still true, continue to execute the code block again. This loop is repeated until the conditional expression is false, and then the loop is terminated.

The execution flow of the while loop structure is shown in the following figure.

For example, to print all the numbers from 1 to 100, you can use a while loop. The implementation code is as follows:

# Loop initialization conditions
num = 1
# When num is less than 100, the loop body will always be executed
while num <100:
    print ("num =", num)
    # Iteration statement
    num += 1
print ("End of loop!")
           

Running the program will find that the program only outputs 1 ~ 99, but not 100. This is because when looping to the value of num 100, the conditional expression is false (100 <100), and of course, the statements in the code block will not be executed again, so 100 will not be output.

Note that when using a while loop, you must ensure that the loop condition becomes false, otherwise the loop will become an endless loop. The so-called endless loop refers to the loop structure that cannot end the loop. For example, comment out the num + = 1 code in the while loop above, and then run the program. You will find that the Python interpreter always outputs "num = 1", never Will end (because num <100 is always True) unless we force close the interpreter.

Again, as long as the code in the body of the while loop is used, it must use the same indentation format (usually 4 spaces), otherwise the Python interpreter will report a SyntaxError. For example, if the num + = 1 statement in the above program is moved forward by one space and the program is executed again, the Python interpreter will report a SyntaxError.

In addition, while loops are often used to iterate through lists, tuples, and strings, because they all support getting the element at the specified position through the index of the index. For example, the following program demonstrates how to loop through a string variable using a while loop:

my_char = "www.freelearningpoints.com"
i = 0;
while i < len (my_char):
    print (my_char [i], end = "")
    i = i + 1
           

Else Usage in Python Loop

In Python, whether it is a while loop or a for loop, it can be followed immediately by an else block. Its role is to execute the code in the else block first when the loop condition is False.

Taking the while loop as an example, the following program demonstrates how to add an else block to the while loop:

website = "www.freelearningpoints.com"
i = 0
while i < len (website):
    print (website[i], end = "")
    i = i + 1
else:
    print ("\ nexecute else code block")
           

In the above program, when i == len (website) ends the loop (to be precise, before the loop ends), the Python interpreter executes the else code block after the while loop.

Some readers may think that the else code block has no specific effect, because the code after the while loop will be executed even if it is not in the else code block. For example, modify the above program to remove the else block:

                               


More Tutorials:

Python Installation - Linux (Ubuntu)
Python Installation - Mac OS
Integrated Development Environment - IDE
Python - Basic Variables
Python - Sequence Introduction
Python - Output Formatting
Python - Escape Character
Python - Type Conversion
Python - Numbers
Python – Arithmetic Operators
Python – Assignment Operators
Python – Comparison Operators
Python – Logical Operators
Python – Precedence and Associativity Operators
Python – Bytes Type and Usage
Python – Long & Raw Strings
Python – Concatenate Function
Python – Slice Function
Python – Length and Split Function
Python – Join and Count Function
Python – Find Function
Python – Index Function
Python – Alignment Function
Python – Startswith and Endswith Function
Python – String Case Conversion
Python – Remove Specified Character
Python – Encode and Decode Function
Python – dir and help Function
Python – Input Output Introduction
Python – Basic Operation
Python – Open Function
Python – Read Function
Python – Readline Function
Python – Write Function
Python – Close Function
Python – Seek and Tell Function
Python – Pickle Module
Python - File Input Module and Linecache Module
Python - Pathlib Module
Python - Pathlib Module
Python - os.path Module
Python - fnmatch Module
Python - Tuple Introduction
Python - List Introduction
Python - List Add Element
Python - List Delete Element
Python - List Modification Element
Python - List Find Element
Python - Dictionary Introduction
Python - Dictionary Basic Operation
Python - Dictionary Method Guide
Python - Set Collection
Python - Set Basic Operation
Python - Set Basic Method
Python - Frozenset Method
Python - If Condition I
Python - If Condition II
Python - While loop
Python - For loop
Python - Pass Statement
Python - Break Statement
Python - Zip Reverse Function
Python - Function Introduction
Python - Positional Parameters
Python - Key Arguments
Python - None and Return
Python - Variable Scope
Python - Local Function
Python - Closure Method
Python - Lamdba Expression


More Python Exercises:

Python String Exercises
Python List Exercises
Python Library Exercises
Python Sets Exercises
Python Array Exercises
Python Condition Statement Exercises