编程和 Python 的初学者,我目前正在为图书馆图书管理员编写程序。我正在尝试从文本文件中选择一段字符串,因此当用户输入必须签入书籍用户名的人时,它会显示书籍和信息。但是,当我这样做时,它不会打印用户编号所在的行,而是打印整个内容。请看我的代码:
searchphrase = raw_input("Please provide Your user ID:")
searchfile = open("Librarybooks.txt","r")
for line in searchfile:
if searchphrase in line:
print line
else:
print "User not identified or invalid entry, please restart program"
break
我认为可能是python无法识别文本文件中的所有不同行,因此认为它都是一行。我将如何安排它工作?或者,如果您发现我的代码有任何明显问题,我们将不胜感激。
您只检查不匹配的第一行:
searchphrase = raw_input("Please provide Your user ID:")
searchfile = open("Librarybooks.txt","r")
for line in searchfile:
if searchphrase in line: # <== if it matches, then print and go to next line..
print line
else: # <== if id doesn't match, exit the for loop
print "User not identified or invalid entry, please restart program"
break
尝试这样的事情:
for line in searchfile:
if searchphrase in line: # <== if matches, then print the line and break out of the for loop
print line
break
else: # <== if the for loop finished without breaking, then the searchphrase was not in the file
print "User not identified or invalid entry, please restart program"
这在 for 循环中使用 else 子句。
调试此类问题的一种简单方法是在某些更改之前(和之后)打印出有趣的变量。例如:
for line in searchfile:
print "LINE: [%s]" % line # I put it inside [] to check if there are any spaces at the end.
这样你就可以验证你的假设是正确的。
您的 IDE 可能有一个调试器,可以让您在非常直观的用户界面中设置断点和检查变量。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句