我已经在互联网上搜索并尝试了代码的变体,但我只是不明白为什么当我在 Udacity 计算机科学入门的第 2 课中研究 PS 2 时,结果之间的输出为“无” .
这是 PS 和我当前的状态:
# Define a procedure, stamps, which takes as its input a positive integer in
# pence and returns the number of 5p, 2p and 1p stamps (p is pence) required
# to make up that value. The return value should be a tuple of three numbers
# (that is, your return statement should be followed by the number of 5p,
# the number of 2p, and the nuber of 1p stamps).
#
# Your answer should use as few total stamps as possible by first using as
# many 5p stamps as possible, then 2 pence stamps and finally 1p stamps as
# needed to make up the total.
#
def stamps(n):
if n > 0:
five = n / 5
two = n % 5 / 2
one = n % 5 % 2
print (five, two, one)
else:
print (0, 0, 0)
print stamps(8)
#>>> (1, 1, 1) # one 5p stamp, one 2p stamp and one 1p stamp
print stamps(5)
#>>> (1, 0, 0) # one 5p stamp, no 2p stamps and no 1p stamps
print stamps(29)
#>>> (5, 2, 0) # five 5p stamps, two 2p stamps and no 1p stamps
print stamps(0)
#>>> (0, 0, 0) # no 5p stamps, no 2p stamps and no 1p stamps
产生输出:
(1, 1, 1)
None
(1, 0, 0)
None
(5, 2, 0)
None
(0, 0, 0)
None
谁能解释一下“无”从何而来?
最佳答案
您正在调用打印结果的函数,然后打印该函数的返回值,即None
。
您应该选择一种显示数据的方法。 要么只在函数内部打印:
def stamps(n):
if n > 0:
five = n / 5
two = n % 5 / 2
one = n % 5 % 2
print five, two, one
else:
print 0, 0, 0
stamps(8)
stamps(5)
stamps(29)
stamps(0)
或者使用return
:
def stamps(n):
if n > 0:
five = n / 5
two = n % 5 / 2
one = n % 5 % 2
return five, two, one
else:
return 0, 0, 0
print stamps(8)
print stamps(5)
print stamps(29)
print stamps(0)
关于python - Udacity 深入计算机科学 (Python) 第 2 课 PS 印章 - 输出包括 "None",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40827161/