+ 1

Book Titles Code

***Why when running this code do I always get an index error, when x = 0 and I use the variable in the code, but if you just input the actual integer of 0 there is no error. Can someone please explain this. file = open("/usercode/files/books.txt", "r") info = file.readlines() x = 0 while x<5: charc_ = (len(info[x]))-1 print(charc_) x+=1 file.close()

4th Mar 2022, 3:45 PM
Joss Clegg
Joss Clegg - avatar
1 ответ
0
In the file books.txt, there are 4 books name means 4 lines and you have written in while that- while x<5: # Here it goes from 0 to 4 charc_ = (len(info[x]))-1 # Here when x is 4 it is IndexError: list index out of range, because index starts from 0 and there are 4 lines so till 3. So in 4, it gives index error So you have to write - while x<4: Then No error
4th Mar 2022, 4:10 PM
Shaurya Kushwaha