【问题标题】:Python pass vs. continue [duplicate]Python传递与继续[重复]
【发布时间】:2016-01-24 23:04:42
【问题描述】:

我是 Python 新手,不知道下面的语法,

item = [0,1,2,3,4,5,6,7,8,9]
for element in item:
      if not element:
          pass
      print(element)

这给了我所有这些元素,这是有道理的,因为 Pass 是跳过这一步到下一个

但是,如果我使用 continue 我会得到以下内容

item = [0,1,2,3,4,5,6,7,8,9]
for element in item:
      if not element:
          continue
      print(element)
[1,2,3,4,5,6,7,8,9]

谁能告诉我为什么我没有得到“0”? 0 不在列表中吗?

【问题讨论】:

  • continue 跳过循环体的其余部分并继续循环的下一次迭代。 pass 什么都不做。
  • 除了已回答的pass/continue 难题之外,您还想达到什么目的?可能有更好的方法来扫描列表并产生所需的输出(例如filter(None, item)

标签: python


【解决方案1】:

continue 跳过它后面的语句,而pass 不做类似的事情。实际上pass 什么都不做,对处理一些语法错误很有用:

 if(somecondition):  #no line after ":" will give you a syntax error

您可以通过以下方式处理它:

 if(somecondition):
     pass   # Do nothing, simply jumps to next line 

演示:

while(True):
    continue
    print "You won't see this"

这将跳过print 语句并且不打印任何内容。

while(True):
    pass
    print "You will see this" 

这将继续打印You will see this

【讨论】:

    【解决方案2】:
    • “通过”仅表示“不操作”。它什么也没做。
    • “继续”中断循环并跳转到循环的下一次迭代
    • "not 0" 是 True,所以你的 element=0 的 "if not element" 会触发 continue 指令,直接跳转到下一次迭代:element = 1

    【讨论】:

      【解决方案3】:

      pass 是空操作。它什么也不做。所以当not element 为真时,Python 什么都不做,继续运行。您也可以省略整个 if 测试,以了解此处所做的不同。

      continue 表示:跳过循环体的其余部分并进入下一次迭代。因此,当not element 为真时,Python 会跳过循环的其余部分(print(element) 行),并继续进行下一次迭代。

      not elementelement 为 0 时为真;见Truth Value Testing

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-10
        • 2019-01-01
        • 1970-01-01
        • 2016-01-01
        • 2021-08-30
        相关资源
        最近更新 更多