For Loops in a Function

https://www.codecademy.com/paths/computer-science/tracks/cspath-python-objects/modules/cspath-python-strings/lessons/introduction-to-strings/exercises/iterating-through-strings

Why would this code return 1 for get_length(‘test’). How does the compiler work when for loops are in a function? Doest it finish the loop first or after every item in for loop does it go to the beginning of the function??

Thanks!

2 Likes

Hi @ozyy.s,

When a return statement is executed, the action of the function that contains it is terminated, even if that return statement is within a loop. In your code, the return statement is within the for loop, therefore the function terminates during the first iteration of the loop, when the value of counter is 1.

3 Likes