Here's the code part :-
arr=[1,2,3,4,5,6,1,2,3,4,5,6]
and say I want to search 5 and print it's index.
x=Number to be searched
for i in range(len(arr)):
if x==arr[i]:
print("Found at",i)
else:
print("Not found")
The output is as follows :-
Found at 4
Found at 10
Not found
Hoe to get rid of the last line ? It should not be printed as 5 is present in arr! Note : I just started learning python few days ago so I'm sorry if this is a trivial question but I can't get the reason of it printing that one.
elsepart then.else:branch of aforloop is executed when you reach the end. You can stop theelsebranch from executing by usingbreak. But you can't break out of the loop here. Don't useelse:, use a flag variable or counter.