Есть ли способ написать цикл FOR ВНУТРИ оператора PRINT? - PullRequest
1 голос
/ 23 июня 2019

Домашнее задание, данное мне моим учителем, состоит в том, чтобы отобразить «Пиво» в одной строке кода, используя python. Песня здесь: http://www.99 -bottles-of-beer.net / lyrics.html

Я использую Python 3.7 и запускаю его на Pycharm. У меня это в 2 строки, но учитель настаивает, это можно сделать в одну.

Извините, если трудно читать. Код, который я написал, выглядит следующим образом:

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"))))

Ответы [ 3 ]

2 голосов
/ 23 июня 2019

Используйте понимание списка и join для генерации всего текста в одну строку:

print('\n\n'.join([f'{i} bottle{"" if i==1 else "s"} of beer on the wall, {i} bottle{"" if i==1 else "s"} of beer.\nTake one down and pass it around, {"no" if i==1 else i-1} bottle{"" if i-1==1 else "s"} of beer on the wall.' for i in range(99,0,-1)]) + '\n\nNo more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.')

Вывод:

99 bottles of beer on the wall, 99 bottles of beer.
Take one down and pass it around, 98 bottles of beer on the wall.

98 bottles of beer on the wall, 98 bottles of beer.
Take one down and pass it around, 97 bottles of beer on the wall.

97 bottles of beer on the wall, 97 bottles of beer.
Take one down and pass it around, 96 bottles of beer on the wall.

...

2 bottles of beer on the wall, 2 bottles of beer.
Take one down and pass it around, 1 bottle of beer on the wall.

1 bottle of beer on the wall, 1 bottle of beer.
Take one down and pass it around, no bottles of beer on the wall.

No more bottles of beer on the wall, no more bottles of beer.
Go to the store and buy some more, 99 bottles of beer on the wall.
0 голосов
/ 23 июня 2019

Благодаря @Mark Tolonen и последнему редактированию @LEEE я выполнил решение без грамматических ошибок.

Начальные строки кода просто выводят то, что требовалось и запрашивалось,

print('\n'.join(f'{i} bottles of beer on the wall, {i} bottles of beer...
\nTake one down and pass it around, {i-1} bottles of beer on the wall.'

, но при добавлении, если еще печатается без грамматической ошибки "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 ("1 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 ("No 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."))) 

for i in range(99,-1,-1)))

Поверьте, это все в 1 строке !!! Я так счастлив!

Выход:

99 bottles of beer on the wall, 99 bottles of beer...
Take one down and pass it around, 98 bottles of beer on the wall.
98 bottles of beer on the wall, 98 bottles of beer...
Take one down and pass it around, 97 bottles of beer on the wall.
...
2 bottles of beer on the wall, 2 bottles of beer on the wall...
Take one down and pass it around, 1 more bottle of beer.
1 bottle of beer on the wall, 1 bottle of beer on the wall...
Take one down and pass it around, no more bottles of beer.
No more bottles of beer on the wall, no bottles of beer on the wall...
Go to the shop and buy some more, 99 more bottles of beer.
0 голосов
/ 23 июня 2019

Да, есть. Понимание списка позволяет использовать цикл for для создания списка. Это выглядело бы так: (извините, что не решил полностью, не может быть обеспокоен)

[<expression> for <element name> in <iterable>]

Например:

[abs(i) for i in range(-5, 5)]

вернется

[5, 4, 3, 2, 1, 0, 1, 2, 3, 4]

Редактировать: чтобы добиться того, чтобы каждый элемент печатался в отдельной строке, используйте

print("\n".join(<list>))
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...