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)
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)
© 2024 OneMinuteCode. All rights reserved.