Two sum code
why the code do not need 'else:' ??and why 'return False' command need to be placed exactly at that position as the arrow indicate to run properly??
def Twosum(a, target):
for i in range(len(a)):
for j in range(i+1, len(a)):
if a[i]+a[j]==target:
print(a[i], a[j])
print(a.index(a[i]), a.index(a[j]))
return True -------> return False print(Twosum(a, target))
for i in range(len(a)):
for j in range(i+1, len(a)):
if a[i]+a[j]==target:
print(a[i], a[j])
print(a.index(a[i]), a.index(a[j]))
return True -------> return False print(Twosum(a, target))
1 answers ( 0 marked as helpful)
Hi Thadaton,
thanks for reaching out! The answer to both of your question are related. In Python instead of writing else explicitly, we indicate where the 'else' portion of the code starts by indicating it with a tab. That is we don't write the command itself, but in order for our code to be parsed correctly, we require the indent of the code. So, it's to do with Python syntax.
Best,
The 365 Team