The loop technique in Python
In this Python lesson, you'll learn how to control the execution of a loop using loop control statements like break and continue.
In this Python lesson, you'll learn how to control the execution of a loop using loop control statements like break and continue.
Python programming language provides 2 types of loops, for loops and while loops. Use these loops together with loop control statements like break
and continue
you can create different types of loops. We'll learn about these Python loops below.
Infinite loop in Python
It is possible to create infinite loops in Python using while. When the while
loop condition always True
, you get an infinite loop.
To get rid of an infinite loop in Python, use Ctrl + C.
Example of while using infinite loop:
The Python program below requires the user to enter a number and print 3 times the number of that number. The loop is infinite because there are no stopping conditions.
while True:
num = int(input("Nhập một số: "))
print("Gấp ba của",num,"là",3 * num)
The result when running the above code is:
Nhập một số: 3
Gấp ba của 3 là 9
Nhập một số: 5
Gấp ba của 5 là 15
Nhập một số: 7
Gấp ba của 7 là 21
Nhập một số: 9
Gấp ba của 9 là 27
Nhập một số: 10
Gấp ba của 10 là 30
Nhập một số:
Traceback (most recent call last):
You just enter Enter will continue to enter the new number and the program will run until you press Ctrl + C.
Python loop with the condition at the beginning
This is a regular repeat, without a break
statement. The while
loop condition will appear at the beginning and end of the loop when this condition is False
.
Python loop diagram provided at the beginning:
Example of a loop with the condition at the beginning:
# Try different numbers by assigning numbers to n
n = 15
# Use the following command if you want users to enter numbers
#n = int (input ("Enter number n:"))
# Initializing and counting variables i
tong = 0
i = 1
while i <= n:
tong = tong + i
i = i + 1 # update count
# Code by TipsMake.com
# in total
print ("Sum of numbers from 1 to", n, "is", tong)
The above program repeats the numbers until the given number n
, sums those numbers and prints them to the screen. After running the program, we get the result:
Tổng các số từ 1 đến 15 là 120
Python loop with conditions in between
This type of loop can be done using an infinite loop associated with the break
statement in the loop block.
Python loop diagram with conditions in between:
Example of a loop with the middle condition:
# Nhận đầu vào từ người dùng cho đến khi họ nhập một nguyên âm nguyenAm = "aeiouAEIOU" # vòng lặp vô hạn while True : m = input ( "Nhập một nguyên âm: " ) # Điều kiện ở giữa khối lệnh if m in nguyenAm : break print ( "Đây không phải là nguyên âm. Hãy thử lại!" ) # Code by TipsMake.com print ( "Chuẩn rồi, cảm ơn bạn!" )
The above program requires the user to enter a vowel, accompanied by a test command to force the user to enter until correct. As long as the user data entered is not vowel until then the loop continues.
After running the program, we get the following results:
Python loop with the condition at the end
This type of loop ensures that the block is executed at least once. It can be done using an infinite loop along with the break
command at the end. This is quite similar to the do.while
loop in C.
Python loop diagram provided at the end:
Example of Python loop with the end condition:
Below we will create a dice program, giving random results to users using a while
loop. The loop will continue until the user chooses to stop.
# Tung xúc xắc cho đến khi người dùng chọn thoát
import random while True : input ( "Nhấn Enter để tung xúc xắc" ) # nhận số mặt xúc xắc bất kỳ từ 1 đến 6 num = random . randint ( 1 , 6 ) print ( "Bạn tung được mặt" , num ) option = input ( "Bạn có muốn tung lại không?(y/n) " ) # điều kiện if option == 'n' : break
When running the program, we get the following result:
Nhấn Enter để tung xúc xắc
Bạn tung được mặt 1
Bạn có muốn tung lại không?(y/n) y
Nhấn Enter để tung xúc xắc
Bạn tung được mặt 4
Bạn có muốn tung lại không?(y/n) n
>>>
So you already know the basic iteration techniques in Python, don't forget to do Python exercises to practice your repetition techniques.
In the next lesson, you will learn about Python functions, syntax and how they work. Do not miss it!
Next lesson: Python functions
Previous post: Pass command in python
You should read it
Maybe you are interested
What is Large Action Model (LAM)? SpaceX's Crew Dragon spacecraft successfully assembled with the ISS station, completely automated Will NASA partner with Tesla to create the most unprecedented lunar exploration vehicle? SpaceX is about to blow up a tens of millions of dollars worth of boosters on the Atlantic Life is amazing: The process of transforming from a living cell to a perfect living organism in just 6 minutes NASA announces a stunning series of GIF images that capture the historic moments of the aerospace industry