Home > Blockchain >  How to delete a specific index in a list and how to break the loop when you are finished with the in
How to delete a specific index in a list and how to break the loop when you are finished with the in

Time:10-02

I want to delete the 2nd and fourth user input and i would like to end the program when the user has an invalid input

num_elements = []

list_length = int(input('Enter number of elems: '))

while True:
try:
    for i in range(list_length):
        item = int(input('Enter the numbers: '))
        num_elements.append(item)
        del (num_elements[0])
        del (num_elements[3])
        break

except:
    print('Invalid Input!!!')
    break

CodePudding user response:

Your code looks like you tried to make the user enter valid numbers only, but put the try/except in the wrong place and then added a while loop to repair that ending up with being prompted for more numbers than required.

I've no idea what all the breaks and dels are about.

You meant to write this:

num_elements = []

list_length = int(input('Enter number of elems: '))

for i in range(list_length):
    while True:
        try:
            item = int(input('Enter the numbers: '))
            num_elements.append(item)
            break
        except ValueError:
            print('Invalid Input!!!')

print(num_elements)
  • Related