Table of Contents
This guide covers for in python loop with practical context and easy-to-follow details. Use it to understand the subject and apply the information confidently.
In the previous section we learned quite a bit about the if statement in Python. Read this article to make sure you don't miss out on useful information about it.
Syntax for for in Python
for bien_lap in chuoi_lap:Khối lệnh của for
In the above syntax, chuoi_lap is the string to repeat, bien_lap is the variable that receives the value of each item inside chuoi_lap on each iteration. The loop will continue until it iterates to the last item in the string.
The for block is indented to distinguish the rest of the code.
Example 1:
#Lặp chữ cái trong TipsMake
for chu in 'tipsmake':
print('Chữ cái hiện tại:', chu)
#Lặp từ trong chuỗi
chuoi = ['bố','mẹ','em']
for tu in chuoi:
print('Anh yêu', tu)
We have the following output:
Chữ cái hiện tại: qChữ cái hiện tại: uChữ cái hiện tại: aChữ cái hiện tại: nChữ cái hiện tại: tChữ cái hiện tại: rChữ cái hiện tại: iChữ cái hiện tại: mChữ cái hiện tại: aChữ cái hiện tại: nChữ cái hiện tại: gAnh yêu bốAnh yêu mẹAnh yêu em
Example 2:
# Tính tổng tất cả các số trong danh sách A# Danh sách A A = [1, 3, 5, 9, 11, 2, 6, 8, 10]# Biến để lưu trữ tổng các số là tong, gán giá trị ban đầu bằng 0 tong = 0# Vòng lặp for, a là biến lặp for a in A: tong = tong+a# Đầu ra: Tổng các số là 55 print("Tổng các số là", tong)
When running the above code, you will get the result:
The total number is 55
Function Range ()()
You can use the range () function to create a sequence of numbers. For example, range (100) will create a number range from 0 to 99 (100 numbers).
The range function (start number, end number, distance between two numbers) is used to create a custom number sequence. If you do not set a distance between two numbers, Python will understand that it is equal to 1 by default.
The range () function does not store all the values in memory but stores the start value, the end value and the distance between the two numbers resulting in the next number in the sequence.
In order for range () to output all values, you need to use the list () function like the example below:
#Lệnh 1 print(range(9)) #Lệnh 2print(list(range(9))) #Lệnh 3print(list(range(2, 5))) #Lệnh 4print(list(range(0, 15, 5)))
We will have the following output:
range(0, 9)[0, 1, 2, 3, 4, 5, 6, 7, 8][2, 3, 4][0, 5, 10]
Each line corresponds to Orders 1, 2, 3, 4 above.
The range () function can be used in conjunction with len () to loop through an array using index, as in the example below:
Example 3:
chuoi = ['bố','mẹ','em']for tu in range(len(chuoi)):print("Anh yêu",chuoi[tu])
We have the same output as example 1 above:
Anh yêu bốAnh yêu mẹAnh yêu em
Combine for with Else
In the previous lesson, you saw if. Else and if. Elif. Else. Else can not only combine with if, but in for loop can also be used.
In for, the else block of statements will be executed when the items in the string have been repeated.
Example 4:
B = [0, 2, 4, 5]for b in B:print(b)else:print("Đã hết số.")
Here, the for loop will print list B until the entries are gone. When the loop ends it executes else's block and prints. We have the result after running the code as follows:
0245Đã hết số.
The break command can be used to stop the for loop, and the else part will be ignored. In other words, the else part for for will run when no break is executed.
Example 5:
#Lặp dãy từ 0 đến 10 for num in range(0,10):# Repeat on factors of a number in the sequencefor i in range(2,num): #Xác định thừa số đầu tiên (phép chia có số dư bằng 0)if num%i == 0:j=num/i #Ước lượng thừa số thứ 2print ('%d bằng %d * %d' % (num,i,j))break #Dừng vòng for hiện tại, chuyển đến số tiếp theo trong vòng for đầu tiênelse: # Phần else trong vòng lặpprint (num, 'là số nguyên tố')
The above code repeats the numbers in the range from 0 to 10, with each number running the loop to check if it is a prime number, if it is, print the message and stop the test loop, switch to the next number within First iteration, if not a prime number, then execute another else block. Running the above code we have the following result:
0 là số nguyên tố1 là số nguyên tố2 là số nguyên tố3 là số nguyên tố4 bằng 2 * 25 là số nguyên tố6 bằng 2 * 37 là số nguyên tố8 bằng 2 * 49 bằng 3 * 3
Above is the most basic knowledge about for loop, in the next article, you will learn about while loop, do you still remember where it was in the introduction series of Python TipsMake. Com?
Next article: While loop in Python
Previous lesson: if, if. Else, if. Elif. Else in Python
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.