What's wrong with this code?

def username_generator(first_name, last_name):
if len(first_name)<3 and len(last_name)<4:
entire_name = first_name + last_name
return entire_name
elif len(first_name)>3 and len(last_name)>4:
new_username = first_name[:3] + last_name[:4]
return new_username

Why i get ‘None’ to terminal after testing with print(username_generator(“Abe”, “Simpson”))

and with this i get it right?:
def username_generator(first_name, last_name):
if len(first_name)<3 or len(last_name)<4:
entire_name = first_name + last_name
return entire_name
else:
new_username = first_name[:3] + last_name[:4]
return new_username

Since there is no else clause and Abe is three letters, this condition is not met and nothing is returned, hence, None.

No need to remove this question. It is a perfectly valid one.

Perhaps you discovered that the use of range is unnecessary. Great! When the first condition is met, we give our variable the first three letters, else we just give it whatever the first name is. When the second condition is met we give our variable the first four letters, else whatever the last name is. Then we do our magic, and voila, username.

Thank you!

Can you help me with the second part of this same exercise? I don’t understand the i - 1 stuff, and every time we’re asked to use something like that, I get frustrated. I looked at the answer and I’m trying to figure out how they got that. Where I get stuck is these lines:

for i in range(0, len(user_name)):
password += user_name[i-1]

I think that means we want to iterate through a range of characters, from index 0 through the length of the list. Yes?

But then I don’t understand why we’re adding user_name[i-1] to the empty string. Can you try to explain? Why i-1?

Thanks!

1 Like

i is a variable which means it is standing in for some value, which we may assume at this time to be an integer.

The above is an expression to our eyes. The computer sees it as a value, immediately.

Decrementing is the process of subtracting 1 from a value. When the value is an integer, say, 10, decrementing results in 9 being the updated value.

There is good reason to decrement when dealing with iterable’s indices. The last index that is reachable is always one less than the length of the iterable. Since they are zero-indexed that means the last character/element is at len(object) - 1.

It’s a good possibility that i - 1 might have something to do with this. If not, it will be a very similar relation to your problem.

Thank you! Got it!! I appreciate you getting back tome.

1 Like

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.