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!