let's say,
def sample():
if a==1:
print(a)
else:
continue
for i in language:
a=i
sample()
I want to use this function in a loop, but the "continue" command gives me an error because there is no loop. What can I do?
CodePudding user response:
Return a boolean from the function and based on the return value make continue or not because continue must be within a loop
CodePudding user response:
continue
keyword in python is only available in for
or while
loops. Also block defined variables like a
are not available on the global scope.
I don't know what you want to achieve but assuming your code, you want to extract a condition into a function, something like this:
def condition(a):
return a == 1
def sample(a):
print(a)
for i in language:
a=i
if condition(a):
sample(a)
else:
continue
CodePudding user response:
It is because the scope of the function doesn't know we are in a loop. You have to put the continue keyword inside the loop
CodePudding user response:
continue
keyword cannot be used inside a function. It must be inside the loop. There is a similar question here. Maybe you can do something like the following.
language = [1,1,1,2,3]
a = 1
def sample():
if a == 1:
print(a)
return False
else:
return True
for i in language:
if sample():
continue
else:
a = i
OR something like this:
language = [1,1,1,2,3]
a = 1
def gen(base):
for item in base:
if a == 1:
yield a
else:
continue
for i in gen(language):
a = i
print(a)