Why does else statement in this code produce something different?


#1

In this excercise:
https://www.codecademy.com/paths/computer-science/tracks/cspath-flow-data-iteration/modules/dspath-python-loops/lessons/python-functions-loops-cc/exercises/reversed

how come my code (code 2) returns True,True instead of True,False like code 1?

code 1:
def reversed_list(lst1, lst2):
for index in range(len(lst1)):
if lst1[index] != lst2[len(lst2) - 1 - index]:
return False
return True

code 2:
def reversed_list(lst1,lst2):
for i in range(len(lst1)):
if lst1[i]!=lst2[len(lst2)-1-i]:
return False
else:
return True
print(reversed_list([1, 2, 3], [3, 2, 1]))
print(reversed_list([1, 5, 3], [3, 2, 1]))


#2

the first code, return True is outside after the loop

in code 2, return True will be reached in the first iteration of the loop when if condition evaluates to true. The return keyword will then end the function. (return is the last thing a function does)


#3

Oh I see, thank you very much!


#4

you could use for/else, that is possible. But if/else won’t do


#5

I also have a question about this exercise: My code on the top (first set) returns incorrectly as True, True. The bottom (solution) returns correctly as True, False.

def reversed_list(lst1, lst2):
for i in range(len(lst1)):
if lst1[i] == lst2[len(lst2) - 1 - i]:
return True
return False
print(reversed_list([1, 2, 3], [3, 2, 1]))
print(reversed_list([1, 5, 3], [3, 2, 1]))

def reversed_list(lst1, lst2):
for index in range(len(lst1)):
if lst1[index] != lst2[len(lst2) - 1 - index]:
return False
return True
print(reversed_list([1, 2, 3], [3, 2, 1]))
print(reversed_list([1, 5, 3], [3, 2, 1]))

From what I can tell, my solution checks lst1 at index 1 and compares it with lst2 at index 3 correctly, but then sees that it’s true, so it kicks back True. Can anyone explain why this is so? Shouldn’t it continue iterating through the loop and realize that lst1 at index 2 and lst2 at index 2 do not match and then kick back false kicking it out of the loop? Also, if I change the values to [1, 5, 3] [ 3, 2, 2] it correctly states True, False. However if I change the last value checked[ 1, 5, 3] [1, 2, 1] it still kicks back True, True.


#6

By default, a function returns None at the end of the function. If we want to return something else at the end of the function, we can use the return keyword.

Given return is the last thing a function does, when a return keyword is reached, the function ends