gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:33:41 26 4
gpt4 key购买 nike

我正在尝试使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com