【发布时间】:2019-11-05 14:20:32
【问题描述】:
老师给我的作业是用python在一行代码中显示“啤酒之歌”。歌曲在这里:http://www.99-bottles-of-beer.net/lyrics.html
我正在使用 python 3.7 并在 Pycharm 上运行它。我分两行搞定了,但是老师坚持说,一条就可以搞定。
如果它难以阅读,我很抱歉。我写的代码如下:
for i in range(99, -1, -1):
print("%d bottles of beer on the wall %d bottles of beer on the wall...\nTake one down and pass it around, %d bottles of beer\n" % (i, i, i - 1) if i > 2 else ("2 bottles of beer on the wall, 2 bottles of beer on the wall...\nTake one down and pass it around, 1 more bottle of beer" if i > 1 else ("\n1 bottle of beer on the wall, 1 bottle of beer on the wall...\nTake one down and pass it around, No more bottles of beer" if i>0 else ("\nNo more bottles of beer on the wall, no bottles of beer on the wall...\nGo to the shop and buy some more, 99 more bottles of beer"))))
【问题讨论】:
-
为什么不把你想打印的东西赋值给一个变量,然后再打印这个变量
-
您可以在 print 语句中使用列表推导并打印结果列表
-
这本身是不可读的。我会再次将其分成多行。不知道为什么老师会问其他方式。
-
你想查看列表推导
-
@Devesh Kumar Singh,正是我所做的。这就是为什么它带我两条线......
标签: python python-3.x for-loop printing while-loop