标签归档:continue

在Python中使用“ continue”语句的示例?

问题:在Python中使用“ continue”语句的示例?

定义中的continue语句是:

continue语句从循环的下一个迭代继续。

我找不到任何好的代码示例。

有人可以在continue必要时提出一些简单的案例吗?

The definition of the continue statement is:

The continue statement continues with the next iteration of the loop.

I can’t find any good examples of code.

Could someone suggest some simple cases where continue is necessary?


回答 0

这是一个简单的例子:

for letter in 'Django':    
    if letter == 'D':
        continue
    printf("Current Letter: {letter}")

输出将是:

Current Letter: j
Current Letter: a
Current Letter: n
Current Letter: g
Current Letter: o

它继续到循环的下一个迭代。

Here’s a simple example:

for letter in 'Django':    
    if letter == 'D':
        continue
    print("Current Letter: " + letter)

Output will be:

Current Letter: j
Current Letter: a
Current Letter: n
Current Letter: g
Current Letter: o

It continues to the next iteration of the loop.


回答 1

我喜欢使用continue in loops,在您陷入“倒闭”之前,要完成许多竞争。因此,而不是像这样的代码:

for x, y in zip(a, b):
    if x > y:
        z = calculate_z(x, y)
        if y - z < x:
            y = min(y, z)
            if x ** 2 - y ** 2 > 0:
                lots()
                of()
                code()
                here()

我得到这样的代码:

for x, y in zip(a, b):
    if x <= y:
        continue
    z = calculate_z(x, y)
    if y - z >= x:
        continue
    y = min(y, z)
    if x ** 2 - y ** 2 <= 0:
        continue
    lots()
    of()
    code()
    here()

通过这种方式,我避免了嵌套很深的代码。另外,通过先消除最常发生的情况来优化循环很容易,因此,当没有其他显示异常时,我只需要处理不常见但很重要的情况(例如,除数为0)。

I like to use continue in loops where there are a lot of contitions to be fulfilled before you get “down to business”. So instead of code like this:

for x, y in zip(a, b):
    if x > y:
        z = calculate_z(x, y)
        if y - z < x:
            y = min(y, z)
            if x ** 2 - y ** 2 > 0:
                lots()
                of()
                code()
                here()

I get code like this:

for x, y in zip(a, b):
    if x <= y:
        continue
    z = calculate_z(x, y)
    if y - z >= x:
        continue
    y = min(y, z)
    if x ** 2 - y ** 2 <= 0:
        continue
    lots()
    of()
    code()
    here()

By doing it this way I avoid very deeply nested code. Also, it is easy to optimize the loop by eliminating the most frequently occurring cases first, so that I only have to deal with the infrequent but important cases (e.g. divisor is 0) when there is no other showstopper.


回答 2

通常情况下,需要继续/有用的情况是当您想跳过循环中的其余代码并继续迭代时。

我真的不认为这是必要的,因为您可以始终使用if语句来提供相同的逻辑,但是对于提高代码的可读性可能会很有用。

Usually the situation where continue is necessary/useful, is when you want to skip the remaining code in the loop and continue iteration.

I don’t really believe it’s necessary, since you can always use if statements to provide the same logic, but it might be useful to increase readability of code.


回答 3

import random  

for i in range(20):  
    x = random.randint(-5,5)  
    if x == 0: continue  
    print 1/x  

继续是一个非常重要的控制声明。上面的代码表示一种典型的应用,其中可以避免除以零的结果。当我需要存储程序的输出时,我经常使用它,但是如果程序崩溃,我不想存储输出。请注意,要测试上面的示例,请用print 1 / float(x)替换最后一个语句,否则只要有小数,您就会得到零,因为randint返回一个整数。为了清楚起见,我省略了它。

import random  

for i in range(20):  
    x = random.randint(-5,5)  
    if x == 0: continue  
    print 1/x  

continue is an extremely important control statement. The above code indicates a typical application, where the result of a division by zero can be avoided. I use it often when I need to store the output from programs, but dont want to store the output if the program has crashed. Note, to test the above example, replace the last statement with print 1/float(x), or you’ll get zeros whenever there’s a fraction, since randint returns an integer. I omitted it for clarity.


回答 4

有人对可读性发表了评论,说:“哦,它对可读性的帮助不大,谁在乎呢?”

假设您需要在主代码之前进行检查:

if precondition_fails(message): continue

''' main code here '''

请注意,您可以在之后执行此操作在编写主代码而无论如何都不会更改该代码。如果您区分代码,因为主代码没有间距变化,因此只会突出显示带有“继续”的添加行。

