循环结束时会发生什么?

2024-10-02 00:33:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python初学者,没有编程知识。我为这个题目的名字道歉,但我实在做不出更好的题目。 我想要的是:

letter = "w"   # search for this letter in the list bellow
listL = ["z","b","y","a","c"]

for let in listL:
    if let == letter:
        print "found it"
        break
    else:
        if  let == listL[-1]:
            print "nope can't find it"
        continue

我有一个字母列表,我想在列表中搜索一个特定的字母。 如果我找到了这封信,那么一切正常,for循环应该停止。 如果找不到,我希望循环停止当前的迭代,并尝试使用列表中的下一个字母。如果列表中没有一个字母有特定的字母,那么它应该打印“不,找不到”。你知道吗

上面的代码起作用。但我想知道这个能不能写清楚一点?而我所说的显然不是“先进”的意思,而是学者之道,书法之例。你知道吗

谢谢你。你知道吗


Tags: in列表forsearchif编程字母it
3条回答

只需在中使用

if let in listL:
    print("Found it")
else:
    print("Not found")

编辑:你快了30秒,恭喜你;)

就这样吧:

if letter in listL:
    print "found it"
else:
    print "nope..."

Python为for循环提供了一个else语句,如果循环结束而没有中断,则执行该语句:

for let in llistL:
    if let == letter:
        print("Found it!")
        break
else:
    print("nope could'nt find it")

这将是for循环的“学者之道”,然而,如果您只是测试列表中元素的存在性,那么Arkady的答案就是接下来的答案。你知道吗

相关问题 更多 >

    热门问题