Thứ Hai, Tháng Hai 17, 2025
spot_img
HomeFor loop in Python

For loop in Python

For loop in Python Important in web and application design. Here's what you need to know about for in Python.

Programming is currently an extremely “sought after” industry because it is the “cradle” of creating many useful applications, software and websites. The programming world is extremely diverse and rich with many different languages. Python is only a part of it but is currently very popular because of its ease of use and flexibility.

Python is famous for being a powerful programming language, designed to be easy to understand and put into practical applications. Python is open source so programmers can easily edit it as desired. Learning Python is basically not difficult. You need to understand basic functions and components.

Like every other programming language, Python also has loops. It is very important when you develop any application. In this article, let's learn about for loops in Python!

What is a for loop in Python?

Python frequently uses loops to iterate over objects such as lists, tuples, and strings. However, it still has differences compared to other programming languages. Below are detailed information.

How does the for loop work internally?

Before going into details, let's learn about iterative variables in Python. First, let's look at a simple for loop example:

# Một ví dụ về for loop đơn giản

fruits = ["apple", "orange", "kiwi"]

for fruit in fruits:

	print(fruit)

Result:

apple
orange
Kiwi

You can see that the for loop variables on the iterator object are fruits displayed as a list. List, set, dictionary are just some iterable objects, while integer objects are not iterable objects. For loop can iterate over any of these iterable objects.

With the help of the example above, let's dig deeper to see what's happening internally here.

  • Create a list of an iterable object with the help of iter() function.
  • Run an endless while loop and only break if StopIteration is raised.
  • In the try block, fetch the next element of the fruit using the next() function.

After fetching the element is done, the operation is carried out with this element. (ie print(fruit))

fruits = ["apple", "orange", "kiwi"]

# Tạo đối tượng lặp
# từ biến có thể lặp i.e fruits
iter_obj = iter(fruits)

# while loop vô tận
while True:
	try:
		# Lấy biến tiếp theo
		fruit = next(iter_obj)
		print(fruit)
	except StopIteration:

		# nếu StopIteration tăng,
		# thoát vòng lặp
		break

Result

apple
orange
kiwi

Other examples:

List each fruit as a list:

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)

Loop for does not require a pre-set index variable.

Syntax of 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 a variable that receives the value of each item inside chuoi_lap on each iteration. The loop will continue until it reaches the last item in the sequence.

Command block of for indented to distinguish it from the rest of the code.

For loop diagram

For loop diagram

For loop through a string

A string is an object that can be looped to read one letter at a time. For example:

#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

For loop in a sequence of numbers

In addition to using loops for To get letters and characters in a string, we also use for to get numbers in an array of numbers.

# 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 you run the above code, you will receive the following result:

Tổng các số là 55

Break statement in for

With the break statement, we can stop the loop before it iterates over all the items in the loop. For example, stop the loop when encountering a period (.) in the string quantrimang.com:

#Lặp chữ cái có break:

a=["quan","tri","mang",".","com"]
for chu in a:
    if chu == ".":
        break
    print(chu)
print("Nội dung ngoài vòng lặp for")

The result after running the above code is:

quan
tri
mang
Nội dung ngoài vòng lặp for

In the above example, the loop iterates over the letters: mandarin, tri, carry; until you reach the dot "."the loop exits completely and does not print the last word: com.

The continue statement in for

Not like breakcommand continue will only stop the iteration of the current loop and continue with the next iteration. For example, repeat the string quan, tri, mang, ., com above but omit to print the dot character (.). The command sequence will be as follows:

#Lặp chữ cái có break:

a=["quan","tri","mang",".","com"]
for chu in a:
    if chu == ".":
        continue
    print(chu)
print("Nội dung ngoài vòng lặp for")

The result after running the command will be:

quan
tri
mang
com
Nội dung ngoài vòng lặp for

As you saw in the above output, the loop just skips the character printing loop . and continues to print words com behind it.

The pass command in for

Commands in loops for usually can't be left blank, but if for some reason you're just coming up with an idea for a loop for without content inside, use the command now pass to “reserve” blocks of code that I haven't thought of yet.

For example:

#Sử dụng pass để đặt chỗ cho những khối code trong tương lai:

for x in 'QuanTriMang':
  pass

Run the above command block and you will not see any results returned, due to the loop for used pass to skip command blocks. If there is no order pass You will get the following error:

File "", line 2
    
    ^
SyntaxError: unexpected EOF while parsing

function range()

You can use functions range() to create a series of numbers. For example, range(100) will create a series of numbers from 0 to 99 (100 numbers).

Jaw range(so_bat_dau, so_ket_thuc, khoang_cach_2_so) used to create custom number ranges. If you do not set a space between two numbers, Python will default to 1.

For example: Write 100 times “I'm sorry“, we will let the variable i iterate from 0 to 100 as follows:

for i in range(100):
    print ("Anh xin lỗi")
print("Em ơi, anh chép xong ồi nè!")

Jaw range() does not store all values ​​in memory but it stores the starting value, ending value and the distance between two numbers from which the next number in the sequence is created.

To range() output all values, you need to use the function list() 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 Commands 1, 2, 3, 4 above.

Jaw range() Can be used in conjunction with len() to iterate over a range using index, as in the example below:

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

Nested for loops

A nested loop is a loop placed inside another loop. The innermost loop will be executed for each iteration of the outer loop.

Example: Match adjectives to each type of fruit

#Ví dụ về vòng lặp lồng nhau trên QuanTriMang

tinhtu = ["đỏ", "to", "ngon"]
qua = ["táo", "chuối", "cherry"]

for x in qua:
  for y in tinhtu:
    print(x, y)

The result after running the above command will be as follows:

táo đỏ
táo to
táo ngon
chuối đỏ
chuối to
chuối ngon
cherry đỏ
cherry to
cherry ngon

Combine for with else

In the previous lesson you saw the structure if...else and if...elif...else. else not only combined with if which in loop for can also be used.

In for, the else block will be executed when the items in the sequence have been iterated.

For example:

B = [0, 2, 4, 5]

for b in B:
    print(b)
else:
    print("Đã hết số.")

Here, the for loop will print out list B until it runs out of items. When the loop ends it executes the else block and prints. We have the following result after running the code:

0
2
4
5
Đã hết số.

Command break can be used to stop the loop forat this part else will be ignored. Or in other words, part else in for will run when there is none break Which is executed.

For example:

#Lặp dãy từ 0 đến 10
for num in range(0,10):
#Lặp trên các thừa số của một số trong dãy
   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 loops the numbers in the range from 0 to 10. For each number, a loop will run to check if it is a prime number. If so, print a message and stop the checking loop, moving on to the next number in the loop. In the first iteration, if the number is not prime, the else block will be executed. 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 loops. In the next article you will learn about while loops. Do you remember where you saw it in the series of introductions to Python by TipsMake.com?

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments