-4

Actually, I am a newbie in python. I have doubt in return in for loop section. -> if i return inside loop output is 1 for (for string "abcd"). -> if I return with the same indentation that for is using in code, the output will 4. Can you please explain this happening?

I have added my problem briefly using the comment in code also.

def print_each_letter(word):
   counter = 0   
   for letter in word:
     counter += 1
     return counter      #its returning length 1  why ?
   return counter        # its returning length 4  why?

print_each_letter("abcd")

3 Answers3

1

return exits the function, and it returns 4 because it's out of the loop, and the loop did all it's operations and added up to 4 (since the length of abcd is 4) and returns the value.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
1

According to the python3 docs:

return leaves the current function call with the expression list (or None) as return value

The reason for the different return values is that the function exits when return is called at the end of the first iteration (hence the value of 1).

0

Because the return inside the loop executes the first time the loop is executed, so this happens:

counter = 0
for letter in word:
    #'a'
    counter += 1
    return counter #return counter (1) and terminate function.

but if you let the loop run first:

counter = 0
for letter in word:
    #'a'
    counter += 1 #1
    #'b'
    counter += 1 #2
    #'c'
    counter += 1 #3
    #'d'
    counter += 1 #4
return counter #return counter (4) and terminate function.
Ruan
  • 219
  • 5
  • 9