Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,945 questions

51,887 answers

573 users

How to break out of nested for loops in Python

2 Answers

0 votes
break_out = False

for i in range(10):
    for j in range(5):
        if i == 4:
            break_out = True
            break
        print(j, end=" ")
    if break_out:
        break
        
    print("\n")

print("After loops")      



'''
run:

0 1 2 3 4 

0 1 2 3 4 

0 1 2 3 4 

0 1 2 3 4 

After loops

'''



 



answered Sep 7, 2022 by avibootz
0 votes
try:
    for i in range(10):
        for j in range(5):
            if i == 4:
                raise StopIteration
            print(j, end=" ")
        print("\n")

except StopIteration:
    pass

print("After loops")      




'''
run:

0 1 2 3 4 

0 1 2 3 4 

0 1 2 3 4 

0 1 2 3 4 

After loops

'''

 



answered Sep 7, 2022 by avibootz

Related questions

3 answers 215 views
3 answers 173 views
3 answers 185 views
2 answers 175 views
4 answers 232 views
3 answers 199 views
199 views asked Sep 7, 2022 by avibootz
2 answers 154 views
...