Python break outside loop error question.

Asked 2 years ago, Updated 2 years ago, 23 views

As many as the number of count, I want to output integers except 0 in b.
However, if you put break in the sys.exit(0) position, an error called break outside loop is displayed...
I want to know how to use break and solve it.

import sys

count=int(input())
b=input().split()

if count<len(b):
    sys.exit(0)

for n in b:
    if int(n)==0:
        break
    else:
        print(n)

python

2022-09-21 10:01

1 Answers

You can only memorize break under for or while. That's why "break outside loop" is an error.

First of all, the following code works.

count = int(input('count = '))
b = input('b = ') # No need to split()

if count >= len(b):
    For n in b: # where b is a string, n becomes one character
        if n != '0':
            print(n)

However, if you need to stop when count < len(b), you can wrap it appropriately with a function.

def printAnythingButZero(count, b):
    if count < len(b):
        return False
    else:
        for n in b:
            if n != '0':
                print(n)
        return True

count = int(input('count = '))
b = input('b = ')
printAnythingButZero(count, b)


2022-09-21 10:01

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.