为什么我的else语句不起作用?它多次打印“这本书在图书馆中不可用”

时间:2019-11-16 20:38:03

标签: python loops for-loop if-statement

file=open('database.txt','r')
x=input("Please enter the title of the book you are looking for?")
print("%s %10s %8s %22s %11s"%\
  ("ID","Title","Author","Purchase Date","Member ID"))
for line in file:
if x in line.split():
    print(line)
else:
    print("This book isn't available in Library.")
file.close()

否则:连续打印“此书在图书馆中不可用”

1 个答案:

答案 0 :(得分:2)

我认为缩进更正后,您的原始代码将是:

file = open('database.txt','r')
x = input("Please enter the title of the book you are looking for?")
print("%s %10s %8s %22s %11s"%\
  ("ID","Title","Author","Purchase Date","Member ID"))
for line in file:
    if x in line.split():
        print(line)
    else:
        print("This book isn't available in Library.")
file.close()

继续打印“这本书在图书馆中不可用”的原因。是因为您的循环要求文件中的每一行都可以 1)打印行 要么 2)打印“此书在图书馆中不可用”。

因此,如果您的文件说1000行,那么无论如何,您都会打印某物 1000次。

相反,也许可以从分配一个布尔变量开始,该变量可以跟踪是否找到一本书。然后遍历database.txt文件中的各行以查找感兴趣的书。

如果找到该书,则可以更改该变量,并打印包含该书的行,并继续在循环中进行

如果未找到该书,则可以在循环的外部中打印“此书在图书馆中不可用”。消息。

file = open('database.txt','r')

x = input("Please enter the title of the book you are looking for?")

print("%s %10s %8s %22s %11s"%\
  ("ID","Title","Author","Purchase Date","Member ID"))

book_not_found = True

for line in file:
    if x in line.split():
        book_not_found = False
        print(line, end = '')

if book_not_found:
    print("This book isn't available in Library.")

file.close()

而且是的,正如Eugene Pakhomov所说,如果您提供输入和预期输出的示例,则更容易排除故障。