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

  • Loop in programming CLoop in programming C
    similar to other programming languages, c also provides us with many control structures and allows you to perform complex parts.
  • How to Fix Boot Loop Problems in WindowsHow to Fix Boot Loop Problems in Windows
    after starting your windows device, you may sometimes experience an infinite boot loop issue (also known as an 'infinite boot loop' error).
  • More than 100 Python exercises have solutions (sample code)More than 100 Python exercises have solutions (sample code)
    more than 100 python code examples are shared by guy zhiwehu on github, however, the solution of this series is written on the old python version. following tipsmake.com will be vietnameseized and edited to suit python 3.x to help you learn and practice python.
  • What is Loop mail?What is Loop mail?
    what is loop mail? to help you with this question, the following article will help you find out what loop mail is.
  • Bookmark 5 best Python programming learning websitesBookmark 5 best Python programming learning websites
    if you are a developer or you are studying and want to stick with this industry, learn python to add a highlight in your journey.
  • Manage files and folders in PythonManage files and folders in Python
    python also provides a variety of methods to handle various directory-related operations. in this article, we will learn about managing files and directories in python, namely creating folders, renaming folders, listing folders and working with them.
  • For ... loop in JavaScriptFor ... loop in JavaScript
    the for ... in loop is used to iterate over the properties of an object. when we haven't discussed the object yet, you may not feel comfortable with this loop. but once you understand how objects work in javascript, you will find this loop very useful.
  • Loop control in JavaScriptLoop control in JavaScript
    javascript provides high control to handle loop commands and switch commands. there may be a situation when you need to exit the loop without having to go to its endpoint. there may also be situations when you want to jump over a part of the code block and start the next loop.
  • Why Microsoft Loop Can't Compare to NotionWhy Microsoft Loop Can't Compare to Notion
    many people have been using notion for brainstorming for years, so it's interesting to see if loop can replace it as they move deeper into the microsoft ecosystem.
  • Multiple choice quiz about Python - Part 3Multiple choice quiz about Python - Part 3
    today's topic quantrimang wants to challenge you is about file and exception handling in python. let's try the following 15 questions!