Dòng lệnh Python trong vòng lặp

Trong khi các vòng lặp là cấu trúc lập trình rất mạnh mẽ mà bạn có thể sử dụng trong các chương trình của mình để lặp lại một chuỗi các câu lệnh

Trong bài viết này, bạn sẽ học

  • vòng lặp while là gì
  • Chúng được sử dụng để làm gì
  • Khi nào chúng nên được sử dụng
  • Cách họ làm việc đằng sau hậu trường
  • Cách viết vòng lặp while trong Python
  • Vòng lặp vô hạn là gì và làm thế nào để ngắt chúng
  • # Define the list
    nums = []
    
    # The loop will run while the length of the
    # list nums is less than 4
    while len(nums) < 4:
        # Ask for user input and store it in a variable as an integer.
        user_input = int(input("Enter an integer: "))
        # If the input is an even number, add it to the list
        if user_input % 2 == 0:
            nums.append(user_input)
    5 được sử dụng để làm gì và cú pháp chung của nó
  • Cách sử dụng câu lệnh
    # Define the list
    nums = []
    
    # The loop will run while the length of the
    # list nums is less than 4
    while len(nums) < 4:
        # Ask for user input and store it in a variable as an integer.
        user_input = int(input("Enter an integer: "))
        # If the input is an even number, add it to the list
        if user_input % 2 == 0:
            nums.append(user_input)
    6 để dừng vòng lặp while

Bạn sẽ tìm hiểu cách các vòng lặp while hoạt động đằng sau hậu trường với các ví dụ, bảng và sơ đồ

Bạn đã sẵn sàng chưa? . 🔅

🔹 Mục đích và các trường hợp sử dụng vòng lặp While

Hãy bắt đầu với mục đích của vòng lặp while. Chúng nó được dùng cho cái gì?

Chúng được sử dụng để lặp lại một chuỗi các câu lệnh với số lần không xác định. Loại vòng lặp này chạy khi điều kiện cho trước là

# Define the list
nums = []

# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
    # Ask for user input and store it in a variable as an integer.
    user_input = int(input("Enter an integer: "))
    # If the input is an even number, add it to the list
    if user_input % 2 == 0:
        nums.append(user_input)
7 và nó chỉ dừng khi điều kiện đó trở thành
# Define the list
nums = []

# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
    # Ask for user input and store it in a variable as an integer.
    user_input = int(input("Enter an integer: "))
    # If the input is an even number, add it to the list
    if user_input % 2 == 0:
        nums.append(user_input)
8

Khi chúng ta viết một vòng lặp while, chúng ta không xác định rõ ràng có bao nhiêu lần lặp sẽ được hoàn thành, chúng ta chỉ viết điều kiện phải là

# Define the list
nums = []

# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
    # Ask for user input and store it in a variable as an integer.
    user_input = int(input("Enter an integer: "))
    # If the input is an even number, add it to the list
    if user_input % 2 == 0:
        nums.append(user_input)
7 để tiếp tục quá trình và
# Define the list
nums = []

# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
    # Ask for user input and store it in a variable as an integer.
    user_input = int(input("Enter an integer: "))
    # If the input is an even number, add it to the list
    if user_input % 2 == 0:
        nums.append(user_input)
8 để dừng nó

💡 Mẹo. nếu điều kiện của vòng lặp while không bao giờ có giá trị là

# Define the list
nums = []

# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
    # Ask for user input and store it in a variable as an integer.
    user_input = int(input("Enter an integer: "))
    # If the input is an even number, add it to the list
    if user_input % 2 == 0:
        nums.append(user_input)
8, thì chúng ta sẽ có một vòng lặp vô hạn, là vòng lặp không bao giờ dừng (về lý thuyết) mà không có sự can thiệp từ bên ngoài

Đây là một số ví dụ về các trường hợp sử dụng thực tế của vòng lặp while

  • Đầu vào của người dùng. Khi chúng tôi yêu cầu người dùng nhập, chúng tôi cần kiểm tra xem giá trị được nhập có hợp lệ không. Chúng tôi không thể biết trước số lần người dùng sẽ nhập một đầu vào không hợp lệ trước khi chương trình có thể tiếp tục. Do đó, một vòng lặp while sẽ hoàn hảo cho kịch bản này
  • Tìm kiếm. tìm kiếm một phần tử trong cấu trúc dữ liệu là một trường hợp sử dụng hoàn hảo khác cho vòng lặp while vì chúng ta không thể biết trước sẽ cần bao nhiêu lần lặp để tìm giá trị đích. Ví dụ: thuật toán Tìm kiếm nhị phân có thể được triển khai bằng vòng lặp while
  • Trò chơi. Trong một trò chơi, vòng lặp while có thể được sử dụng để duy trì logic chính của trò chơi cho đến khi người chơi thua hoặc trò chơi kết thúc. Chúng ta không thể biết trước khi nào điều này sẽ xảy ra, vì vậy đây là một kịch bản hoàn hảo khác cho vòng lặp while

🔸 Cách vòng lặp hoạt động

Bây giờ bạn đã biết vòng lặp while được sử dụng để làm gì, hãy xem logic chính của chúng và cách chúng hoạt động đằng sau hậu trường. Ở đây chúng ta có một sơ đồ

Dòng lệnh Python trong vòng lặp
Trong khi lặp lại

