-3

I'm new to python and found this small exercise online:

"Create a Python program to print the character that repeats itself in a subsequent sequence"

The solution that was given was the following:

def same_subsequent(string):
    for i in range(len(string)):
        if string[i] == string[i + 1]:
            return string[i]

letter = 'Hello'
print(same_subsequent(letter))

Let's not discuss the design of the solution itself, but I was curious why return string[i] was working however, if instead I am trying to print(string[i]), I have an index error (IndexError: string index out of range).

I do not understand what makes the return different from the print() function in this case

I tried to write:

def same_subsequent(string):
    for i in range(len(string)):
        if string[i] == string[i + 1]:
            print(string[i])
            
letter = 'Hello'
same_subsequent(letter)

... and had the aforementioned error.

I found a very similar question here that explains how to fix the error here:

Index out of range when printing adjacent letter

but it is still not clear why this happens with print but not return.

Thanks a lot!

1 Answers1

2

Return will exit the function the first time it is hit. So when it sees the first 'l' to compare it against the second 'l', the function will complete.

The print doesn't do this. It'll continue running. So once it gets to the 'o' (doesn't happen with return) it'll try comparing it to what comes after, which is nothing.

Taylor
  • 21
  • 1