【问题标题】:Cant get str to work in if-loop Python 3无法让 str 在 if-loop Python 3 中工作
【发布时间】:2015-03-02 18:43:41
【问题描述】:

我写了一个成绩计算器,你可以在其中放入一个浮点数,然后根据你的得分获得一个成绩。我的问题是我相信我需要一个 float(input... 但是如果你在框中写字母就会出错...

def scoreGrade():
"""
Determine the grade from a score
"""
gradeA = "A"
gradeB = "B"
gradeC = "C"
gradeD = "D"
gradeF = "F"

score = float(input("Please write the score you got on the test, 0-10: "))
if score >= 9:
    print("You did really good, your grade is:", gradeA, ". Congratulations")
elif score >= 7:
    print("Your results are good. They earn you a:", gradeB, ". Better luck next time")
elif score >= 5:
    print("Not too bad. You got a:", gradeC)
elif score >= 4:
    print("That was close...:", gradeD)
elif score < 4:
    print("You need to step up and take the test again:", gradeF)
else:
    print("Grow up and write your score between 0 and 10")

如果你写了分数从 0-10 的其他东西,有没有办法摆脱浮动并打印最后一条语句?

【问题讨论】:

  • 这叫做“if 语句”,而不是“if-loop” :)
  • 我删除了不必要的性别诽谤。这里不需要那种语言。
  • 我是英国人。这个词仍然令人反感

标签: python string python-3.x


【解决方案1】:

类似这样的:

score = None
while score is None:
    try:
        score = float(input("Please write the score you got on the test, 0-10: "))
    except ValueError:
        continue

继续询问,直到 float 演员表起作用而不引发 ValueError 异常。

【讨论】:

    【解决方案2】:

    你可以这样做

    try:
        score = float(input("Please write the score you got on the test, 0-10: "))
    except ValueError:
        print("Grow up and write your score between 0 and 10")
        scoreGrade()
    

    【讨论】:

      【解决方案3】:

      我建议使用EAFP 方法并分开处理好输入和坏输入。

      score_as_string = input("Please write the score you got on the test, 0-10: ")
      try:
          score_as_number = float(score_as_string)
      except ValueError:
          # handle error
      else:
          print_grade(score_as_number)
      
      def print_grade(score):
      """
      Determine the grade from a score
      """
      gradeA = "A"
      gradeB = "B"
      gradeC = "C"
      gradeD = "D"
      gradeF = "F"
      
      if score >= 9:
          print("You did really good, your grade is:", gradeA, ". Congratulations")
      elif score >= 7:
          print("Your results are good. They earn you a:", gradeB, ". Better luck next time")
      elif score >= 5:
          print("Not too bad. You got a:", gradeC)
      elif score >= 4:
          print("That was close...:", gradeD)
      elif score < 4:
          print("You need to step up and take the test again:", gradeF)
      else:
          print("Grow up and write your score between 0 and 10")
      

      请注意,通常您希望从函数返回,而不是在其中打印。使用函数输出作为 print 语句的一部分是细节,函数不必知道这一点。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-06-28
        • 1970-01-01
        • 2023-03-27
        • 1970-01-01
        • 2015-12-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多