Reputation: 23
I am an artist taking a class on how to manipulate code to make poetry. Python was not supposed to be a prerequisite, but I am not getting it! Please help- we are supposed to make a snowball poem. Here's the code I have so far:
my_string = "you're going home in a Chelsea ambulance"
counter = 0
new_list = my_string.split()
def make_a_snowball (text):
poem = ' '
for i in text:
poem = poem + "\n" + i
print (poem)
make_a_snowball (new_list)
The result is:
you're
going
home
etc..
I'd like it to look like:
you're
you're going
you're going home
etc...
Any suggestions? Help would be appreciated.
Upvotes: 1
Views: 70
Reputation: 4238
The reason the code is printing each item on a new line is because we are inadvertantly adding a newline character between the terms, when we should be adding a space character.
In the following code, if we replace the \n
with a " "
and shift the print()
function inwards so that it prints every time we loop through the items of the list, then this should work just fine.
my_string = "you're going home in a Chelsea ambulance"
counter = 0
new_list = my_string.split()
def make_a_snowball (text):
poem = ' '
for i in text:
poem = poem + " " + i
print (poem)
make_a_snowball (new_list)
This results in:
you're
you're going
you're going home
you're going home in
you're going home in a
you're going home in a Chelsea
you're going home in a Chelsea ambulance
A couple of additional thoughts.
In your code above, a counter
is not necessary.
I like my code to be somewhat self descriptive, so I might replace this:
for i in text:
poem = poem + " " + i
print (poem)
with
for word in text:
poem = poem + " " + word
print (poem)
Upvotes: 0
Reputation: 6857
If you want to have your whole poem be stored in one long string, here's how you'd do it:
def make_a_snowball(text):
poem_line = ''
full_poem = ''
for word in text:
poem_line += word + ' '
full_poem += poem_line + '\n'
print(full_poem)
return full_poem
This prints exactly what you want, except all at once rather than line-by-line.
Upvotes: 0
Reputation: 24234
You just need to move the print method inside the loop:
my_string = "you're going home in a Chelsea ambulance"
counter = 0
new_list = my_string.split()
print(new_list)
def make_a_snowball(text):
poem = ' '
for word in text:
poem = poem + ' ' + word
print(poem)
make_a_snowball(new_list)
Upvotes: 1