1
def inputList():
        list=[]
        length=int(input("Enter the length of the list : "))
        print("Enter the elements -->")
        for i in range(length):
                print(i)
                try:
                        element=int(input(":"))
                        list.append(element)
                except:
                        print("Invalid element entered! WON'T BE COUNTED!")
                        i-=1
                        print("i NOW :",i)
        print("Unaltered list :",list)
        return list

I am trying to code the except block such that it also decreases the value of i if an error occurs (Eg. Entering a float instead of int). When the except block runs it prints the decreased value but when the for runs again i remains unchanged and therefore the total length is one less than what it should be (because of one incorrect value).

bot-coder101
  • 132
  • 1
  • 7

2 Answers2

1

you can view in a different way and use this, this is more simple and avoid the substract in the counter

def inputList():
list =[]
print("Unaltered list :",list)
length =int(input("Enter the length of the list: "))
print("Enter the elements -->")
i=0
while(i<length):
    print(i)
    try:
        element = int(input(":"))
        list.append(element)
        i++
    except:
        print("Invalid element entered! WON'T BE COUNTED!")
        print("i NOW :",i)

return list
sacoco
  • 66
  • 2
0

Does it work if you put your call of i in the last except print statement within str()?

                print("i NOW : "+ str(i))
CreekGeek
  • 1,809
  • 2
  • 14
  • 24
  • No, actually my concern is updating i not the printing part, cause when I print i after doing i-=1 it shows the value that we needed but when it went back to the for loop the updated value was not being used(one less than the original). – bot-coder101 Mar 28 '21 at 18:08