Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading