For in Python loop
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.
In this article, we will learn more about the for loop in the Python programming language as well as its variants, how to use for to repeat a string of elements in Python such as list, string or other iterative objects. .
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 quantrimang
for chu in 'quantrimang':
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: q
Chữ cái hiện tại: u
Chữ cái hiện tại: a
Chữ cái hiện tại: n
Chữ cái hiện tại: t
Chữ cái hiện tại: r
Chữ cái hiện tại: i
Chữ cái hiện tại: m
Chữ cái hiện tại: a
Chữ cái hiện tại: n
Chữ cái hiện tại: g
Anh 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 2
print(list(range(9)))
#Lệnh 3
print(list(range(2, 5)))
#Lệnh 4
print(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:
0
2
4
5
Đã 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
# Repeat on factors of a number in the sequence
for num in range(0,10):
for 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ứ 2
print ('%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ên
else: # Phần else trong vòng lặp
print (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 * 2
5 là số nguyên tố
6 bằng 2 * 3
7 là số nguyên tố
8 bằng 2 * 4
9 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
You should read it
- 5 choose the best Python IDE for you
- Python data type: string, number, list, tuple, set and dictionary
- The loop technique in Python
- What is Python? Why choose Python?
- If, if ... else, if ... elif ... else commands in Python
- Why should you learn Python programming language?
- Python online editor
- How to set up Python to program on WSL
May be interested
- Loop in programming Csimilar 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 Windowsafter 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 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? to help you with this question, the following article will help you find out what loop mail is.
- Bookmark 5 best Python programming learning websitesif 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 Pythonpython 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 JavaScriptthe 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 JavaScriptjavascript 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 Notionmany 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 3today's topic quantrimang wants to challenge you is about file and exception handling in python. let's try the following 15 questions!