Home > Mobile >  Python Function doesn't returns correct value while calling from for loop
Python Function doesn't returns correct value while calling from for loop

Time:09-14

Ok guys I have this following Python script

myDict = {
    "a":1,
    "b":2,
    "c":3
}


def get_ky(val):
    for key, value in myDict.items():
        if val == value:
            return key
        else:
            return "no match"


myList = [1,2,3]


for i in myList:
    print(get_ky(i))

and got this result

a
no match
no match

I want to know why it printed correct result at first iteration and "no match" at the consecutive iteration. please help me to understand this. Also this my first question, if I got something wrong please don't kill me.

CodePudding user response:

The reason why it is not working for you:

Step 1: when you pass the i=1, then it checks the 1==1, which is true and returns the key a

Step 2: When you send i=2, then it checks the 2==1 which is false so it will jump to the else block and return "no match"(here it will not iterate for other values of the myDict)

Step 2: Same thing is happening here also like Step 2.

So you need to do it this way, if it is not matched after the whole myDict then return "no match"

myDict = {
    "a":1,
    "b":2,
    "c":3
}


def get_ky(val):
    for key, value in myDict.items():
        if val == value:
            return key
    return "no match"

myList = [1,2,3]

for i in myList:
    print(get_ky(i))

You can also visualize yourself what is happening behind the scene step by step here at pythontutor.com

CodePudding user response:

You want to use else on the for loop:

myDict = {"a": 1, "b": 2, "c": 3}


def get_ky(val):
    for key, value in myDict.items():
        if val == value:
            return key
    else:
        return "no match"


myList = [1, 2, 3, 4]

for i in myList:
    print(get_ky(i))

Out:

a
b
c
no match
  • Related