为什么我无法运行谷歌的Python测试?

1 投票
1 回答
2235 浏览
提问于 2025-04-18 13:59

我正在尝试使用谷歌的Python入门课程(https://developers.google.com/edu/python/exercises/basic)来开始学习编程。

根据它给我的指示,我写了下面的代码:

# Given an int count of a number of donuts, return a string
# of the form 'Number of donuts: <count>', where <count> is the number
# passed in. However, if the count is 10 or more, then use the word 'many'
# instead of the actual count.
# So donuts(5) returns 'Number of donuts: 5'
# and donuts(23) returns 'Number of donuts: many'
def donuts(count):
  if count < 10:
    numberofdonuts = count
  else:
    numberofdonuts = 'many'
  print 'Number of donuts:', str(numberofdonuts)
  return

如果我只是让Python打印我写的代码,它的输出和说明书上说的一模一样(比如:“甜甜圈的数量:4”)。但是当我用谷歌提供的测试模块来测试时:

# Provided simple test() function used in main() to print
# what each function returns vs. what it's supposed to return.
def test(got, expected):
  if got == expected:
    prefix = ' OK '
  else:
    prefix = '  X '
  print '%s got: %s expected: %s' % (prefix, repr(got), repr(expected))


# Provided main() calls the above functions with interesting inputs,
# using test() to check if each result is correct or not.
def main():
  print 'donuts'
  # Each line calls donuts, compares its result to the expected for that call.
  test(donuts(4), 'Number of donuts: 4')
  test(donuts(9), 'Number of donuts: 9')
  test(donuts(10), 'Number of donuts: many')
  test(donuts(99), 'Number of donuts: many')

它总是返回一个“X”,并说它得到了“None”,像这样:

donuts
Number of donuts: 4
  X  got: None expected: 'Number of donuts: 4'
Number of donuts: 9
  X  got: None expected: 'Number of donuts: 9'
Number of donuts: many
  X  got: None expected: 'Number of donuts: many'
Number of donuts: many
  X  got: None expected: 'Number of donuts: many'

我想谷歌肯定知道怎么写Python,但我花了很多时间在弄清楚这个测试模块是怎么工作的,还对比我的结果和它似乎想要的结果,但就是没办法解决这个问题?

我觉得我可能漏掉了一些非常基础的东西……

1 个回答

5

你的函数是打印内容,而不是返回一个值。

print 是把内容写到你的控制台或终端上。调用这个函数的人并不能得到结果。

与其使用 print,不如直接返回这个字符串:

def donuts(count):
  if count < 10:
    numberofdonuts = count
  else:
    numberofdonuts = 'many'
  return 'Number of donuts: ' + str(numberofdonuts)

撰写回答