简体   繁体   中英

Python3: for-loop break and else (if statement)

Background information:

hey, I want to do the following: I have a dictionary with IDs as keys and lists with various things as value. One of the items of the value is a string . I want to check, if a list contains this string . And I want to do it for all keys in my dictionary.

  • If the list contains the string, I want to print "String is valid"
  • If the list does not contain the string, I want to print "String is NOT valid"

So far, so good.

Furthermore, the lists I want to check depend on one console input of the user, which specifies, which list should be checked. The console input is "number" .

My idea was to iterate over my dictionary and my list with a nested for-loop and compare, if the string(the item of the value) is equal to any list item. If it is, I want to break out of the loop. If the String is not found in the list, I want to execute the else-statement to print my "String is not valid" message.

Code snippet:

def validationHelper(myDict, myList):
        for key in myDict:
            for value in myDict[key][0]:
                for item in myList:
                    if value==item:
                        validationHelper.true="String is valid"
                        break
                else:
                    validationHelper.true="Warning: String is NOT valid"

def validation(anyList,helperfunc):
    if anyList=="one":
        return helperfunc(finalDict,myList1)
    if anyList=="two":
         return helperfunc(finalDict,myList2)
    if anyList=="three":
         return helperfunc(finalDict,myList3)

validation(number, validationHelper)

print(validationHelper.true)

Problem:

I am running this, but no matter if the string is in the list or not, I always get my printout for the else-statement. So, I guess I have an error in reasoning in my for-loop? Or maybe, I did not understand for-loops at all?! I have tried out different indentions with the else-statement, but couldnt solve my problem.

I would suggest you to change your function the following way (without changing the logic):

def validationHelper(myDict, myList):
    for key in myDict:
        for value in myDict[key][0]:
            for item in myList:
                if value==item:
                    return "String is valid" # Add here to exit
    return "Warning: String is NOT valid" # will be returned inf nothing will be found in your 3 loops

def validation(anyList,helperfunc):
    if anyList=="one":
        return helperfunc(finalDict,myList1)
    if anyList=="two":
         return helperfunc(finalDict,myList2)
    if anyList=="three":
         return helperfunc(finalDict,myList3)

validation(number, validationHelper)

print(validationHelper)

This will help you to exit your 3 nested loops as it was mentioned in comments.
Because in the negative case on first wrong occurrence you don't need to check anything else.

Use return to break all of your loop. Having an else statement is not necessary if you don't have any if statement to begin with.

def validationHelper(myDict, myList):
    for item in myList:
        if item in myDict.values():
            return ("String is valid")
    return ("String is NOT valid")

def validation(anyList,helperfunc):
    if anyList=="one":
        return helperfunc(finalDict,myList1)
    elif anyList=="two":
        return helperfunc(finalDict,myList2)
    elif anyList=="three":
        return helperfunc(finalDict,myList3)

validation(number, validationHelper)

print(validationHelper.true)

Using elif instead of multiple if is a better practice. Be careful with indentions next time.

Also you might want to check .keys() and .values()

You can replace:

for key in myDict:
    for value in myDict[key][0]:

with:

for value in myDict.values():

The other answers give a good explanation of how to break out of multiple loops. But you could also simplify your code by using Python's built-in functions and list comprehensions, like this:

def validationHelper(myDict, myList):
    if any(v in myList for val in myDict.values() for v in val[0]):
        validationHelper.true="String is valid"
    else:
        validationHelper.true="Warning: String is NOT valid"

def validation(anyList,helperfunc):
    if anyList=="one":
        return helperfunc(finalDict,myList1)
    if anyList=="two":
         return helperfunc(finalDict,myList2)
    if anyList=="three":
         return helperfunc(finalDict,myList3)

validation(number, validationHelper)

print(validationHelper.true)

This should be as efficient as your code, since any short circuits at the first match. And it may be a little more readable. (Note that multi-level list comprehensions go in the same order as regular for loops.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM