def numberToText(number):
if number == 1:
return('one')
elif number == 2:
return('two')
elif number == 3:
return('three')
elif number == 4:
return('four')
elif number == 5:
return('five')
elif number == 6:
return('six')
elif number == 7:
return('seven')
elif number == 8:
return('eight')
elif number == 9:
return('nine')
elif number == 10:
return('ten')
def tenGreenBottles():
print ("How many bottles to start with?")
bottles = int(input())
for i in range (bottles, 0, -1):
print "%g green bottles, hanging on the wall" %numberToText(i)
print "%g green bottles, hanging on the wall" %numberToText(i)
print "and if one green bottle, should accidentally fall"
bob = i - 1
print "there'd be %g green bottles." %numberToText(bob)
print
我一直在玩这段代码一段时间,无论我做什么,For Loop打印出NaN而不是字符串。当我使用For循环而没有字符串格式时,函数numberToText
按预期工作。
答案 0 :(得分:2)
你应该试试这个:
print "{} green bottles, hanging on the wall".format(numberToText(i))
我推荐的推理format
最初,在Python中,执行字符串插值的常用方法(这就是我们在这里讨论的)是使用格式字符串(例如%s
,%d
或{{1} })和字符串与要插入其中的内容之间的格式运算符。
但是,您必须为要插入的内容使用正确的格式字符串。
例如,要将字符串插入另一个字符串,请使用%g
:
%s
但是,如果您有想要插值的数字,通常会使用>>> print "%s green bottles, hanging on the wall" % "fifteen"
fifteen green bottles, hanging on the wall
:
%d
如果您犯了错误,则会收到错误消息:
>>> print "%d green bottles, hanging on the wall" % 15
15 green bottles, hanging on the wall
您似乎不熟悉Python,所以我建议您只使用>>> print "%d green bottles, hanging on the wall" % "15"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: %d format: a number is required, not str
,这是一种更新,更强大的字符串插值方法:
format
当您对字符串插值更加熟悉时,可以尝试使用 >>> print "{} green bottles, hanging on the {}".format(20, "balcony")
20 green bottles, hanging on the balcony
进行更高级的操作。您可能永远不需要再次使用format
来执行字符串插值。我建议您只关注并记住%
。