鱼C论坛

 找回密码
 立即注册
查看: 875|回复: 4

[已解决]想问一下我这个代码有什么问题?

[复制链接]
发表于 2020-8-14 18:37:05 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
我没懂最后代码有什么问题  它测试都是对的 但是最后给出的结果是这个(Expected 12 test results, got 3. Perhaps excessive output or error in question? 预期有12个测试结果,得到3个。也许输出过多或有问题?)


考虑以下功能:
def read_scores(filename):
    input_file = open(filename, "r")
    scores = input_file.read().split()
    numbers = [float(score) for score in scores if float(score) >= 0 ]
    input_file.close()
    number_of_marks = len(numbers)
    total_marks = sum(numbers)
    print("There are {} score(s).".format(number_of_marks))
    print("The total is {:.2f}.".format(total_marks))
    print("The average is {:.2f}.".format(total_marks/number_of_marks))

read_scores(filename)函数使用文件名作为参数,从文件中读取所有分数,并显示它们的总和和平均值。您可以假定分数由空格分隔,并且文本文件包含未指定数量的分数。

修改上面的函数,并使用try ... except块来处理可能发生的任何异常。该功能应忽略任何负分数。如果参数文件名类型无效,则函数应显示“ERROR: Invalid input!”。如果参数文件名是一个空字符串,该函数应打印一条错误消息“ERROR: Invalid filename!”。如果无法打开该文件,则该功能应显示“ERROR: The file ... does not exist.”。其中...表示文件名。如果文件包含任何无效值,该函数应打印一条错误消息“ERROR: The input file contains invalid values.”。注意:如果可以打开文件,请记住正确关闭文件。


javascript:;



  1. import os
  2. import sys
  3. def read_scores(filename):
  4.     try:
  5.         file_name,file_extension = os.path.splitext(filename)
  6.         if(file_name==""):
  7.             print("Error: Invalid filename!")
  8.             sys.exit()
  9.         input_file = open(filename,"r")
  10.         scores = input_file.read().split()
  11.         try:
  12.             numbers = [float(score) for score in scores if float(score)>=0]
  13.         except ValueError:
  14.             print("Error: The input file contains invalid values")
  15.             sys.exit()
  16.         input_file.close()
  17.         number_of_marks = len(numbers)
  18.         total_marks = sum(numbers)
  19.         average = 0
  20.         try:
  21.             average = total_marks/number_of_marks
  22.         except ArithmeticError:
  23.             print("Error: No positive scores in the input file.")
  24.             sys.exit()
  25.         print("There are {} score(s).".format(number_of_marks))
  26.         print("The total is {:.2f}.".format(total_marks))
  27.         print("The average is {:.2f}.".format(average))
  28.     except TypeError:
  29.         print("Error: Invalid input!")
  30.     except FileNotFoundError:
  31.         print("Error: The file '{}{}' does not exist.".format(file_name,file_extension))
复制代码
最佳答案
2020-8-14 18:51:00
  1. import os
  2. import sys
  3. def read_scores(filename):
  4.     try:
  5.         file_name,file_extension = os.path.splitext(filename)
  6.         if(file_name==""):
  7.             print("Error: Invalid filename!")
  8.             sys.exit()
  9.         try:
  10.             input_file = open(filename,"r")
  11.         except OSError:
  12.             print("Error: The file '{}{}' does not exist.".format(file_name, file_extension))
  13.             return
  14.         scores = input_file.read().split()
  15.         try:
  16.             numbers = [float(score) for score in scores if float(score)>=0]
  17.         except ValueError:
  18.             print("Error: The input file contains invalid values")
  19.             sys.exit()
  20.         input_file.close()
  21.         for i in numbers:
  22.             if i < 0:
  23.                 print("Error: No positive scores in the input file.")
  24.                 return
  25.         number_of_marks = len(numbers)
  26.         total_marks = sum(numbers)
  27.         average = 0
  28.         average = total_marks/number_of_marks
  29.         print("There are {} score(s).".format(number_of_marks))
  30.         print("The total is {:.2f}.".format(total_marks))
  31.         print("The average is {:.2f}.".format(average))
  32.     except TypeError:
  33.         print("Error: Invalid input!")
