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

Why do return and print statements in for-loop don't work together in Python?

Can you please explain why does this function prints -1 only once, when it has to print it on each loop cycle? However, when I remove line 9 return -1, it prints -1 4 times, as it should be. How does it work?

def find_index(to_search, target):
    enum_tuple = tuple(enumerate(to_search))
    # print(enum_tuple)
    for i, value in enum_tuple:
        if value == target:
            break
        else: 
            print(-1)
            return -1
    return i

my_list = ["Rick", "Amy", "Jack", "Mary"]

index_location = find_index(my_list, "Tom")

>Solution :

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

This happens because when you reach line 9 return -1 you are exiting the function find_index so the loop won’t continue running.

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