-2
L=eval(input("Enter a list of elements(number): "))
n=len(L)
print("The original list: ")
print(L)
x=int(input("Enter an element to be searched in the list: "))
for i in range(0,n):
    if L[i]==x:
         print(x," is found at: ",i+1)
         break
else:
    print("Not found")

This is a code to search and find an element inside a user given list. This shouldn't be able to work as the else statement is clearly of no use and wrongly indented (with the if statement). A flag would've done the trick but here a flag isn't needed as it manages to work. Can someone explain how?

1 Answers1

0

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.

Red
  • 26,798
  • 7
  • 36
  • 58