While Python What function does it have? Use loop while in Python how? Let's find out with Quantrimang.com!
Programming is currently one of the top sought-after and high-paying professions today. All because programming is an indispensable part of a country's scientific and technological development journey. Thanks to programming, many useful products and applications have been born.
Loop or loop is a useful and frequently used feature in all modern programming languages today. If you want to automate a specific repetitive task or prevent yourself from writing duplicate code in a program you're developing, using loops is the best choice.
A loop is a set of instructions that run repeatedly until a condition is met. In Python, you have two types of loops:
- for loop
- while loop
In this article, we will learn how to create a while function in Python and learn how it works.
What is a while loop in Python?
Basically, while
in Python is used to repeat a block of statements or code when a condition is true. You can use while in many situations, but it is often used when the user cannot predict how many times it will need to be repeated. Below are details on how to use Python when programming web and applications.
while dieu_kien:
Khối lệnh của while
In the while loop, dieu_kien
will be checked first, if it is Truethen the loop block will be executed. After one iteration, dieu_kien
will be rechecked and this iteration will only stop until the condition is False.
In Python any non-zero value is TrueNone and 0 are understood as False. This characteristic can lead to the case of while
may not run because of the first iteration dieu_kien
was False. Then, the command block of while
will be ignored and the code below the command block while
will be executed.
While loop diagram in Python
Like if or loop forcommand block of while
also identified through indentation. The block begins with the first indent and ends with the first unindented line immediately following the block.
For example: Print numbers smaller than 8 one at a time
#In và đếm các số từ 0 tới 8:
count = 1
n = 0
while (n
With this code, we will increase gradually count. count and print the value of n until n no longer less than 8. The result when running the above command is:
Số thứ 1 là: 0
Số thứ 2 là: 1
Số thứ 3 là: 2
Số thứ 4 là: 3
Số thứ 5 là: 4
Số thứ 6 là: 5
Số thứ 7 là: 6
Số thứ 8 là: 7
Hết rồi!
Note:
- Remember to increment the condition variable in
while
(in the example above is n), otherwise the loop will become an infinite loop – continuing to loop forever. - Loop
while
requires the variable in the condition to be a specified value, in the above example the iterative indexing variable is the variable nwe must set its initial value to 1.
Example: Calculate the sum of 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
With the above command block we have, enter any natural number n and calculate the sum of numbers from 1 to n, then print the sum. The total storage variable is tongthe counter variable is iuntil i is less than or equal to n, the loop continues and total continues to increase.
After running the command we have the result:
Nhập n: 11
Tổng là 66
In the above example the counter variable i needs to be incremented, this is very important, otherwise it will lead to an infinite loop. In many cases this note has been forgotten.
Example 3: Infinite loop
Taking the example above again, 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
When we run this command we will get:
Nhập n: 1
Traceback (most recent call last):
File "C:/Users/Quantrimang.com/Programs/Python/Python36-32/QTM.com", line 6, in
tong = tong + i
KeyboardInterrupt
2
3
4
5
When you enter the value 1, you will see that no further commands will be executed. Press Enter > enter 2 > Enter > enter 3… to 5 and still not see it. tong printed. This is a case of infinite order. To exit the infinite loop, press the key Ctrl + Cthen the message “Traceback…” as above.
Break statement in while
With command break
we can stop the loop even if the condition of while
To be True:
For example: Exit the loop when i equals 3:
i = 1
while i
The result of the above example is that i will be printed from number 1 to number 3. After printing number 3, an if statement will be encountered and the loop will stop (no further printing of numbers 4 and 5):
1
2
3
The continue statement in while
Command continue
in while
will cause the loop to skip the current iteration and continue running on the next iteration.
For example: Print the numbers 1 to 6 except number 3
i = 0
while i
In the first 2 loops i equals 1 and 2, the loop still runs the print command. Go to the next loop, matching the condition if
i equals 3 then the command will be run continue
=> skip that loop to run straight to the next loop after it (print numbers 4, 5, 6).
Output:
1
2
4
5
6
Combine while with else
Like loop for
you can also combine else
with while
. In this case, the command block of else
will be performed when the condition of while
To be False.
Example: Illustrate the use of while in combination with else
dem = 0
while dem
Here we use the variable dem to print the string “Being in a while loop” 3 times. On the 4th iteration, the condition of while
become Falseso the command part of else
is executed. The results are:
Đ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: Count and print numbers less than 2
n = 0
while n
We assign the initial value of n to 0, gradually increase the value of n and print, repeating until n is not less than 2. If n is equal to or greater than 2, the loop ends and the command block else
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 statement on one line
If loop while
There is only one command that can be written on the same line while
like this example:
Example: Infinite loop with while one line of code
flag = 1
while (flag): print ('Flag đã cho là True!")
Print ("Hẹn gặp lại!")
This is an infinite loop, remember the keystrokes Ctrl + C before you press F5 nice Runotherwise it will run from day to day =)).
Check your knowledge of while loop in Python
Summary of things to know about the while command in Python:
- Start the while loop using the while keyword.
- Then you add a condition that is a Boolean expression. A Boolean expression evaluates to true or false.
- The clause is followed by a colon (:).
- On the new line, you add one level of indentation. Many code editors will automatically do this for you. For example, when using Visual Studio Code with the Python extension, immediately after writing a colon and pressing Enter, it will automatically indent the code to the right.
- The code you want will be in the body of the while statement.
- The while condition evaluates to true, the code inside the while body will run. This section of code will continue to run until the condition is no longer met and evaluates to false.
Do while in Python can be confusing to beginners. However, once you understand the concept of loops, you will realize that the “while” before Python’s “loop” is just a conditional statement.
A conditional statement follows a while loop. It determines what happens in the loop. While the condition remains True, the expression in the loop is continuously executed.
In general, loops are used when you need to process each element in a list or array while programming. A while loop also continuously runs until a statement in that loop stops.
The while loop in Python has some limitations when dealing with an array collection. In fact, unlike for loops, while loops do not provide specificity in control statements. However, the while loop has its own applications, so understanding how to use it when programming is absolutely necessary.
Above are the things you need to know about do while in Python. Hope this article helps you know how to use this loop well.