调用dev时中断for循环

时间:2018-07-22 17:54:10

标签: python python-3.x

我的代码如下:

as.numeric(as.factor(x))

def a(num): #if num == 2, then want to skip running b() and go on to next loop if a == 2: # i have tried break, pass and continue there # pass and continue return an error (SyntaxError: 'pass/continue' not properly in loop) def b(num): print('b:' str(num)) for x in range(1,10): a(x) b(x) 为2时,如何跳过运行b()?我尝试过numpasscontinue,但是没有任何线索。


感谢您的大力帮助。我最终使用break使之成为可能。谢谢队友!

3 个答案:

答案 0 :(得分:3)

  for x in range(1,10):
    a(x)
    if x != 2:
        b(x)

答案 1 :(得分:0)

break 语句不同(终止循环),有一个 continue 语句可跳过当前迭代并继续下一个迭代。

这是代码。

def a(num):
    print('a:', str(num))

def b(num):
    print('b:', str(num))

for x in range(1,10):
    if x == 2:
        continue
    a(x)
    b(x)

输出»

a: 1
b: 1
a: 3
b: 3
a: 4
b: 4
a: 5
b: 5
a: 6
b: 6
a: 7
b: 7
a: 8
b: 8
a: 9
b: 9

答案 2 :(得分:0)

breakcontinue在同一范围内作用于封闭循环。这意味着您无法在调用函数的块中编写循环,而无法在调用的函数中编写中断。语言不允许。句号。

您可以从函数返回一个值并对其进行测试,也可以引发异常并对其进行捕获。这是异常用法的示例:

class SkipException(Exception):
    pass

def a(num):
    if num == 2:
        raise SkipException

def b(num):
    print('b:', str(num))

for x in range(1, 10):
    try:
        a(x)
        b(x)
    except SkipException:
        pass

它给出了预期的结果:

b: 1
b: 3
b: 4
b: 5
b: 6
b: 7
b: 8
b: 9