为什么我的if语句不适用于此评分代码?

时间:2017-02-17 20:30:10

标签: python

这是我的代码,我希望它能够通过并选择适合的类别,但它总是给我F。

import random

def rand(start, stop):
  print random.randint(start,stop)

def grader(rand):
  print "Your test score is "
  x = rand(50, 100)
  if x >= 90:
    print "which is an A."
  elif x <= 89 and x >= 80:
    print "which is a B."
  elif x <= 79 and x >= 70:
    print "which is a C."
  elif x <= 69 and x >=60:
    print "which is a D."
  else:
    print "which is a F."

2 个答案:

答案 0 :(得分:0)

而不是返回random.randint(start,stop),而是打印它。

更改

def rand(start, stop):
  print random.randint(start,stop)

def rand(start, stop):
  return random.randint(start,stop)

答案 1 :(得分:0)

您的rand函数正在返回None,因为它正在打印一个值,而不是返回它。此外,良好的做法是将其命名为更具描述性的内容,例如get_randomget_random_number。此外,您的get_random函数与randint完全相同,但我会在那里给您带来疑问(要添加更多功能?

作为奖励,我已经列举了一个例子,这个鲜为人知的bisect库如何适用于这些价值交叉问题!

示例:

import bisect, random

def get_random(start, stop):
  return random.randint(start,stop)

def match_grade(score):
    breakpoints = [60, 70, 80, 90]
    grades = ["which is a F.", "which is a D.", 
    "which is a C.", "which is a B.", "which is an A."]
    bisect_index = bisect.bisect(breakpoints, score)
    return grades[bisect_index]

random_number = get_random(50, 100)
grade_range = match_grade(random_number)
print "Your test score is {}, {}".format(random_number, grade_range)

示例输出:

Your test score is 63, which is a D.