Help In Python For Loop Not Iterating?

Hello! I would just like to ask why isn’t the for loop below not iterating each letter in my string?


def get_letters(word):
  for letter in word:
    return letter

print(get_letters("BROWNIE"))
# returns only "B", why is that?

thanks so much! sorry for the trouble

Hello @eltgnd. The reason it only printing ‘B’ is that when the program is iterating, it goes: ‘for every letter in the word “BROWNIE”…return letter.’ Now, what is the first letter that it comes across? B. Therefore, it returns that letter, ‘B’, because all it has to do is return letter, not do anything else, and therefore it just stops.

Here is some code that would print "BROWNIE"
def get_letters(word):
    lst = []
    for letter in word:
        lst.append(letter)
    str_lst = str(lst)
    return str_lst
print(get_letters("BROWNIE"))

That may not be the shortest way, but it should give you a good understanding of what is happening.
I hope this helps!

2 Likes

You probably didn’t mean to do that though (you could comment that out and get the same printed output)

1 Like

Yes, you’re right, thanks!

Thank you for the reply!! I understand it now

1 Like