如何使用 For 循环解决索引错误问题

How To Solve a Index Error Problem With a For Loop

我遇到无法完成代码的问题。 运行 此代码出现 IndexError 时出现问题。

name = str(input("Please input the books name that you would like to borrow: ")
file = open("books.txt", "r")

file_contents = []
for line in file:
    stripped_line = line.strip()
    line_list = stripped_line.split()
    file_contents.append(line_list)
file.close()
i = 0
for name in range(len(file_contents)):
    i = i +1
    if name == file_contents[i]:
        table_3= [["Borrow Book","1"],
                    ["Cancel Borrowing","2"]]
        headers_3 = ["Details", "No."]
        print(tabulate(table_3, headers_3, tablefmt = "grid"))
        num = int(input("Please input 1 for confirmation of booking and 2 for canceling the booking: "))
        file_contents[i] = changed_name
        changed_name = str(changed_name)
if name == file_contents[i]:
IndexError: list index out of range
Example Of The File: 
(books.txt)
Exile
Dancing In The Moonlight

如错误所述,int 不可迭代。你怎么循环遍历 4?

解决办法?创建一个数字范围:

for name in range(len(file_names)):

我想你是想遍历 file_contents:

# code above elided
file.close()
for line in file_contents:
    if name == line:
# following code elided

如果您发布了您收到的 IndexError,将会有所帮助。 以及您正在打开的文件的示例?

我想我能发现的是,你正在使用变量 i 作为迭代器,但我在你的循环中找不到它。

您缺少 range 关键字

试试这个

for name in range(len(file_contents)):
           #your work

这是您的完整解决方案。希望对您有所帮助

from tabulate import tabulate

name = str(input("Please input the books name that you would like to borrow: "))
file = open("books.txt", "r")

file_contents = []   #available books
for line in file:
    line=line.strip()
    file_contents.append(line)
file.close()   
print("file content: ",file_contents)
i = 0
if name in file_contents:
    table_3= [["Borrow Book","1"],["Cancel Borrowing","2"]]
    headers_3 = ["Details", "No."]
    print(tabulate(table_3, headers_3, tablefmt = "grid"))
    num = int(input("Please input 1 for confirmation of booking and 2 for canceling the booking: "))
    if(num==1):
        try:
            #user wants to withdraw that books so we've to remove that book from our available list of books 
            file_contents.remove(name)
            #now we remove that book name from our available books.txt file
            file=open("books.txt","w")
            str1=" "
            str1.join(file_contents)
            file.write(str1)
            print("Happy to serve you :-)  visit again for more good books")  
        except Exception as e:
            print("There is an error ",e)

    else:
        print("visit again for more good books")