Hãy chia nhỏ điều này chi tiết hơn

  • Quá trình bắt đầu khi vòng lặp while được tìm thấy trong quá trình thực thi chương trình
  • Điều kiện được đánh giá để kiểm tra xem nó là
    # Define the list
    nums = []
    
    # The loop will run while the length of the
    # list nums is less than 4
    while len(nums) < 4:
        # Ask for user input and store it in a variable as an integer.
        user_input = int(input("Enter an integer: "))
        # If the input is an even number, add it to the list
        if user_input % 2 == 0:
            nums.append(user_input)
    7 hay
    # Define the list
    nums = []
    
    # The loop will run while the length of the
    # list nums is less than 4
    while len(nums) < 4:
        # Ask for user input and store it in a variable as an integer.
        user_input = int(input("Enter an integer: "))
        # If the input is an even number, add it to the list
        if user_input % 2 == 0:
            nums.append(user_input)
    8
  • Nếu điều kiện là
    # Define the list
    nums = []
    
    # The loop will run while the length of the
    # list nums is less than 4
    while len(nums) < 4:
        # Ask for user input and store it in a variable as an integer.
        user_input = int(input("Enter an integer: "))
        # If the input is an even number, add it to the list
        if user_input % 2 == 0:
            nums.append(user_input)
    7 thì các câu lệnh thuộc vòng lặp được thực hiện
  • Điều kiện vòng lặp while được kiểm tra lại
  • Nếu điều kiện đánh giá lại thành
    # Define the list
    nums = []
    
    # The loop will run while the length of the
    # list nums is less than 4
    while len(nums) < 4:
        # Ask for user input and store it in a variable as an integer.
        user_input = int(input("Enter an integer: "))
        # If the input is an even number, add it to the list
        if user_input % 2 == 0:
            nums.append(user_input)
    7, chuỗi các câu lệnh sẽ chạy lại và quy trình được lặp lại
  • Khi điều kiện đánh giá là
    # Define the list
    nums = []
    
    # The loop will run while the length of the
    # list nums is less than 4
    while len(nums) < 4:
        # Ask for user input and store it in a variable as an integer.
        user_input = int(input("Enter an integer: "))
        # If the input is an even number, add it to the list
        if user_input % 2 == 0:
            nums.append(user_input)
    8, vòng lặp dừng lại và chương trình tiếp tục vượt ra ngoài vòng lặp

Một trong những đặc điểm quan trọng nhất của vòng lặp while là các biến được sử dụng trong điều kiện vòng lặp không được cập nhật tự động. Chúng tôi phải cập nhật các giá trị của chúng một cách rõ ràng bằng mã của mình để đảm bảo rằng vòng lặp cuối cùng sẽ dừng khi điều kiện ước tính thành

# Define the list
nums = []

# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
    # Ask for user input and store it in a variable as an integer.
    user_input = int(input("Enter an integer: "))
    # If the input is an even number, add it to the list
    if user_input % 2 == 0:
        nums.append(user_input)
8

🔹 Cú pháp chung của vòng lặp While

Tuyệt. Bây giờ bạn đã biết vòng lặp while hoạt động như thế nào, vì vậy hãy đi sâu vào mã và xem cách bạn có thể viết vòng lặp while bằng Python. Đây là cú pháp cơ bản

Dòng lệnh Python trong vòng lặp
Vòng lặp While (Cú pháp)

Đây là những yếu tố chính (theo thứ tự)

  • Từ khóa
    nums = []
    8 (theo sau là khoảng trắng)
  • Một điều kiện để xác định xem vòng lặp có tiếp tục chạy hay không dựa trên giá trị thực của nó (
    # Define the list
    nums = []
    
    # The loop will run while the length of the
    # list nums is less than 4
    while len(nums) < 4:
        # Ask for user input and store it in a variable as an integer.
        user_input = int(input("Enter an integer: "))
        # If the input is an even number, add it to the list
        if user_input % 2 == 0:
            nums.append(user_input)
    7 hoặc
    # Define the list
    nums = []
    
    # The loop will run while the length of the
    # list nums is less than 4
    while len(nums) < 4:
        # Ask for user input and store it in a variable as an integer.
        user_input = int(input("Enter an integer: "))
        # If the input is an even number, add it to the list
        if user_input % 2 == 0:
            nums.append(user_input)
    8 )
  • Dấu hai chấm (
    while len(nums) < 4:
    1) ở cuối dòng đầu tiên
  • Chuỗi các câu lệnh sẽ được lặp lại. Khối mã này được gọi là "phần thân" của vòng lặp và nó phải được thụt vào. Nếu một câu lệnh không được thụt vào, nó sẽ không được coi là một phần của vòng lặp (vui lòng xem sơ đồ bên dưới)
Dòng lệnh Python trong vòng lặp

💡 Mẹo. (PEP 8) khuyến nghị sử dụng 4 dấu cách cho mỗi mức thụt đầu dòng. Các tab chỉ nên được sử dụng để duy trì tính nhất quán với mã đã được thụt lề bằng các tab

🔸 Ví dụ về vòng lặp While

Bây giờ bạn đã biết cách vòng lặp while hoạt động và cách viết chúng trong Python, hãy xem cách chúng hoạt động đằng sau hậu trường với một số ví dụ

Vòng lặp While cơ bản hoạt động như thế nào

Ở đây chúng ta có một vòng lặp while cơ bản in ra giá trị của

while len(nums) < 4:
2 trong khi
while len(nums) < 4:
2 nhỏ hơn 8 (
while len(nums) < 4:
4)

i = 4

while i < 8:
    print(i)
    i += 1

Nếu chúng ta chạy mã, chúng ta sẽ thấy đầu ra này

4
5
6
7

Hãy xem điều gì xảy ra đằng sau hậu trường khi mã chạy

