Home > Software design >  Different behavior of a loop in a function when else clause is added
Different behavior of a loop in a function when else clause is added

Time:12-29

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?

CodePudding user response:

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
  • Related