While loop in Python

What does the while loop in Python do? What is the syntax and how to use while loop? Those are the content we will approach in this Python lesson.

The loop used in programming to repeat a specific code, while also is one of them. In Python, while used to repeat a command block, the code when the test condition is true. while using in cases where we can not predict how many times to repeat.

The syntax of while in Python

 while điều_kiện_kiểm_tra: 
Khối lệnh của while

In the while loop, điều_kiện_kiểm_tra will be checked first. The loop command block is only loaded if the condition_folder is True. After a loop, điều_kiện_kiểm_tra will be checked again. This process will continue until điều_kiện_kiểm_tra is False. In Python any value other than 0 is True, None and 0 are interpreted as False. This feature of while can lead to the case that while may not run because the first iteration điều_kiện_kiểm_tra has False. Meanwhile, while 's block will be ignored and the code immediately after that will be executed.

While loop in Python Picture 1
While loop diagram in Python

Like if or for loop, while's block is also defined through indentation. The block starts with the first indent and ends with the first indented line immediately after the block.

Example 1:

 count = 0 
n = 0
while (count < 8):
print ('Số thứ', n,' là:', count)
n = n + 1
count = count + 1
print ("Hết rồi!")

With this code, we will gradually increase the count and print its value until this value is no longer smaller than 8. The result when running the above command we have:

 Số thứ 0 là: 0 
Số thứ 1 là: 1
Số thứ 2 là: 2
Số thứ 3 là: 3
Số thứ 4 là: 4
Số thứ 5 là: 5
Số thứ 6 là: 6
Số thứ 7 là: 7
Hết rồi!

Example 2: Use while to calculate the sum of the numbers

 n = int(input("Nhập n: ")) #Nhập số n tùy ý 
tong = 0 #khai báo và gán giá trị cho tong
i = 1 #khai báo và gán giá trị cho biến đếm i

while i <= n:
tong = tong + i
i = i+1 # cập nhật biến đếm

print("Tổng là", tong)

With the above block we have, enter a natural number n any and sum the numbers from 1 to n, then print the sum. The variable that stores the sum is tong, the count variable is i, until i is less than or equal to n, the loop continues and the tong keeps rising.

After running the command, we get the result:

 Nhập n: 11 
Tổng là 66

In the example above the variable count i needs to be incremented, this is very important, otherwise it will lead to an infinite loop. Many cases of this note have been forgotten.

Example 3: Infinite loop

Retrieving the above example, you just need to remove the line i = i + 1

 n = int(input("Nhập n: ")) #Nhập số n tùy ý 
tong = 0 #khai báo và gán giá trị cho tong
i = 1 #khai báo và gán giá trị cho biến đếm i

while i <= n:
tong = tong + i

print("Tổng là", tong)

When this runs the command we will get:

 Nhập n: 1 
Traceback (most recent call last):
File "C:/Users/TipsMake.com/Programs/Python/Python36-32/QTM.com", line 6, in
tong = tong + i
KeyboardInterrupt
2
3
4
5

When you enter a value of 1, you can see that no command is executed, press Enter> enter 2> Enter> enter 3 . to 5 still not see tong printed. This is a case of an infinite command. To get rid of the infinite loop, press Ctrl + C, and the message "Traceback ." will appear.

Combination while with else

Like the for loop, you can also combine else with while. In this case, the else block of statements will be executed when the condition of while is False.

Example 4: Illustrating the use of while combining with else

 dem = 0 
while dem < 3:
print("Đang ở trong vòng lặp while")
dem = dem + 1
else:
print("Đang ở trong else")

Here we use the variable dem to print the string "Being in the while loop" 3 times. By the fourth iteration, the condition of while becomes False, so the else's command part is executed. The result is:

 Đang ở trong vòng lặp while 
Đang ở trong vòng lặp while
Đang ở trong vòng lặp while
Đang ở trong else

Example 5: Count and print numbers smaller than 2

 n = 0 
while n < 2:
print(n,"nhỏ hơn 2")
n = n + 1
else:
print (n,"không nhỏ hơn 2")

The initial value of n is set to 0, incrementing the value of n and printing, repeating until n is not less than 2, if n is equal to or greater than 2, the end loop and else block will be executed. , the result is:

 0 là nhỏ hơn 2 
1 là nhỏ hơn 2
2 không nhỏ hơn 2

while on a line

If the while loop has only one command, it can be written on the same line as while this example:

Example 6: Infinite loop with while a command line

 flag = 1 while ( flag ): print ( 'Flag đã cho là True!")
Print ("Hẹn gặp lại!")

This is an infinite loop, remember Ctrl + C before you press F5 or Run, otherwise it will run from day to day =)).

After all, the while loop is not very complicated. In the next section we will look at the break command and continue in Python, so read it.

Next article: Break and continue commands in Python

Previous article: For in Python loop

3.5 ★ | 2 Vote

May be interested

  • For in Python loopPhoto of For in Python loop
    in this article, we will learn more about for for loop in python as well as its variations, how to use for to repeat a string of elements in python such as list, string or other iterative objects.
  • If, if ... else, if ... elif ... else commands in PythonPhoto of If, if ... else, if ... elif ... else commands in Python
    the if statement in python is one of the most common and easy-to-learn commands. apart from if there is if else, if elif else. let's explore the details and see examples of these if commands.
  • Learn the first Python programPhoto of Learn the first Python program
    in this article we will learn a simple python program to get a little more insight into python, before starting to learn about the main components of this programming language.
  • Python data type: string, number, list, tuple, set and dictionaryPhoto of Python data type: string, number, list, tuple, set and dictionary
    in this section, you'll learn how to use python as a computer, grasp python's data types and take the first step towards python programming.
  • How to install Python on Windows, macOS, LinuxPhoto of How to install Python on Windows, macOS, Linux
    to get started with python, you first need to install python on the computer you are using, be it windows, macos or linux. below is a guide to installing python on your computer, specific to each operating system.
  • What is Python? Why choose Python?Photo of What is Python?  Why choose Python?
    python is a powerful, high-level, object-oriented programming language, created by guido van rossum. python is easy to learn and emerging as one of the best introductory programming languages ​​for people who are first exposed to programming languages.