Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.5k views
in Technique[技术] by (71.8m points)

python - Understanding my case insensitive list comparison

I'm working through the Python Crash Course book. I was doing one of the exercises that I mostly managed to figure out. There is just one bit of code that I can't seem to get.

The exercise:

Compare two lists, one of current_users one of new_users. Make sure they are case insensitive.

I want to know why when I convert current_users to lowercase, is 'andy657' still being read as available when printed the first time?

The Code:

current_users = ['nedboy78', 'codingking678', 'johnnykapahala','jam95','python65','ANDY657']
new_users = ['hamlet56', 'python65', 'jam95','todds4','andy657']

current_users_convert = [current_user.lower() for current_user in current_users]

for new_user in new_users:
    if new_user in current_users:
        print("sorry username " + new_user + ' not available pick a new username')
    else:
        print("username " + new_user + ' is available')

    if new_user in current_users_convert:
        print("CANT USE " + new_user + " AS A USERNAME")

The Output:

username hamlet56 is available
sorry username python65 not available pick a new username
CANT USE python65 AS A USERNAME
sorry username jam95 not available pick a new username
CANT USE jam95 AS A USERNAME
username todds4 is available
username andy657 is available
CANT USE andy657 AS A USERNAME

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

That is because your else condition executes before the last if condition. So here I have change the order.

current_users = ['nedboy78', 'codingking678', 'johnnykapahala','jam95','python65','ANDY657']
new_users = ['hamlet56', 'python65', 'jam95','todds4','andy657']

current_users_convert = [current_user.lower() for current_user in current_users]
for new_user in new_users:
    if new_user in current_users:
        print(f'sorry username {new_user} not available pick a new username')

    elif new_user in current_users_convert:
        print(f"CANT USE {new_user} AS A USERNAME")

    else:
        print(f'username {new_user} is available')

Output:

username hamlet56 is available
sorry username python65 not available pick a new username
sorry username jam95 not available pick a new username
username todds4 is available
CANT USE andy657 AS A USERNAME

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...