gpt4 book ai didi

Python 通过与继续

转载 作者:行者123 更新时间:2023-12-03 23:49:16 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Is there a difference between `continue` and `pass` in a for loop in python?

(12 个回答)


3年前关闭。




我是 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什么都不做,有助于处理一些语法错误,例如:

 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

关于Python 通过与继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33335740/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com