TransWikia.com

Using while to exit for loop

Stack Overflow Asked by Lojcs on November 24, 2021

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?

3 Answers

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, e.g. just after the while statement, just after the for statement, just after the if statement. That will show you which statements are executed when.

Answered by Martin C. Martin on November 24, 2021

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")

Answered by Albert Alberto on November 24, 2021

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).

Answered by Adrien Kaczmarek on November 24, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP