FAQ: Introduction to Strings - Review

#21

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

#22

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

#23

Not sure the intent of what you’re doing there and haven’t been able to see codecademy solution, however, I would do the following:

def username_generator(first, last):
tab return first[:3] + last[:4]
def password_generator(username):
tab password = “”
tab for i in range(len(username)):
tab tab password += username[i-1]
tab return password

The reason the second piece of code gives the right answer and not your expected “AbeSimpp” is because “password += something” is the same as “password = password + something” and for each iteration you add your previous iteration’s password plus the new “something”.

#24

Hi arcrunner11706,
Thanks a lot for explaining to me very thoroughly and also taking your time for it. I think I can understand very well for the first part. As for the second part, under this line of code:

password += user_name[i-1]

Schouldn"t it take last index in the user_name and fit right at the back of the username instead at the front like this : AbeSimpp ?

#26

that’s what I did whoop

#27
def username_generator(first_name,last_name):
  return (first_name[0:3] if len(first_name) >= 3 else first_name) + (last_name[0:4] if len(last_name) >= 4 else last_name)

one line!

#28

Hello. Can anyone suggest more efficient code to solve the problem? Here are the instructions:

Now for the temporary password, they want the function to take the input user name and shift all of the letters by one to the right, so the last letter of the username ends up as the first letter and so forth. For example, if the username is AbeSimp, then the temporary password generated should be pAbeSim.

def password_generator(username):
  password = ""
  for i in username:
    if not i == username[-1]:
      continue
    else:
      new_password = password + i + username[0:-1]
      return new_password
#29

Guy on Slack offered this solution. Yeah, not too pleased with myself lol

def password_generator_huh(username):
    return username[-1] + username[:-1]