我可以在python中使用子函数的continue语句吗?

我可以在python中使用子函数的continue语句吗?,python,Python,为了澄清我想做什么,我修改了这个问题 def main(): for i in range(10): sub1(i) sub2(i) def sub1(i): if i == 5: continue else: print(f'hello world from sub1') def sub2(i): print(f'hello world from sub2') if __name__ == '__main__': main

为了澄清我想做什么,我修改了这个问题

def main(): 
  for i in range(10): 
    sub1(i)
    sub2(i)
 
def sub1(i):
  if i == 5: 
    continue 
  else: 
    print(f'hello world from sub1')

def sub2(i):
  print(f'hello world from sub2')

if __name__ == '__main__': 
  main()
我想在5岁时跳过sub2

当我运行这个脚本时,我得到了
SyntaxError的错误:“continue”在循环中不正确
。可以从子函数调用continue语句吗?有没有其他方法可以做到这一点

由于可读性,我想使用此语法。

为什么不:

def main(): 
  for i in range(10): 
    sub(i)

def sub(i):
  if i != 5: 
    print(f'hello world!')

正如我在评论中提到的,您可以提前从内部函数返回
,如果您有许多地方需要停止执行,这也很有用,例如

def main(): 
  for i in range(10): 
    sub(i)

def sub(i):
  if i == 5: return
  print(f'hello world!')
  if i < 10: return
  print('wow a big number')

为了满足您的好奇心,我将为您的确切问题提供一个变通方法:

def main(): 
  for i in range(10): 
    if sub1(i):
      sub2(i)
 
def sub1(i):
  if i == 5: 
    return False 
  print(f'hello world from sub1')
  return True

def sub2(i):
  print(f'hello world from sub2')

修改if语句以包含除i为5时以外的所有内容,然后从sub1中调用sub2

def main(): 
  for i in range(10): 
    sub1(i)
    
 
def sub1(i):
  if i != 5: 
    print(f'hello world from sub1')
    sub2(i)


def sub2(i):
  print(f'hello world from sub2')

if __name__ == '__main__': 
  main()

Continue语句,您必须在循环中直接使用它

continue语句允许您跳过触发外部条件的循环部分,但可以继续完成循环的其余部分。也就是说,循环的当前迭代将被中断,但程序将返回到循环的顶部

continue语句将位于loop语句下的代码块内,通常位于条件if语句之后

使用与上面Break语句部分相同的for循环程序,我们将使用continue语句而不是Break语句:

number = 0

for number in range(10):
    if number == 5:
        continue    # continue here

    print('Number is ' + str(number))

print('Out of loop')
使用continue语句而不是break语句的区别在于,当变量数被计算为等于5时,我们的代码将继续运行,尽管中断。让我们看看我们的输出:

Output
Number is 0
Number is 1
Number is 2
Number is 3
Number is 4
Number is 6
Number is 7
Number is 8
Number is 9
Out of loop
在这里,输出中从未出现数字为5,但循环在该点之后继续打印数字6-10的行,然后离开循环

您可以使用continue语句来避免深度嵌套的条件代码,或者通过消除希望拒绝的频繁发生的情况来优化循环


continue语句使程序跳过循环中出现的某些因素,然后继续执行循环的其余部分。

您不能完全按照所示执行。但是您可以从函数返回(
return
而不是
continue
),这样您的内部函数将结束,
main
中的新迭代将开始感谢您的回答。我稍微修改了一下这个问题。当我5岁时,我想从sub1函数跳过sub2。我该怎么做?不会运行,
continue
在loopSorry-yep之外被调用,这意味着也修改了if语句。我修改了代码,谢谢。这个答案是处理这个问题的最佳选择。谢谢你的评论和回答。
Output
Number is 0
Number is 1
Number is 2
Number is 3
Number is 4
Number is 6
Number is 7
Number is 8
Number is 9
Out of loop