试想一下,如果您必须对生产代码进行断点修补,那么结果发现这仅仅是在添加一个行,并继续。显而易见,这是您查看代码时唯一的更改。如果您开始将主代码包装在if / else中,则diff将突出显示新缩进的代码,除非您忽略间距更改,这在Python中尤其危险。我认为除非您一直处于必须在短时间内推出代码的情况,否则您可能不会完全理解这一点。

Some people have commented about readability, saying “Oh it doesn’t help readability that much, who cares?”

Suppose you need a check before the main code:

if precondition_fails(message): continue

''' main code here '''

Note you can do this after the main code was written without changing that code in anyway. If you diff the code, only the added line with “continue” will be highlighted since there are no spacing changes to the main code.

Imagine if you have to do a breakfix of production code, which turns out to simply be adding a line with continue. It’s easy to see that’s the only change when you review the code. If you start wrapping the main code in if/else, diff will highlight the newly indented code, unless you ignore spacing changes, which is dangerous particularly in Python. I think unless you’ve been in the situation where you have to roll out code on short notice, you might not fully appreciate this.


回答 5

def filter_out_colors(elements):
  colors = ['red', 'green']
  result = []
  for element in elements:
    if element in colors:
       continue # skip the element
    # You can do whatever here
    result.append(element)
  return result

  >>> filter_out_colors(['lemon', 'orange', 'red', 'pear'])
  ['lemon', 'orange', 'pear']
def filter_out_colors(elements):
  colors = ['red', 'green']
  result = []
  for element in elements:
    if element in colors:
       continue # skip the element
    # You can do whatever here
    result.append(element)
  return result

  >>> filter_out_colors(['lemon', 'orange', 'red', 'pear'])
  ['lemon', 'orange', 'pear']

回答 6

假设我们要打印所有不是3和5的倍数的数字

for x in range(0, 101):
    if x % 3 ==0 or x % 5 == 0:
        continue
        #no more code is executed, we go to the next number 
    print x

Let’s say we want to print all numbers which are not multiples of 3 and 5

for x in range(0, 101):
    if x % 3 ==0 or x % 5 == 0:
        continue
        #no more code is executed, we go to the next number 
    print x

回答 7

这不是绝对必要的,因为它可以使用IF来完成,但是它更具可读性,并且运行时成本更低。

如果数据不符合某些要求,我将其用于跳过循环中的迭代:

# List of times at which git commits were done.
# Formatted in hour, minutes in tuples.
# Note the last one has some fantasy.
commit_times = [(8,20), (9,30), (11, 45), (15, 50), (17, 45), (27, 132)]

for time in commit_times:
    hour = time[0]
    minutes = time[1]

    # If the hour is not between 0 and 24
    # and the minutes not between 0 and 59 then we know something is wrong.
    # Then we don't want to use this value,
    # we skip directly to the next iteration in the loop.
    if not (0 <= hour <= 24 and 0 <= minutes <= 59):
        continue

    # From here you know the time format in the tuples is reliable.
    # Apply some logic based on time.
    print("Someone commited at {h}:{m}".format(h=hour, m=minutes))

输出:

Someone commited at 8:20
Someone commited at 9:30
Someone commited at 11:45
Someone commited at 15:50
Someone commited at 17:45

如您所见,在continue语句后没有出现错误的值。

It is not absolutely necessary since it can be done with IFs but it’s more readable and also less expensive in run time.

I use it in order to skip an iteration in a loop if the data does not meet some requirements:

# List of times at which git commits were done.
# Formatted in hour, minutes in tuples.
# Note the last one has some fantasy.
commit_times = [(8,20), (9,30), (11, 45), (15, 50), (17, 45), (27, 132)]

for time in commit_times:
    hour = time[0]
    minutes = time[1]

    # If the hour is not between 0 and 24
    # and the minutes not between 0 and 59 then we know something is wrong.
    # Then we don't want to use this value,
    # we skip directly to the next iteration in the loop.
    if not (0 <= hour <= 24 and 0 <= minutes <= 59):
        continue

    # From here you know the time format in the tuples is reliable.
    # Apply some logic based on time.
    print("Someone commited at {h}:{m}".format(h=hour, m=minutes))

Output:

Someone commited at 8:20
Someone commited at 9:30
Someone commited at 11:45
Someone commited at 15:50
Someone commited at 17:45

As you can see, the wrong value did not make it after the continue statement.


回答 8

例如,如果您想根据变量的值做不同的事情:

