I am python beginner, with no previous programming knowledge. I apologize for the name of the topic, but I simply could not make a better one. Here is what I want:

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

I have a list of letters, and I want to search for a particular letter in that list. If I find the letter, then everything is ok, and the for loop should stop. If I do not find it, I would like the loop to stop that current iteration, and try with the next letter in the list. If not a single letter in the list has that particular letter, then it should print "nope can't find it".

The upper code works. But I was wondering if this could be wrote a bit clearly? And by clearly I do not mean "advanced", but scholar way, an-example-from-the-book way.

Thank you.

有帮助吗?

解决方案

Python offers an else statement for the for loop that is executed if the loop ends without being broken:

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

That would be the "scholar way" for a for loop, however if you just test the presence of an element in a list, Arkady's answer is the one to follow.

其他提示

How about just:

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

Simply use in

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

edit : you were faster by 30 s, congrats ;)

Your loop will keep looping until it either breaks (found it!) or the list is exhausted. You do not need to do anything special to "stop that current iteration, and try with the next letter in the list". We don't need a continue when a letter doesn't match, this will happen automatically as long as there are more letters to check.

We only want to display "nope can't find it" after we've searched through the entire list, so we don't need to check until the end. This else statement corresponds to the for loop, instead of the if in your previous code.

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 #found letter stop search
else: #loop is done, didn't find matching letter in all of list
  print "nope can't find it"

There is actually a for: else: construct in Python, where the else runs if the for loop doesn't break:

for let in listL:
    if let == letter:
        print("Found it")
        break
else:
    print("Not found")

Alternatively, you can use list.index, which will give the index of an item if found in a list and raise a ValueError if it isn't found:

try:
    index = listL.index(letter)
except ValueError:
    print("Not found")
else:
    print("Found it")
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top