复制代码
QQ图片20200814223413.png
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2020-8-14 18:42:10 | 显示全部楼层
这样试试:

  1. import os
  2. import sys
  3. def read_scores(filename):
  4.     try:
  5.         file_name,file_extension = os.path.splitext(filename)
  6.         if(file_name==""):
  7.             print("Error: Invalid filename!")
  8.             sys.exit()
  9.         input_file = open(filename,"r")
  10.         scores = input_file.read().split()
  11.         try:
  12.             numbers = [float(score) for score in scores if float(score)>=0]
  13.         except ValueError:
  14.             print("Error: The input file contains invalid values")
  15.             sys.exit()
  16.         input_file.close()
  17.         for i in numbers:
  18.             if i < 0:
  19.                 print("Error: No positive scores in the input file.")
  20.         number_of_marks = len(numbers)
  21.         total_marks = sum(numbers)
  22.         average = 0
  23.         average = total_marks/number_of_marks
  24.         print("There are {} score(s).".format(number_of_marks))
  25.         print("The total is {:.2f}.".format(total_marks))
  26.         print("The average is {:.2f}.".format(average))
  27.     except TypeError:
  28.         print("Error: Invalid input!")
  29.     except FileNotFoundError:
  30.         print("Error: The file '{}{}' does not exist.".format(file_name,file_extension))
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-8-14 18:48:14 | 显示全部楼层
  1. import os
  2. import sys
  3. def read_scores(filename):
  4.     try:
  5.         file_name,file_extension = os.path.splitext(filename)
  6.         if(file_name==""):
  7.             print("ERROR: Invalid filename!")
  8.             sys.exit()
  9.         input_file = open(filename,"r")
  10.         scores = input_file.read().split()
  11.         try:
  12.             numbers = [float(score) for score in scores if float(score)>=0]
  13.         except ValueError:
  14.             print("ERROR: The input file contains invalid values")
  15.             sys.exit()
  16.         input_file.close()
  17.         for i in numbers:
  18.             if i < 0:
  19.                 print("ERROR: No positive scores in the input file.")
  20.         number_of_marks = len(numbers)
  21.         total_marks = sum(numbers)
  22.         average = 0
  23.         average = total_marks/number_of_marks
  24.         print("There are {} score(s).".format(number_of_marks))
  25.         print("The total is {:.2f}.".format(total_marks))
  26.         print("The average is {:.2f}.".format(average))
  27.     except TypeError:
  28.         print("ERROR: Invalid input!")
  29.     except FileNotFoundError:
  30.         print("ERROR: The file '{}{}' does not exist.".format(file_name,file_extension))
复制代码


read_scores('empty.txt') 这个test 又出错了~
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-8-14 18:51:00 | 显示全部楼层    本楼为最佳答案   
  1. import os
  2. import sys
  3. def read_scores(filename):
  4.     try:
  5.         file_name,file_extension = os.path.splitext(filename)
  6.         if(file_name==""):
  7.             print("Error: Invalid filename!")
  8.             sys.exit()
  9.         try:
  10.             input_file = open(filename,"r")
  11.         except OSError:
  12.             print("Error: The file '{}{}' does not exist.".format(file_name, file_extension))
  13.             return
  14.         scores = input_file.read().split()
  15.         try:
  16.             numbers = [float(score) for score in scores if float(score)>=0]
  17.         except ValueError:
  18.             print("Error: The input file contains invalid values")
  19.             sys.exit()
  20.         input_file.close()
  21.         for i in numbers:
  22.             if i < 0:
  23.                 print("Error: No positive scores in the input file.")
  24.                 return
  25.         number_of_marks = len(numbers)
  26.         total_marks = sum(numbers)
  27.         average = 0
  28.         average = total_marks/number_of_marks
  29.         print("There are {} score(s).".format(number_of_marks))
  30.         print("The total is {:.2f}.".format(total_marks))
  31.         print("The average is {:.2f}.".format(average))
  32.     except TypeError:
  33.         print("Error: Invalid input!")
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-8-14 18:53:22 | 显示全部楼层

系统说
您必须在代码中捕获FileNotFoundError。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-20 10:54

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表