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

Question:

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:

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

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

Asked By: AbreQueVoy

||

Answers:

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
Answered By: CodeKorn
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.