Dòng lệnh Python trong vòng lặp
  • lặp lại 1. ban đầu, giá trị của
    while len(nums) < 4:
    2 là 4, vì vậy điều kiện
    while len(nums) < 4:
    4 ước tính là
    # Define the list
    nums = []
    
    # The loop will run while the length of the
    # list nums is less than 4
    while len(nums) < 4:
        # Ask for user input and store it in a variable as an integer.
        user_input = int(input("Enter an integer: "))
        # If the input is an even number, add it to the list
        if user_input % 2 == 0:
            nums.append(user_input)
    7 và vòng lặp bắt đầu chạy. Giá trị của
    while len(nums) < 4:
    2 được in ra (4) và giá trị này được tăng thêm 1. Vòng lặp lại bắt đầu
  • lặp lại 2. bây giờ giá trị của
    while len(nums) < 4:
    2 là 5, vì vậy điều kiện
    while len(nums) < 4:
    4 ước tính thành
    # Define the list
    nums = []
    
    # The loop will run while the length of the
    # list nums is less than 4
    while len(nums) < 4:
        # Ask for user input and store it in a variable as an integer.
        user_input = int(input("Enter an integer: "))
        # If the input is an even number, add it to the list
        if user_input % 2 == 0:
            nums.append(user_input)
    7. Phần thân của vòng lặp chạy, giá trị của
    while len(nums) < 4:
    2 được in ra (5) và giá trị
    while len(nums) < 4:
    2 này được tăng thêm 1. Vòng lặp lại bắt đầu
  • Lặp lại 3 và 4. Quá trình tương tự được lặp lại cho lần lặp thứ ba và thứ tư, do đó các số nguyên 6 và 7 được in ra
  • Trước khi bắt đầu lần lặp thứ năm, giá trị của
    while len(nums) < 4:
    2 là
    user_input = int(input("Enter an integer: "))
    5. Bây giờ điều kiện của vòng lặp while
    while len(nums) < 4:
    4 có giá trị là
    # Define the list
    nums = []
    
    # The loop will run while the length of the
    # list nums is less than 4
    while len(nums) < 4:
        # Ask for user input and store it in a variable as an integer.
        user_input = int(input("Enter an integer: "))
        # If the input is an even number, add it to the list
        if user_input % 2 == 0:
            nums.append(user_input)
    8 và vòng lặp dừng ngay lập tức

💡 Mẹo. Nếu điều kiện của vòng lặp while là

# Define the list
nums = []

# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
    # Ask for user input and store it in a variable as an integer.
    user_input = int(input("Enter an integer: "))
    # If the input is an even number, add it to the list
    if user_input % 2 == 0:
        nums.append(user_input)
8 trước khi bắt đầu lần lặp đầu tiên, thì vòng lặp while thậm chí sẽ không bắt đầu chạy

Đầu vào của người dùng bằng vòng lặp While

Bây giờ hãy xem một ví dụ về vòng lặp while trong một chương trình lấy đầu vào của người dùng. Chúng ta sẽ sử dụng hàm

user_input = int(input("Enter an integer: "))
9 để yêu cầu người dùng nhập một số nguyên và số nguyên đó sẽ chỉ được thêm vào danh sách nếu nó chẵn

Đây là mã

# Define the list
nums = []

# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
    # Ask for user input and store it in a variable as an integer.
    user_input = int(input("Enter an integer: "))
    # If the input is an even number, add it to the list
    if user_input % 2 == 0:
        nums.append(user_input)

Điều kiện của vòng lặp là

if user_input % 2 == 0:
0, vì vậy vòng lặp sẽ chạy trong khi độ dài của danh sách
if user_input % 2 == 0:
1 hoàn toàn nhỏ hơn 4

Hãy phân tích từng dòng chương trình này

  • Chúng tôi bắt đầu bằng cách xác định một danh sách trống và gán nó cho một biến có tên là
    if user_input % 2 == 0:
    1
nums = []
  • Sau đó, chúng tôi xác định một vòng lặp while sẽ chạy trong khi
    if user_input % 2 == 0:
    0
while len(nums) < 4:
  • Chúng tôi yêu cầu đầu vào của người dùng với hàm
    user_input = int(input("Enter an integer: "))
    9 và lưu trữ nó trong biến
    if user_input % 2 == 0:
    5
user_input = int(input("Enter an integer: "))

💡 Mẹo. Ta cần chuyển đổi (cast) giá trị do người dùng nhập thành số nguyên bằng hàm

if user_input % 2 == 0:
6 trước khi gán cho biến vì hàm
user_input = int(input("Enter an integer: "))
9 trả về một chuỗi ()

  • Chúng tôi kiểm tra xem giá trị này là chẵn hay lẻ
if user_input % 2 == 0:
  • Nếu nó chẵn, chúng ta thêm nó vào danh sách
    if user_input % 2 == 0:
    1
nums.append(user_input)
  • Ngược lại, nếu nó là số lẻ, vòng lặp sẽ bắt đầu lại và điều kiện được kiểm tra để xác định xem vòng lặp có tiếp tục hay không

Nếu chúng tôi chạy mã này với đầu vào của người dùng tùy chỉnh, chúng tôi sẽ nhận được đầu ra sau

Enter an integer: 3
Enter an integer: 4    
Enter an integer: 2    
Enter an integer: 1
Enter an integer: 7
Enter an integer: 6    
Enter an integer: 3
Enter an integer: 4    

Bảng này tóm tắt những gì diễn ra ở hậu trường khi mã chạy

Dòng lệnh Python trong vòng lặp

💡 Mẹo. Giá trị ban đầu của

if user_input % 2 == 0:
9 là
nums.append(user_input)
0 vì ban đầu danh sách trống. Cột cuối cùng của bảng hiển thị độ dài của danh sách ở cuối lần lặp hiện tại. Giá trị này được sử dụng để kiểm tra điều kiện trước khi bắt đầu lần lặp tiếp theo

Như bạn có thể thấy trong bảng, người dùng nhập các số nguyên chẵn vào lần lặp thứ hai, thứ ba, thứ sáu và thứ tám và các giá trị này được thêm vào danh sách

if user_input % 2 == 0:
1

Trước khi lần lặp "thứ chín" bắt đầu, điều kiện được kiểm tra lại nhưng bây giờ nó ước tính thành

# Define the list
nums = []

# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
    # Ask for user input and store it in a variable as an integer.
    user_input = int(input("Enter an integer: "))
    # If the input is an even number, add it to the list
    if user_input % 2 == 0:
        nums.append(user_input)
8 vì danh sách
if user_input % 2 == 0:
1 có bốn phần tử (độ dài 4), vì vậy vòng lặp dừng lại

Nếu chúng tôi kiểm tra giá trị của danh sách

if user_input % 2 == 0:
1 khi quá trình này đã hoàn tất, chúng tôi sẽ thấy điều này

