An for
-else
statement is legit, where the else
statement only executes if no break
statement ever got parsed in that for
loop.
Here is an explanation of the code line-by-line:
1.
L=eval(input("Enter a list of elements(number): "))
Receive input from the user. The user's input would be taken in as a sting, so using the eval()
method will evaluate the string as code.
2.
n=len(L)
The len()
method takes in an array, and returns the amount of characters in the array.
3.
print("The original list: ")
print(L)
Display the original list.
4.
x=int(input("Enter an element to be searched in the list: "))
Receive input from the user, and convert the string to an integer.
5.
for i in range(0,n):
Loop through the numbers from 0
to n
, where the n
is exclusive.
6.
if L[i]==x:
print(x," is found at: ",i+1)
break
In each iteration, if the i
index of the array is equal to x
, display the found message, and use the break
statement to jump out of the loop.
7.
else:
print("Not found")
If the program never met the break
statement, meaning x
was never found during the looping, display the not-found message.
Warning: Using the eval()
method opens up many security risks, and is extremely dangerous when using it on un-trusted user input.