python - 为什么我不能让 Google 的 Python 测试工作?

标签 python string python-2.7

我正在尝试使用 Google 的 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 打印我编写的代码,它的输出结果看起来就像指令所说的那样(例如:“ donut 数量:4”)。但是当它通过 Google 提供的测试模块时:

# 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'

我假设 Google 知道如何很好地编写 Python,但我花了很多时间试图弄清楚测试模块的工作原理并将我的结果与它似乎想要的结果进行比较,但我做不到去哪儿了?

我想我在这里遗漏了一些非常基本的东西......

最佳答案

您的函数打印,但不返回值。

print 写入您的控制台或终端。调用者没有收到结果。

不使用print,而是返回字符串:

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

关于python - 为什么我不能让 Google 的 Python 测试工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24846806/

相关文章:

python - 列表理解条件中的 `elif`

python - 附加到 for 语句输出的前面

java - 将输入字符串解析为整数似乎会使我的应用程序崩溃

python - 从expect脚本调用python脚本时出错

python - 与早期版本相比,Python 2.7 的新 IO 库快了多少?

java - 使用 gson 在 Java 中序列化千兆字节的 python 对象

python - 如何只打印具有唯一字段的行?

java - 如何获取单词和等号以及等号和值之间的文本?

java - 无法将字符串转换为 int (Java)

python-2.7 - 是否可以使用机器人框架进行Windows Mobile测试?