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

Different behavior of a loop in a function when else clause is added

There’s a simple function:

users = [
    (['bmiller', 'Miller, Brett'], 'Brett Miller'),
    (['Gianni Tina', 'tgiann', 'tgianni'], 'Tina Gianni'),
    (['mplavis', 'marcusp', 'Plavis, Marcus'], 'Marcus Plavis')
]


def replace_user_login_with_name(login):
    name = ''
    for u in users:
        if login in u[0]:
            name = str(login).replace(login, u[1])
        else:                  # without these lines
            name = str(login)  # it works fine

    return name

It was working just fine, replacing logins with full names of users when executed without the else clause (marked with the comments in the markup above):

full_name = replace_user_login_with_name('bmiller')
print(full_name)
# 'Brett Miller'

But after adding the else clause to just return user’s login when given user is not present in the users array, all entries are returned as logins, so:

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

full_name = replace_user_login_with_name('bmiller')
print(full_name)
# 'bmiller'

Why the else clause gets executed even if logins are matched?

>Solution :

Return name after a match is found:

users = [
    (['bmiller', 'Miller, Brett'], 'Brett Miller'),
    (['Gianni Tina', 'tgiann', 'tgianni'], 'Tina Gianni'),
    (['mplavis', 'marcusp', 'Plavis, Marcus'], 'Marcus Plavis')
]


def replace_user_login_with_name(login):
    name = ''
    for u in users:
        if login in u[0]:
            name = str(login).replace(login, u[1])
            return name
        else:                  # without these lines
            name = str(login)  # it works fine

    return name
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