>>> nums
[4, 2, 6, 4]

Chính xác như những gì chúng ta mong đợi, vòng lặp while dừng lại khi điều kiện

if user_input % 2 == 0:
0 được đánh giá là
# Define the list
nums = []

# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
    # Ask for user input and store it in a variable as an integer.
    user_input = int(input("Enter an integer: "))
    # If the input is an even number, add it to the list
    if user_input % 2 == 0:
        nums.append(user_input)
8

Bây giờ bạn đã biết các vòng lặp while hoạt động đằng sau hậu trường như thế nào và bạn đã thấy một số ví dụ thực tế, vì vậy hãy đi sâu vào yếu tố chính của vòng lặp while. điều kiện

🔹 Mẹo về Điều kiện trong Vòng lặp While

Trước khi bắt đầu làm việc với vòng lặp while, bạn nên biết rằng điều kiện vòng lặp đóng vai trò trung tâm trong chức năng và đầu ra của vòng lặp while

Dòng lệnh Python trong vòng lặp

Bạn phải rất cẩn thận với toán tử so sánh mà bạn chọn vì đây là nguồn lỗi rất phổ biến

Ví dụ, các lỗi phổ biến bao gồm

  • Sử dụng
    nums.append(user_input)
    7 (nhỏ hơn) thay vì
    nums.append(user_input)
    8 (nhỏ hơn hoặc bằng) (hoặc ngược lại)
  • Sử dụng
    nums.append(user_input)
    9 (lớn hơn) thay vì
    Enter an integer: 3
    Enter an integer: 4    
    Enter an integer: 2    
    Enter an integer: 1
    Enter an integer: 7
    Enter an integer: 6    
    Enter an integer: 3
    Enter an integer: 4    
    0 (lớn hơn hoặc bằng) (hoặc ngược lại).  

Điều này có thể ảnh hưởng đến số lần lặp của vòng lặp và thậm chí cả đầu ra của nó

Hãy xem một ví dụ

Nếu chúng ta viết vòng lặp while này với điều kiện

Enter an integer: 3
Enter an integer: 4    
Enter an integer: 2    
Enter an integer: 1
Enter an integer: 7
Enter an integer: 6    
Enter an integer: 3
Enter an integer: 4    
1

4
5
6
7
0

Chúng tôi thấy đầu ra này khi mã chạy

4
5
6
7
1

Vòng lặp hoàn thành ba lần lặp và nó dừng khi

while len(nums) < 4:
2 bằng với
Enter an integer: 3
Enter an integer: 4    
Enter an integer: 2    
Enter an integer: 1
Enter an integer: 7
Enter an integer: 6    
Enter an integer: 3
Enter an integer: 4    
3

Bảng này minh họa những gì diễn ra ở hậu trường khi mã chạy

Dòng lệnh Python trong vòng lặp
  • Trước lần lặp đầu tiên của vòng lặp, giá trị của
    while len(nums) < 4:
    2 là 6, vì vậy điều kiện
    Enter an integer: 3
    Enter an integer: 4    
    Enter an integer: 2    
    Enter an integer: 1
    Enter an integer: 7
    Enter an integer: 6    
    Enter an integer: 3
    Enter an integer: 4    
    1 là
    # Define the list
    nums = []
    
    # The loop will run while the length of the
    # list nums is less than 4
    while len(nums) < 4:
        # Ask for user input and store it in a variable as an integer.
        user_input = int(input("Enter an integer: "))
        # If the input is an even number, add it to the list
        if user_input % 2 == 0:
            nums.append(user_input)
    7 và vòng lặp bắt đầu chạy. Giá trị của
    while len(nums) < 4:
    2 được in ra và sau đó nó được tăng thêm 1
  • Trong lần lặp thứ hai của vòng lặp, giá trị của
    while len(nums) < 4:
    2 là 7, vì vậy điều kiện
    Enter an integer: 3
    Enter an integer: 4    
    Enter an integer: 2    
    Enter an integer: 1
    Enter an integer: 7
    Enter an integer: 6    
    Enter an integer: 3
    Enter an integer: 4    
    1 là
    # Define the list
    nums = []
    
    # The loop will run while the length of the
    # list nums is less than 4
    while len(nums) < 4:
        # Ask for user input and store it in a variable as an integer.
        user_input = int(input("Enter an integer: "))
        # If the input is an even number, add it to the list
        if user_input % 2 == 0:
            nums.append(user_input)
    7. Phần thân của vòng lặp chạy, giá trị của
    while len(nums) < 4:
    2 được in ra, sau đó giá trị này được tăng thêm 1
  • Trong lần lặp thứ ba của vòng lặp, giá trị của
    while len(nums) < 4:
    2 là 8, vì vậy điều kiện
    Enter an integer: 3
    Enter an integer: 4    
    Enter an integer: 2    
    Enter an integer: 1
    Enter an integer: 7
    Enter an integer: 6    
    Enter an integer: 3
    Enter an integer: 4    
    1 là
    # Define the list
    nums = []
    
    # The loop will run while the length of the
    # list nums is less than 4
    while len(nums) < 4:
        # Ask for user input and store it in a variable as an integer.
        user_input = int(input("Enter an integer: "))
        # If the input is an even number, add it to the list
        if user_input % 2 == 0:
            nums.append(user_input)
    7. Phần thân của vòng lặp chạy, giá trị của
    while len(nums) < 4:
    2 được in ra, sau đó giá trị này được tăng thêm 1
  • Điều kiện được kiểm tra lại trước khi lần lặp thứ tư bắt đầu, nhưng bây giờ giá trị của
    while len(nums) < 4:
    2 là 9, vì vậy
    Enter an integer: 3
    Enter an integer: 4    
    Enter an integer: 2    
    Enter an integer: 1
    Enter an integer: 7
    Enter an integer: 6    
    Enter an integer: 3
    Enter an integer: 4    
    1 là
    # Define the list
    nums = []
    
    # The loop will run while the length of the
    # list nums is less than 4
    while len(nums) < 4:
        # Ask for user input and store it in a variable as an integer.
        user_input = int(input("Enter an integer: "))
        # If the input is an even number, add it to the list
        if user_input % 2 == 0:
            nums.append(user_input)
    8 và vòng lặp dừng lại

