【问题标题】:Why isn't my try except catching if you put a string into the argument of score?如果您将字符串放入 score 的参数中,为什么我除了捕捉之外没有尝试?
【发布时间】:2017-07-07 22:26:09
【问题描述】:
#Write a program to prompt for a score between 0.0 and 1.0.
#If the score is out of range print an error.
#If the score is between 0.0 and 1.0, print a grade using the following table:
#Score Grade >=0.9 A >=0.8 B >=0.7 C >=0.6 D <0.6 F

def computegrade(score):
    try:
        score1 = float(score)
        if score1 <= 1.0 and score1 >= 0.9:        
            grade = "A"
        elif score1 < 0.9 and score1 >= 0.8:
            grade = "B"
        elif score1 < 0.8 and score1 >= 0.7:
            grade = "C"
        elif score1 < 0.7 and score1 >= 0.6:
            grade = "D"
        elif score1 < 0.6 and score1 > 0:
            grade = "F"
        else:
            grade = "ERROR: You did not enter a number or you entered a number out of the range of 0.0 and 1.0!"
        print(grade) 
    except:
        print("ERROR: You did not enter a number or you entered a number out of the range of 0.0 and 1.0!")

无论我输入 0.0 和 1.0 范围之外的整数还是输入该范围内的整数,一切似乎都按预期工作。我创建了一个尝试,除非用户输入一个字符串作为分数。但它似乎没有抓住它,我不知道为什么。

【问题讨论】:

  • 那你怎么称呼它?
  • 输出是什么?
  • 你可以像这样链接条件:0.9 &lt;= score1 &lt;= 1.0
  • 我无法复制。这个对我有用。但是您确实需要更改您的 except 子句以专门捕获ValueError,而不是任何异常。
  • 您的字符串是否类似于"0.8"

标签: python python-3.x


【解决方案1】:

我试过了,效果很好。确保输入是一个不能转换为浮点数的字符串,你应该没问题。

def computegrade(score):
    try:
        score1 = float(score)
        if score1 <= 1.0 and score1 >= 0.9:
            grade = "A"
        elif score1 < 0.9 and score1 >= 0.8:
            grade = "B"
        elif score1 < 0.8 and score1 >= 0.7:
            grade = "C"
        elif score1 < 0.7 and score1 >= 0.6:
            grade = "D"
        elif score1 < 0.6 and score1 > 0:
            grade = "F"
        else:
            grade = "ERROR: You did not enter a number or you entered a     number out of the range of 0.0 and 1.0!"
        print(grade)
    except:
        print("ERROR: You did not enter a number or you entered a number out of the range of 0.0 and 1.0!")
computegrade("fire")

输出:

ERROR: You did not enter a number or you entered a number out of the range of 0.0 and 1.0!

【讨论】:

  • 那我一定没有正确输入。这是我正在尝试的:
  • >>> computegrade(dragoon) Traceback(最近一次调用最后):文件“”,第 1 行,在 computegrade(dragoon) NameError: name 'dragon' is未定义 >>> computegrade("dragon") >>>
  • 你尝试了什么?
  • Cary,该函数称为 computegrade,括号中是我正在尝试的项目。因此,在上面的示例中,我使用单词 dragoon 运行该函数,然后使用引号“dragoon”。抱歉,如果不清楚,我在解释/学习方面还是很陌生。
  • 对不起,我应该知道的。计算等级(“龙”)的输出是什么?
猜你喜欢
  • 2022-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-13
  • 1970-01-01
  • 2018-04-04
  • 1970-01-01
  • 2020-12-16
相关资源
最近更新 更多