From 3bcf9bec44c3e40d4549cc7c53a303c3f7fa2a62 Mon Sep 17 00:00:00 2001 From: ana mertens Date: Fri, 10 Dec 2021 11:20:03 +0100 Subject: [PATCH] Solutions for exercises on loops --- exercises_loop.py | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 exercises_loop.py diff --git a/exercises_loop.py b/exercises_loop.py new file mode 100644 index 0000000..ba198b9 --- /dev/null +++ b/exercises_loop.py @@ -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 r’s) +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))