Trong trường hợp này, chúng tôi đã sử dụng

nums.append(user_input)
7 làm toán tử so sánh trong điều kiện, nhưng bạn nghĩ điều gì sẽ xảy ra nếu chúng tôi sử dụng
nums.append(user_input)
8 thay thế?

4
5
6
7
2

Chúng tôi thấy đầu ra này

4
5
6
7
3

Vòng lặp hoàn thành một lần lặp nữa vì bây giờ chúng ta đang sử dụng toán tử "nhỏ hơn hoặc bằng"

nums.append(user_input)
8 , vì vậy điều kiện vẫn là
# Define the list
nums = []

# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
    # Ask for user input and store it in a variable as an integer.
    user_input = int(input("Enter an integer: "))
    # If the input is an even number, add it to the list
    if user_input % 2 == 0:
        nums.append(user_input)
7 khi
while len(nums) < 4:
2 bằng với
Enter an integer: 3
Enter an integer: 4    
Enter an integer: 2    
Enter an integer: 1
Enter an integer: 7
Enter an integer: 6    
Enter an integer: 3
Enter an integer: 4    
3

Bảng này minh họa những gì xảy ra đằng sau hậu trường

Dòng lệnh Python trong vòng lặp

Bốn lần lặp được hoàn thành. Điều kiện được kiểm tra lại trước khi bắt đầu lặp lại "thứ năm". Tại thời điểm này, giá trị của

while len(nums) < 4:
2 là
4
5
6
7
06, vì vậy điều kiện
4
5
6
7
07 là
# Define the list
nums = []

# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
    # Ask for user input and store it in a variable as an integer.
    user_input = int(input("Enter an integer: "))
    # If the input is an even number, add it to the list
    if user_input % 2 == 0:
        nums.append(user_input)
8 và vòng lặp dừng lại

🔸 Vòng lặp While vô hạn

Bây giờ bạn đã biết vòng lặp while hoạt động như thế nào, nhưng bạn nghĩ điều gì sẽ xảy ra nếu điều kiện của vòng lặp while không bao giờ có giá trị là

# Define the list
nums = []

# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
    # Ask for user input and store it in a variable as an integer.
    user_input = int(input("Enter an integer: "))
    # If the input is an even number, add it to the list
    if user_input % 2 == 0:
        nums.append(user_input)
8?

Dòng lệnh Python trong vòng lặp

Vòng lặp While vô hạn là gì?

Hãy nhớ rằng các vòng lặp while không tự động cập nhật các biến (chúng tôi chịu trách nhiệm thực hiện điều đó một cách rõ ràng bằng mã của mình). Vì vậy, không có gì đảm bảo rằng vòng lặp sẽ dừng trừ khi chúng ta viết mã cần thiết để tạo điều kiện

# Define the list
nums = []

# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
    # Ask for user input and store it in a variable as an integer.
    user_input = int(input("Enter an integer: "))
    # If the input is an even number, add it to the list
    if user_input % 2 == 0:
        nums.append(user_input)
8 tại một thời điểm nào đó trong quá trình thực hiện vòng lặp

Nếu chúng ta không làm điều này và điều kiện luôn có giá trị là

# Define the list
nums = []

# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
    # Ask for user input and store it in a variable as an integer.
    user_input = int(input("Enter an integer: "))
    # If the input is an even number, add it to the list
    if user_input % 2 == 0:
        nums.append(user_input)
7, thì chúng ta sẽ có một vòng lặp vô hạn, đó là một vòng lặp while chạy vô thời hạn (theo lý thuyết)

Các vòng lặp vô hạn thường là kết quả của một lỗi, nhưng chúng cũng có thể được gây ra một cách có chủ ý khi chúng ta muốn lặp lại một chuỗi các câu lệnh vô thời hạn cho đến khi tìm thấy một câu lệnh

# Define the list
nums = []

# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
    # Ask for user input and store it in a variable as an integer.
    user_input = int(input("Enter an integer: "))
    # If the input is an even number, add it to the list
    if user_input % 2 == 0:
        nums.append(user_input)
6

Hãy xem hai loại vòng lặp vô hạn này trong các ví dụ dưới đây

💡 Mẹo. Lỗi là lỗi trong chương trình gây ra kết quả không chính xác hoặc không mong muốn

Ví dụ về Vòng lặp vô hạn

Đây là một ví dụ về một vòng lặp vô hạn không chủ ý gây ra bởi một lỗi trong chương trình

4
5
6
7
4

Phân tích mã này trong giây lát

Bạn không nhận thấy một cái gì đó bị thiếu trong phần thân của vòng lặp?

Đúng rồi

Giá trị của biến

while len(nums) < 4:
2 không bao giờ được cập nhật (nó luôn là
4
5
6
7
14). Do đó, điều kiện
4
5
6
7
15 luôn là
# Define the list
nums = []

# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
    # Ask for user input and store it in a variable as an integer.
    user_input = int(input("Enter an integer: "))
    # If the input is an even number, add it to the list
    if user_input % 2 == 0:
        nums.append(user_input)
7 và vòng lặp không bao giờ dừng

Nếu chúng tôi chạy mã này, đầu ra sẽ là một chuỗi "vô hạn" gồm các thông báo

4
5
6
7
17 vì phần thân của vòng lặp
4
5
6
7
18 sẽ chạy vô thời hạn

4
5
6
7
5

Để dừng chương trình, chúng ta cần ngắt vòng lặp theo cách thủ công bằng cách nhấn

4
5
6
7
19

Khi chúng tôi thực hiện, chúng tôi sẽ thấy lỗi

4
5
6
7
20 tương tự như lỗi này

Dòng lệnh Python trong vòng lặp

