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

时间:2020-06-08 16:04:20

标签: python index-error

我遇到了无法完成代码的问题。 在运行此代码时,它会出现一个IndexError问题。

<section id="aboutuspic">
  <div class="container">
    <img src="inside.jpg" />
  </div>
</section>
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

5 个答案:

答案 0 :(得分:2)

您缺少range关键字

尝试一下

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

答案 1 :(得分:2)

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

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")

答案 2 :(得分:1)

我认为您是要遍历file_contents

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

答案 3 :(得分:0)

如错误所示,一个int不可迭代。您如何遍历4个?

解决方案?创建一系列数字:

for name in range(len(file_names)):

答案 4 :(得分:-1)

如果发布所得到的IndexError会有所帮助。 还有您要打开的文件的示例?

我想我能发现的是,您正在使用变量i als迭代器,但是我无法在您的循环中找到它。

相关问题