not able to execute else part of this program in py

li = []

n = int(input(“Enter numbers: “))

count = 0

for i in range(0,n):

a=int(input())
li.append(a)

print( li)

s = int(input(‘nEnter a number for search : ‘))

for j in li:

if s == j:
    li.remove(j)
    count+=1
    if count == 1:
        print(f" {j} is removed . n")
        break
    #else part is not executed
    else:
        print(f"Nothing is removed. n")

print(li)

Answer

It looks like the else statement belongs to the wrong if statement. Try moving the else statement back one indent. This will print Nothing is removed each time an element is not found.

for j in li:

    if s == j:
        li.remove(j)
        count+=1
        if count == 1:
            print(f" {j} is removed . n")
            break
        #else part is not executed
    else:
        print(f"Nothing is removed. n")
    print(li)

Leave a Reply

Your email address will not be published. Required fields are marked *