Để khắc phục vòng lặp này, chúng ta sẽ cần cập nhật giá trị của

while len(nums) < 4:
2 trong phần thân của vòng lặp để đảm bảo rằng điều kiện
4
5
6
7
15 cuối cùng sẽ có giá trị là
# Define the list
nums = []

# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
    # Ask for user input and store it in a variable as an integer.
    user_input = int(input("Enter an integer: "))
    # If the input is an even number, add it to the list
    if user_input % 2 == 0:
        nums.append(user_input)
8

Đây là một giải pháp khả thi, tăng giá trị của

while len(nums) < 4:
2 lên 2 trên mỗi lần lặp lại

4
5
6
7
6

Tuyệt. Bây giờ bạn đã biết cách khắc phục các vòng lặp vô hạn do lỗi gây ra. Bạn chỉ cần viết mã để đảm bảo rằng điều kiện cuối cùng sẽ đánh giá là

# Define the list
nums = []

# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
    # Ask for user input and store it in a variable as an integer.
    user_input = int(input("Enter an integer: "))
    # If the input is an even number, add it to the list
    if user_input % 2 == 0:
        nums.append(user_input)
8

Hãy bắt đầu đi sâu vào các vòng lặp vô hạn có chủ ý và cách chúng hoạt động

🔹 Cách tạo vòng lặp vô hạn với While True

Chúng ta có thể cố ý tạo một vòng lặp vô hạn bằng cách sử dụng

# Define the list
nums = []

# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
    # Ask for user input and store it in a variable as an integer.
    user_input = int(input("Enter an integer: "))
    # If the input is an even number, add it to the list
    if user_input % 2 == 0:
        nums.append(user_input)
5. Trong trường hợp này, vòng lặp sẽ chạy vô thời hạn cho đến khi quá trình bị dừng bởi sự can thiệp từ bên ngoài (
4
5
6
7
19) hoặc khi tìm thấy câu lệnh
# Define the list
nums = []

# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
    # Ask for user input and store it in a variable as an integer.
    user_input = int(input("Enter an integer: "))
    # If the input is an even number, add it to the list
    if user_input % 2 == 0:
        nums.append(user_input)
6 (bạn sẽ tìm hiểu thêm về
# Define the list
nums = []

# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
    # Ask for user input and store it in a variable as an integer.
    user_input = int(input("Enter an integer: "))
    # If the input is an even number, add it to the list
    if user_input % 2 == 0:
        nums.append(user_input)
6 ngay sau đây)

Đây là cú pháp cơ bản

Dòng lệnh Python trong vòng lặp

Thay vì viết một điều kiện sau từ khóa

nums = []
8, chúng ta chỉ viết trực tiếp giá trị thực để chỉ ra rằng điều kiện sẽ luôn là
# Define the list
nums = []

# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
    # Ask for user input and store it in a variable as an integer.
    user_input = int(input("Enter an integer: "))
    # If the input is an even number, add it to the list
    if user_input % 2 == 0:
        nums.append(user_input)
7

Ở đây chúng ta có một ví dụ

4
5
6
7
7

Vòng lặp chạy cho đến khi nhấn vào

4
5
6
7
19, nhưng Python cũng có câu lệnh
# Define the list
nums = []

# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
    # Ask for user input and store it in a variable as an integer.
    user_input = int(input("Enter an integer: "))
    # If the input is an even number, add it to the list
    if user_input % 2 == 0:
        nums.append(user_input)
6 mà chúng ta có thể sử dụng trực tiếp trong mã của mình để dừng loại vòng lặp này

Tuyên bố # Define the list nums = [] # The loop will run while the length of the # list nums is less than 4 while len(nums) < 4: # Ask for user input and store it in a variable as an integer. user_input = int(input("Enter an integer: ")) # If the input is an even number, add it to the list if user_input % 2 == 0: nums.append(user_input)6

Câu lệnh này được sử dụng để dừng một vòng lặp ngay lập tức. Bạn nên coi nó như một "dấu hiệu dừng" màu đỏ mà bạn có thể sử dụng trong mã của mình để có nhiều quyền kiểm soát hơn đối với hành vi của vòng lặp

Dòng lệnh Python trong vòng lặp

Theo

Câu lệnh, giống như trong C, thoát ra khỏi vòng lặp hoặc bao quanh trong cùng

Sơ đồ này minh họa logic cơ bản của câu lệnh

# Define the list
nums = []

# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
    # Ask for user input and store it in a variable as an integer.
    user_input = int(input("Enter an integer: "))
    # If the input is an even number, add it to the list
    if user_input % 2 == 0:
        nums.append(user_input)
6

Dòng lệnh Python trong vòng lặp
Tuyên bố
# Define the list
nums = []

# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
    # Ask for user input and store it in a variable as an integer.
    user_input = int(input("Enter an integer: "))
    # If the input is an even number, add it to the list
    if user_input % 2 == 0:
        nums.append(user_input)
6

Đây là logic cơ bản của câu lệnh

# Define the list
nums = []

# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
    # Ask for user input and store it in a variable as an integer.
    user_input = int(input("Enter an integer: "))
    # If the input is an even number, add it to the list
    if user_input % 2 == 0:
        nums.append(user_input)
