简体   繁体   中英

Using while to exit for loop

I have this code that prints first ten elements of the list and then prints end:

a = ["11","12","13","14","15","16","17","18","19","110"]
n = 0
limit= 10
while n != limit:
    for b in a:
        if "1" in b:
            print(b)
            n += 1
print("end")

I am trying to figure out why it breaks if I add more numbers to the list.

a = ["11","12","13","14","15","16","17","18","19","110","111","112"]
n = 0
limit= 10
while n != limit:
    for b in a:
        if "1" in b:
            print(b)
            n += 1
print("end")

Goes on forever, printing the numbers again and again. Can someone explain why?

I have already replaced it with this but I just want to understand what was wrong with the first one.

a = ["11","12","13","14","15","16","17","18","19","110","111","112"]
n = 0
limit= 10
for b in a:
    if "1" in b:
        print(b)
        n += 1
    if n == limit:
        break
print("end")

What was wrong with it?

You add more than 1 at each turn in the ( while ) loop , so before the loop, n is smaller thant 10 , and after, it is greater than n . Thus, never equals 10 .

Just change the condition to >= (or > depending on what you want).

I am not still convinced that whatever you are doing is right. If fr sure you want to print the first 10 elements in the list, use this approach:

a = ["1", "12", "13", "14", "15", "16", "17", "18", "19", "110", "111", "112"]

limit = 10
for i in a[0:limit]:
    print(i)
print("end")

I have this code that prints first ten elements of the list and then prints end

That's not what your original code does. The for loop will iterate over all elements of the list, no matter how long. So, the while condition is only checked after you've iterated over the entire list.

So, when the code starts, the first while check is before any looping, and checks 0 != 10 . It's then not checked again until the for loop has visited every element of the list. Because your first list has exactly 10 elements with "1" in them, it turns out n will be exactly 10, and the second time the while condition is tested, it will be 10 == 10 . But in your second example, where you have 11 elements, the while condition won't be checked until n is 11.

Try putting print statements in various spots to see what's going on, eg just after the while statement, just after the for statement, just after the if statement. That will show you which statements are executed when.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM