Question about whether or not my code is right/wrong/better/worse

Hi! I’m finishing up the Python section on strings, and the review problem calls for a for loop. I had done it in a different way and the green check mark appeared before I even got to the last question, because my code returns the desired result. My question that I am wondering is if there is a reason a for loop is better? What is a reason my response would be less favorable (if it is, at all)? (The question was to loop through the user_name, and to move the last letter to the front while shifting the others to the right). Thank you!

Mine:
def password_generator(user_name):
password = user_name[-1:] + user_name[:-1]
return password

Codecademy’s:
def password_generator(user_name):
password = “”
for i in range(0, len(user_name)):
password += user_name[i-1]
return password

Using for loops (depending on how you see it) is better since it improves the readability of the code. Taking your provided code as example, [-1:] and [:-1] is quite cryptic sometimes especially in a large project where you are working with others (or solo). In the for loop, everyone who knows a bit of looping will know exactly what your program does.
Of course if you want a concise code or you know you gonna understand the code you wrote when you come back a few years later your code is absolutely fine. However in a long run for loop is better.

(And this lesson is for beginner in general so they might not understand user_name[-1:] + user_name[:-1] if Codecademy chose this solution)

1 Like

Thank you! I was really hoping for some insight on what makes it better or worse, and you explained that very well :slight_smile: