我已经为下面的问题做了很长一段时间了,我仍然无法通过自动评分。这个问题来自于我正在通过edX学习的从网络介绍到python的课程。你能给我指点方向吗?谢谢。
下面是问题和我的代码:编写一个名为"angry_file_finder“的函数,它接受文件名作为参数。该函数应该打开文件,读取它,如果文件包含"!“,则返回True。每一行。否则,函数应该返回False。
提示:有很多方法可以做到这一点。我们建议使用readline()或readline()方法。readline()返回文件中的下一行;readline()返回文件中所有行的列表。
#在这里写你的函数!
def angry_file_finder(file_name):
read = open(file_name, "r")
lines = read.readlines()
for line in lines:
if not "!" in line:
return False
else:
return True
read.close()下面是一些将测试您的函数的代码行。您可以更改变量的值,以使用不同的输入测试函数。
如果您的函数工作正常,这将最初打印: True
print(angry_file_finder("AngryFileFinderInput.txt"))发布于 2022-05-01 20:14:44
提示:检查您返回的语句。
如果我正确理解了你的问题,你应该返回真如果"!“每一行都是假的,否则就是假的。如果是这样,那么您编写的代码将读取第一行,并返回false If "!“不在直线上,如果是的话,也是正确的。
这是个错误。在这两种情况下,您都要返回true或false,所以程序总是在只检查第一行之后返回,其余的行永远不会被选中。
for line in lines:
if not "!" in line:
return False
else:
return True # <- this is the error, premature return您希望您的程序检查每一行,返回false如果"!“不在里面。如果"!“在行中,然后检查下一行。只有一次你检查了所有行的"!“你能说每一行都有一个"!“在里面。
我建议你有更相似的代码
for line in lines:
if not "!" in line:
read.close() # close the file before returning
return False
read.close()
return True # <- outside of loop so will only return true after loop is finished这样,你的程序就会检查每一行的"!“只有当"!“时才会产生真。每一行都是假的,如果是"!“在任何线路上都不见了。
我希望这对你的学习有帮助,祝你好运:)
发布于 2022-05-01 20:16:07
def angry_file_finder(file_name):
file = open(file_name, "r")
lines = file.readlines()
file.close() # you can close the file now because you have
# already read all its content and stored it in
# lines
for line in lines:
# Return false if any line does not contain "!"
if not "!" in line:
return False
# Only after checking all the lines you can be sure that they
# all contain at least one "!" character
return Truehttps://stackoverflow.com/questions/72079810
复制相似问题