my_var = 1
for items in range(0,100):
    if my_var < 10:
        continue
    elif my_var == 10:
        print("hit")
    elif my_var > 10:
        print("passed")
    my_var = my_var + 1

在上面的示例中,如果使用break解释器,则将跳过循环。但是使用continue它仅跳过if-elif语句并直接转到循环的下一项。

For example if you want to do diferent things depending on the value of a variable:

my_var = 1
for items in range(0,100):
    if my_var < 10:
        continue
    elif my_var == 10:
        print("hit")
    elif my_var > 10:
        print("passed")
    my_var = my_var + 1

In the example above if I use break the interpreter will skip the loop. But with continueit only skips the if-elif statements and go directly to the next item of the loop.


回答 9

continue 只需跳过循环中的其余代码,直到下一次迭代

continue simply skips the rest of the code in the loop until next iteration


python的for循环中的`continue`和`pass`之间有区别吗?

问题:python的for循环中的`continue`和`pass`之间有区别吗?

两个python关键字之间是否有任何显着差异continuepass如示例中所示

for element in some_list:
    if not element:
        pass

for element in some_list:
    if not element:
        continue

我应该知道吗?

Is there any significant difference between the two python keywords continue and pass like in the examples

for element in some_list:
    if not element:
        pass

and

for element in some_list:
    if not element:
        continue

I should be aware of?


回答 0

是的,他们做的事情完全不同。 pass只是不执行任何操作,而continue继续进行下一个循环迭代。在您的示例中,如果您在if:之后添加了另一个语句,则区别将变得显而易见pass。之后continue,就不会了。

>>> a = [0, 1, 2]
>>> for element in a:
...     if not element:
...         pass
...     print element
... 
0
1
2
>>> for element in a:
...     if not element:
...         continue
...     print element
... 
1
2

Yes, they do completely different things. pass simply does nothing, while continue goes on with the next loop iteration. In your example, the difference would become apparent if you added another statement after the if: After executing pass, this further statement would be executed. After continue, it wouldn’t.

>>> a = [0, 1, 2]
>>> for element in a:
...     if not element:
...         pass
...     print element
... 
0
1
2
>>> for element in a:
...     if not element:
...         continue
...     print element
... 
1
2

回答 1

是,有一点不同。continue强制循环从下一次迭代开始,而pass意味着“此处没有代码要执行”,并将继续执行其余部分或循环体。

运行这些,看看有什么区别:

for element in some_list:
    if not element:
        pass
    print 1 # will print after pass

for element in some_list:
   if not element:
       continue
   print 1 # will not print after continue

Yes, there is a difference. continue forces the loop to start at the next iteration while pass means “there is no code to execute here” and will continue through the remainder or the loop body.

Run these and see the difference:

for element in some_list:
    if not element:
        pass
    print 1 # will print after pass

for element in some_list:
   if not element:
       continue
   print 1 # will not print after continue

回答 2

continue 将跳回到循环的顶部。 pass将继续处理。

如果pass在循环的末尾,则差异可以忽略不计,因为流量始终会回到循环的顶部。

continue will jump back to the top of the loop. pass will continue processing.

if pass is at the end for the loop, the difference is negligible as the flow would just back to the top of the loop anyway.


回答 3

在您的示例中,这没有什么区别,因为两个语句都出现在循环的末尾。pass只是一个占位符,它什么都不做(它将执行传递给下一条语句)。continue另一方面,它有一个明确的目的:它告诉循环继续,就像刚刚重新启动一样。

for element in some_list:
    if not element:
        pass
    print element  

for element in some_list:
    if not element:
        continue
    print element

In your example, there will be no difference, since both statements appear at the end of the loop. pass is simply a placeholder, in that it does nothing (it passes execution to the next statement). continue, on the other hand, has a definite purpose: it tells the loop to continue as if it had just restarted.

for element in some_list:
    if not element:
        pass
    print element  

is very different from

for element in some_list:
    if not element:
        continue
    print element

回答 4

它们之间是有区别的,
continue跳过循环的当前迭代并执行下一个迭代。
pass什么也没做。这是一个空语句占位符。
我想给你一个例子,这将更好地阐明这一点。

>>> for element in some_list:
...     if element == 1:
...         print "Pass executed"
...         pass
...     print element
... 
0
Pass executed
1
2

>>> for element in some_list:
...     if element == 1:
...         print "Continue executed"
...         continue
...     print element
... 
0
Continue executed
2

