You need to iterate through a list to find the first occurrence of an item that satisfies a condition. Such an item may be in the list or it may not. If the item is found, you should end the loop immediately and print 'found'. If the item is not found you should print 'not found'.
The question is which of these two solutions is better 'programming practice' and why? If you think neither is good programming practice, please include a better solution.
Note that this is a question about programming practice, what is/isn't generally considered good programming practice and why.
Solution 1:
for item in lst:
if condition(item):
print('found')
break
else:
print('not found')
Solution 2:
i = 0
found = False
while i < len(lst) and not found:
if condition(lst[i]):
found = True
i += 1
if found:
print('found')
else:
print('not found')
Aucun commentaire:
Enregistrer un commentaire