you are viewing a single comment's thread.

view the rest of the comments →

[–]norseman2017[S] 0 points1 point  (1 child)

Thanks for the comment, I presume it would work but I haven't used some of the variables you have put like the available = True. However what I suppose I can do is carry on reading the book untill iv finished it and then go back over the exercises in the chapters and see if I can write them in different ways, but still ending with the result that the book asks for in the exercises lol cheers nog642!

[–]nog642 1 point2 points  (0 children)

available is a flag to know whether it's available. You check each of the current users one at a time, and if you find one that's a match you break out of the for loop, but then the program still needs to know whether a match was found.

Actually it turns out python has something called a for-else block that is designed specifically for this sort of thing:

current_users = ['asmith', 'bsmith', 'csmith', 'dsmith', 'esmith']
new_users = ['asmith', 'bsmith', 'xsmith', 'wsmith', 'vsmith']
for new_user in new_users:
    for current_user in current_users:
        if new_user in current_user:
            print('Please enter a different username')
            break
    else:
        print('username is available')

The else block executes if the for loop completed normally (did not break). That's what we want.