Table of Contents
This guide covers while loop in python with practical context and easy-to-follow details. Use it to understand the subject and apply the information confidently.
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.
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_traWill 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_traWill be checked again. This process will continue until?i?u_ki?n_ki?m_traIs 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_traHas False. Meanwhile, while 's block will be ignored and the code immediately after that will be executed.
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 = 0n = 0while (count < 8):print ('S? th?', n,' là:', count)n = n + 1count = count + 1print ("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à: 0S? th? 1 là: 1S? th? 2 là: 2S? th? 3 là: 3S? th? 4 là: 4S? th? 5 là: 5S? th? 6 là: 6S? th? 7 là: 7H?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 tongi = 1 #khai báo và gán giá tr? cho bi?n ??m iwhile i <= n:tong = tong + ii = i+1 # c?p nh?t bi?n ??mprint("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: 11T?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 tongi = 1 #khai báo và gán giá tr? cho bi?n ??m iwhile i <= n:tong = tong + iprint("T?ng là", tong)
When this runs the command we will get:
Nh?p n: 1Traceback (most recent call last):File "C:/Users/TipsMake.com/Programs/Python/Python36-32/QTM.com", line 6, intong = tong + iKeyboardInterrupt2345
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. " appears.
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 = 0while dem < 3:print("?ang ? trong vòng l?p while")dem = dem + 1else: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 = 0while n < 2:print(n,"nh? h?n 2")n = n + 1else: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 21 là nh? h?n 22 không nh? h?n 2
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
FAQ
What should I check before following these steps?
Confirm device and software compatibility, save important data, and make sure you have the required permissions, files, and account access.
Why might the process not work?
Common causes include outdated software, missing permissions, incompatible hardware, an unstable connection, or completing a step in the wrong order.
Can I undo the changes if necessary?
That depends on the tool or setting. Use built-in restore options when available, keep a backup, and record the original configuration first.
Reader Comments 0
Sign in with email or Google to join the discussion.