我将提供该代码应该执行的任务的描述,以防万一有人需要它来回答我。
#Write a function called "load_file" that accepts one
#parameter: a filename. The function should open the
#file and return the contents.#
#
# - If the contents of the file can be interpreted as
# an integer, return the contents as an integer.
# - Otherwise, if the contents of the file can be
# interpreted as a float, return the contents as a
# float.
# - Otherwise, return the contents of the file as a
# string.
#
#You may assume that the file has only one line.
#
#Hints:
#
# - Don't forget to close the file when you're done!
# - Remember, anything you read from a file is
# initially interpreted as a string.
#Write your function here!
def load_file(filename):
file=open(filename, "r")
try:
return int(file.readline())
except ValueError:
return float(file.readline())
except:
return str(file.readline())
finally:
file.close()
#Below are some lines of code that will test your function.
#You can change the value of the variable(s) to test your
#function with different inputs.
#
#If your function works correctly, this will originally
#print 123, followed by <class 'int'>.
contents = load_file("LoadFromFileInput.txt")
print(contents)
print(type(contents))
使用包含“ 123”的文件测试代码时,一切正常。当网站加载另一个文件以测试此代码时,会发生以下错误:
[Executed at: Sat Feb 2 7:02:54 PST 2019]
We found a few things wrong with your code. The first one is shown below, and the rest can be found in full_results.txt in the dropdown in the top left:
We tested your code with filename = "AutomatedTest-uwixoW.txt". We expected load_file to return the float -97.88285. However, it instead encountered the following error:
ValueError: could not convert string to float:
因此,我猜测该错误发生在第一个except
语句内,但我不明白为什么。如果将文件中的值转换为float时发生错误,代码是否应该转到第二个except
语句?然后在第二个except
中将其转换为字符串,该字符串仍然可以工作吗?我猜我对try-except(specified error)-except(no specified error)
的工作方式有误解。
对不起,很长的帖子。
答案 0 :(得分:1)
该代码是否应转到除语句之外的第二个语句?
都能跟得上:这个 “平坦” 的try / except语句仅适用于在第一 try
块。如果在那里发生异常,则except
分支将捕获此异常并立即评估适当的块。如果在该块中发生了异常,它不被任何东西卡住,因为没有try
块在那里。
因此,您必须做很多嵌套的try / except语句:
try:
do_this()
except ValueError:
try:
do_that()
except ValueError:
do_this()
except:
do_that_one()
except:
# a whole bunch of try/except here as well
您可能需要添加更多级别的嵌套。
就需要编写的代码量而言,这是非常低效的。更好的选择可能是:
data = file.readline()
for converter in (int, float, str):
try:
return converter(data)
except:
pass
请注意,如果你做converter(file.readline())
,新的生产线将在每次迭代(/或,你的情况,在任何新的尝试,除了块)读取,这可能不是你所需要的。
答案 1 :(得分:0)
否,将仅执行那些except
块中的一个-第一个与异常匹配的块。您描述的行为将与
except ValueError:
try:
return float(file.readline())
except:
return str(file.readline())
答案 2 :(得分:0)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ol class="status"></ol>
<div class="img"></div>
<div class="img" style="background-image: url('')"></div>
<div class="img" style="background-image: url('https://uploads-ssl.webflow.com/59de7f3f07bb6700016482bc/5ed2bfa63643bc3cf3cf2b5c_files-and-folders.svg')"></div>