I was watching python lecture by Raymond Hettinger on youtube. And he showed the right way to exit for loop:
def find(seq, target):
for i, value in enumerate(seq):
if value == target:
break
else:
return -1
return i
I dont get why bother with else statement and not just do:
def find(seq, target):
for i, value in enumerate(seq):
if value == target:
return i
return -1
Am I missing something or it is just good idea to sometimes add this else/break statement for whatever reason?
Condensed answer: Once you use return you are out of your function. Break means the code continue to run and you can add more things. So you are right in your example, but what if you want to do more things if nothing was found:
Raise an error:
def find(seq, target):
for i, value in enumerate(seq):
if value == target:
break
else:
raise ValueError("Nothing found in {}".format(seq))
return i
find("hello","a")
Or write to a file:
def find(seq, target):
for i, value in enumerate(seq):
if value == target:
break
else:
with open("output.txt", "w") as f:
f.write("Nothing found :(((")
return i
find("hello","a")
Developping further (@Joe Iddon):
You maybe want to continue further too:
def find(seq, target):
for i, value in enumerate(seq):
if value == target:
break
else:
return "Nothing found"
# calculate more things
a = [1,2,3]
if i in a:
return i
else:
return "Not in a"
find("hello","a")
So for this small purpose it wasn't necessary. But if you are building something upon that, the else clause can be useful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With