There is a difference between them,
continue skips the loop’s current iteration and executes the next iteration.
pass does nothing. It’s an empty statement placeholder.
I would rather give you an example, which will clarify this more better.

>>> for element in some_list:
...     if element == 1:
...         print "Pass executed"
...         pass
...     print element
... 
0
Pass executed
1
2

>>> for element in some_list:
...     if element == 1:
...         print "Continue executed"
...         continue
...     print element
... 
0
Continue executed
2

回答 5

是,有一点不同。Continue实际上跳过了循环的当前迭代的其余部分(返回到开头)。Pass是不执行任何操作的空白语句。

查看python文档

Yes, there is a difference. Continue actually skips the rest of the current iteration of the loop (returning to the beginning). Pass is a blank statement that does nothing.

See the python docs


回答 6

在那些例子中,没有。如果该语句不是循环中的最后一条语句,那么它们将产生非常不同的效果。

In those examples, no. If the statement is not the very last in the loop then they have very different effects.


回答 7

在for循环中通过和继续之间的区别:

那么为什么要传入python呢?

如果要创建一个空的类,方法或块。

例子:

class MyException(Exception):
    pass


try:
   1/0
 except:
   pass

在上面的示例中如果没有“ pass”,将抛出IndentationError。

Difference between pass and continue in a for loop:

So why pass in python?

If you want to create a empty class, method or block.

Examples:

class MyException(Exception):
    pass


try:
   1/0
 except:
   pass

without ‘pass’ in the above examples will throw IndentationError.


回答 8

x = [1,2,3,4] 
for i in x:
    if i==2:
         pass  #Pass actually does nothing. It continues to execute statements below it.
         print "This statement is from pass."
for i in x:
    if i==2:
         continue #Continue gets back to top of the loop.And statements below continue are executed.
         print "This statement is from continue."

输出是

>>> This statement is from pass.

再次,让我们运行相同的代码进行较小的更改。

x = [1,2,3,4]
for i in x:
    if i==2:
       pass  #Pass actually does nothing. It continues to execute statements below it.
    print "This statement is from pass."
for i in x:
    if i==2:
        continue #Continue gets back to top of the loop.And statements below continue are executed.
    print "This statement is from continue."

输出是-

>>> This statement is from pass.
This statement is from pass.
This statement is from pass.
This statement is from pass.
This statement is from continue.
This statement is from continue.
This statement is from continue.

通过不执行任何操作。计算不受影响。但是继续返回到循环的顶部进行下一步计算。

x = [1,2,3,4] 
for i in x:
    if i==2:
         pass  #Pass actually does nothing. It continues to execute statements below it.
         print "This statement is from pass."
for i in x:
    if i==2:
         continue #Continue gets back to top of the loop.And statements below continue are executed.
         print "This statement is from continue."

The output is

>>> This statement is from pass.

Again, let run same code with minor changes.

x = [1,2,3,4]
for i in x:
    if i==2:
       pass  #Pass actually does nothing. It continues to execute statements below it.
    print "This statement is from pass."
for i in x:
    if i==2:
        continue #Continue gets back to top of the loop.And statements below continue are executed.
    print "This statement is from continue."

The output is –

>>> This statement is from pass.
This statement is from pass.
This statement is from pass.
This statement is from pass.
This statement is from continue.
This statement is from continue.
This statement is from continue.

Pass doesn’t do anything. Computation is unaffected. But continue gets back to top of the loop to procced with next computation.


回答 9

这样考虑:

通过: Python只能在缩进上工作!与其他语言不同,没有空的花括号。

因此,如果您不希望在条件为真的情况下不执行任何操作,则除了pass之外没有其他选择。

继续:仅在循环的情况下才有用。如果对于一定范围的值,您不想在该特定遍次的条件为真之后执行循环的其余语句,则必须使用continue。

Consider it this way:

Pass: Python works purely on indentation! There are no empty curly braces, unlike other languages.

So, if you want to do nothing in case a condition is true there is no option other than pass.

Continue: This is useful only in case of loops. In case, for a range of values, you don’t want to execute the remaining statements of the loop after that condition is true for that particular pass, then you will have to use continue.


回答 10

pass当您需要一些空函数,类或循环以用于将来的实现,而无需执行任何代码时,可以在场景中使用它。
continue用于在循环中未满足某些条件且没有条件且您需要跳过当前迭代并移至下一个迭代的场景中使用。

pass could be used in scenarios when you need some empty functions, classes or loops for future implementations, and there’s no requirement of executing any code.
continue is used in scenarios when no when some condition has met within a loop and you need to skip the current iteration and move to the next one.