Solutions for exercises on loops

main
ana mertens 3 years ago
parent 10194f6209
commit 3bcf9bec44

@ -0,0 +1,40 @@
### Exercise 1. Print a list of words of the song
# + next to each word its position in the sentence
# Prince, Purple Rain (using a hashtag = making a comment)
song = "I never meant to cause you any sorrow\n \
I never meant to cause you any pain\n \
I only wanted to one time to see you laughing\n \
I only wanted to see you\n \
Laughing in the purple rain."
# each word has a unique number
pos = 0
words = song.split()
for word in words:
print(word, pos)
pos += 1
# index of words, using string method index()
for word in words:
print(word, song.index(word))
### Exercise 2: rewrite song by copying words with r to the beginning of the song
words_with_r = []
for word in words:
if 'r' in word:
words_with_r.append(word)
new_text = words_with_r + words
print(' '.join(new_text))
### Exercise 3: create an Anaerobe of the song (remove all rs)
new_song = []
for word in words:
if 'r' in word:
word = word.replace('r','')
new_song.append(word)
else:
new_song.append(word)
print(' '.join(new_song))
Loading…
Cancel
Save