6

  • Vòng lặp while chỉ bắt đầu nếu điều kiện đánh giá là
    # Define the list
    nums = []
    
    # The loop will run while the length of the
    # list nums is less than 4
    while len(nums) < 4:
        # Ask for user input and store it in a variable as an integer.
        user_input = int(input("Enter an integer: "))
        # If the input is an even number, add it to the list
        if user_input % 2 == 0:
            nums.append(user_input)
    7
  • Nếu một câu lệnh
    # Define the list
    nums = []
    
    # The loop will run while the length of the
    # list nums is less than 4
    while len(nums) < 4:
        # Ask for user input and store it in a variable as an integer.
        user_input = int(input("Enter an integer: "))
        # If the input is an even number, add it to the list
        if user_input % 2 == 0:
            nums.append(user_input)
    6 được tìm thấy tại bất kỳ thời điểm nào trong quá trình thực hiện vòng lặp, vòng lặp sẽ dừng ngay lập tức
  • Ngược lại, nếu không tìm thấy
    # Define the list
    nums = []
    
    # The loop will run while the length of the
    # list nums is less than 4
    while len(nums) < 4:
        # Ask for user input and store it in a variable as an integer.
        user_input = int(input("Enter an integer: "))
        # If the input is an even number, add it to the list
        if user_input % 2 == 0:
            nums.append(user_input)
    6, vòng lặp tiếp tục thực hiện bình thường và dừng khi điều kiện ước tính thành
    # Define the list
    nums = []
    
    # The loop will run while the length of the
    # list nums is less than 4
    while len(nums) < 4:
        # Ask for user input and store it in a variable as an integer.
        user_input = int(input("Enter an integer: "))
        # If the input is an even number, add it to the list
        if user_input % 2 == 0:
            nums.append(user_input)
    8

Chúng ta có thể sử dụng

# Define the list
nums = []

# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
    # Ask for user input and store it in a variable as an integer.
    user_input = int(input("Enter an integer: "))
    # If the input is an even number, add it to the list
    if user_input % 2 == 0:
        nums.append(user_input)
6 để dừng vòng lặp while khi một điều kiện được đáp ứng tại một thời điểm thực thi cụ thể của nó, vì vậy bạn thường sẽ tìm thấy nó trong một câu lệnh có điều kiện, như thế này

4
5
6
7
8

Điều này dừng vòng lặp ngay lập tức nếu điều kiện là

# Define the list
nums = []

# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
    # Ask for user input and store it in a variable as an integer.
    user_input = int(input("Enter an integer: "))
    # If the input is an even number, add it to the list
    if user_input % 2 == 0:
        nums.append(user_input)
7

💡 Mẹo. Bạn có thể (về lý thuyết) viết một câu lệnh

# Define the list
nums = []

# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
    # Ask for user input and store it in a variable as an integer.
    user_input = int(input("Enter an integer: "))
    # If the input is an even number, add it to the list
    if user_input % 2 == 0:
        nums.append(user_input)
6 ở bất kỳ đâu trong phần thân của vòng lặp. Nó không nhất thiết phải là một phần của điều kiện, nhưng chúng ta thường sử dụng nó để dừng vòng lặp khi một điều kiện nhất định là
# Define the list
nums = []

# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
    # Ask for user input and store it in a variable as an integer.
    user_input = int(input("Enter an integer: "))
    # If the input is an even number, add it to the list
    if user_input % 2 == 0:
        nums.append(user_input)
7

Ở đây chúng ta có một ví dụ về

# Define the list
nums = []

# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
    # Ask for user input and store it in a variable as an integer.
    user_input = int(input("Enter an integer: "))
    # If the input is an even number, add it to the list
    if user_input % 2 == 0:
        nums.append(user_input)
6 trong vòng lặp
# Define the list
nums = []

# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
    # Ask for user input and store it in a variable as an integer.
    user_input = int(input("Enter an integer: "))
    # If the input is an even number, add it to the list
    if user_input % 2 == 0:
        nums.append(user_input)
5

Dòng lệnh Python trong vòng lặp

Hãy xem chi tiết hơn

Dòng đầu tiên định nghĩa một vòng lặp

# Define the list
nums = []

# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
    # Ask for user input and store it in a variable as an integer.
    user_input = int(input("Enter an integer: "))
    # If the input is an even number, add it to the list
    if user_input % 2 == 0:
        nums.append(user_input)
5 sẽ chạy vô thời hạn cho đến khi tìm thấy câu lệnh
# Define the list
nums = []

# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
    # Ask for user input and store it in a variable as an integer.
    user_input = int(input("Enter an integer: "))
    # If the input is an even number, add it to the list
    if user_input % 2 == 0:
        nums.append(user_input)
6 (hoặc cho đến khi nó bị gián đoạn bởi
4
5
6
7
19)

4
5
6
7
9

Dòng thứ hai yêu cầu đầu vào của người dùng. Đầu vào này được chuyển đổi thành một số nguyên và được gán cho biến

if user_input % 2 == 0:
5

user_input = int(input("Enter an integer: "))

Dòng thứ ba kiểm tra xem đầu vào có phải là số lẻ không

# Define the list
nums = []

# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
    # Ask for user input and store it in a variable as an integer.
    user_input = int(input("Enter an integer: "))
    # If the input is an even number, add it to the list
    if user_input % 2 == 0:
        nums.append(user_input)
1

Nếu đúng, thông báo

4
5
6
7
55 được in ra và câu lệnh
# Define the list
nums = []

# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
    # Ask for user input and store it in a variable as an integer.
    user_input = int(input("Enter an integer: "))
    # If the input is an even number, add it to the list
    if user_input % 2 == 0:
        nums.append(user_input)
6 dừng vòng lặp ngay lập tức

# Define the list
nums = []

# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
    # Ask for user input and store it in a variable as an integer.
    user_input = int(input("Enter an integer: "))
    # If the input is an even number, add it to the list
    if user_input % 2 == 0:
        nums.append(user_input)
2

Ngược lại, nếu đầu vào là chẵn , thông báo

4
5
6
7
57 được in ra và vòng lặp bắt đầu lại

# Define the list
nums = []

# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
    # Ask for user input and store it in a variable as an integer.
    user_input = int(input("Enter an integer: "))
    # If the input is an even number, add it to the list
    if user_input % 2 == 0:
        nums.append(user_input)
3

Vòng lặp sẽ chạy vô thời hạn cho đến khi một số nguyên lẻ được nhập vào vì đó là cách duy nhất mà câu lệnh

# Define the list
nums = []

# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
    # Ask for user input and store it in a variable as an integer.
    user_input = int(input("Enter an integer: "))
    # If the input is an even number, add it to the list
    if user_input % 2 == 0:
        nums.append(user_input)
6 sẽ được tìm thấy

Ở đây chúng tôi có một ví dụ với đầu vào người dùng tùy chỉnh

# Define the list
nums = []

# The loop will run while the length of the
# list nums is less than 4
while len(nums) < 4:
    # Ask for user input and store it in a variable as an integer.
    user_input = int(input("Enter an integer: "))
    # If the input is an even number, add it to the list
    if user_input % 2 == 0:
        nums.append(user_input)
4

🔸 Tóm lại

  • Trong khi các vòng lặp là cấu trúc lập trình được sử dụng để lặp lại một chuỗi các câu lệnh trong khi một điều kiện là
    # Define the list
    nums = []
    
    # The loop will run while the length of the
    # list nums is less than 4
    while len(nums) < 4:
        # Ask for user input and store it in a variable as an integer.
        user_input = int(input("Enter an integer: "))
        # If the input is an even number, add it to the list
        if user_input % 2 == 0:
            nums.append(user_input)
    7. Họ dừng lại khi điều kiện đánh giá là
    # Define the list
    nums = []
    
    # The loop will run while the length of the
    # list nums is less than 4
    while len(nums) < 4:
        # Ask for user input and store it in a variable as an integer.
        user_input = int(input("Enter an integer: "))
        # If the input is an even number, add it to the list
        if user_input % 2 == 0:
            nums.append(user_input)
    8
  • Khi bạn viết một vòng lặp while, bạn cần thực hiện các cập nhật cần thiết trong mã của mình để đảm bảo rằng vòng lặp cuối cùng sẽ dừng lại
  • Vòng lặp vô hạn là vòng lặp chạy vô thời hạn và nó chỉ dừng lại khi có sự can thiệp từ bên ngoài hoặc khi tìm thấy câu lệnh
    # Define the list
    nums = []
    
    # The loop will run while the length of the
    # list nums is less than 4
    while len(nums) < 4:
        # Ask for user input and store it in a variable as an integer.
        user_input = int(input("Enter an integer: "))
        # If the input is an even number, add it to the list
        if user_input % 2 == 0:
            nums.append(user_input)
    6
  • Bạn có thể dừng một vòng lặp vô hạn với
    4
    5
    6
    7
    19
  • Bạn có thể cố ý tạo một vòng lặp vô hạn với
    # Define the list
    nums = []
    
    # The loop will run while the length of the
    # list nums is less than 4
    while len(nums) < 4:
        # Ask for user input and store it in a variable as an integer.
        user_input = int(input("Enter an integer: "))
        # If the input is an even number, add it to the list
        if user_input % 2 == 0:
            nums.append(user_input)
    5
  • Câu lệnh
    # Define the list
    nums = []
    
    # The loop will run while the length of the
    # list nums is less than 4
    while len(nums) < 4:
        # Ask for user input and store it in a variable as an integer.
        user_input = int(input("Enter an integer: "))
        # If the input is an even number, add it to the list
        if user_input % 2 == 0:
            nums.append(user_input)
    6 có thể được sử dụng để dừng vòng lặp while ngay lập tức

Tôi thực sự hy vọng bạn thích bài viết của tôi và thấy nó hữu ích. Bây giờ bạn đã biết cách làm việc với Vòng lặp While trong Python

Theo dõi tôi trên Twitter @EstefaniaCassN và nếu bạn muốn tìm hiểu thêm về chủ đề này, hãy xem khóa học trực tuyến của tôi Vòng lặp Python và Kỹ thuật lặp. Mới bắt đầu đến nâng cao

QUẢNG CÁO

QUẢNG CÁO

QUẢNG CÁO

QUẢNG CÁO

QUẢNG CÁO

QUẢNG CÁO

QUẢNG CÁO

QUẢNG CÁO

QUẢNG CÁO

QUẢNG CÁO

QUẢNG CÁO

QUẢNG CÁO

QUẢNG CÁO

QUẢNG CÁO

QUẢNG CÁO


Dòng lệnh Python trong vòng lặp
Estefania Cassingena Navone

Nhà phát triển, nhà văn kỹ thuật và người tạo nội dung @freeCodeCamp. Tôi chạy freeCodeCamp. org Kênh YouTube Español


Nếu bạn đọc đến đây, hãy tweet cho tác giả để cho họ thấy bạn quan tâm. Tweet một lời cảm ơn

Học cách viết mã miễn phí. Chương trình giảng dạy mã nguồn mở của freeCodeCamp đã giúp hơn 40.000 người có được việc làm với tư cách là nhà phát triển. Bắt đầu

Có thể sử dụng vòng lặp while không. ?

Giả sử trong vòng lặp while, bạn có hai điều kiện và bất kỳ điều kiện nào cũng phải đúng để tiếp tục với phần thân, thì trong trường hợp đó bạn có thể sử dụng. toán tử giữa hai điều kiện đó và trong trường hợp bạn muốn cả hai đều đúng, bạn có thể sử dụng toán tử &&.

Có lệnh lặp trong Python không?

Trong python, vòng lặp while được sử dụng để thực thi lặp đi lặp lại một khối câu lệnh cho đến khi một điều kiện nhất định được thỏa mãn . Và khi điều kiện trở thành sai thì dòng ngay sau vòng lặp trong chương trình được thực hiện.

Vòng lặp while hoạt động như thế nào trong Python?

Vòng lặp while sẽ chạy một đoạn mã khi điều kiện là Đúng . Nó sẽ tiếp tục thực thi tập hợp các câu lệnh mã mong muốn cho đến khi điều kiện đó không còn đúng nữa. Vòng lặp while sẽ luôn kiểm tra điều kiện trước khi chạy. Nếu điều kiện đánh giá là True thì vòng lặp sẽ chạy mã trong phần thân của vòng lặp.

+= trong Python là gì?

Toán tử cộng-bằng += cung cấp một cách thuận tiện để thêm giá trị vào một biến hiện có và gán lại giá trị mới cho cùng một biến. In the case where the variable and the value are strings, this operator performs string concatenation instead of addition.