In programming, it is often very useful do carry out a the same action for a series of different items. You might, for instance, want to go through a list of words and count and print the number of characters in each word. Now, you could do this for each word individually and access every word, one item at a time
fruits = ["apple", "pear", "peach", "banana", "peach", "cherry", "orange", "kiwi"] print(len(fruits)) print(len(fruits)) print(len(fruits))
This is a lot of repetitive typing. Luckily, Python provides the so-called
for-statements for this. The
for loop allows us to iterate through any iteratable object, such as a list, and do the same thing with each of its elements. The basic format of a
for a_single_item in an_iterable_something: do_something_with(a_single_item)
We can print all letters of the word wonderful as follows:
for letter in "wonderful": print(letter)
Likewise, we can print all the items that are contained in the fruit list:
for fruit in fruits: print(fruit)
Exercise: REMIX SONG using STRING, LIST and FOR, IN, IF
# 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.”
Transform string in list of words. Double all words of list and print this list again as a song: use the for statement, declare a new list outside of the loop and append all doubled words to this new list, transform this new list into a string.
Note that you can combine IF and FOR. We rewrite the song with the words that count more than 4 letters.
remix_2 =  for word in song: if len(word)<= 4: remix_2.append(word) print("°*@".join(remix_2))
There are different operators possible: larger than, smaller than, equal to, larger than and equal to, smaller than and equal to.
Note that you will often encounter a more compact way to write the same.
remix_2 = [word for word in song if len(word) <= 4] print(remix_2)
Exercise: print a list of words of the song + next to each word its position in the sentence
Exercise: rewrite song by copying words with r to the beginning of the song
Exercise: create an Anaerobe of the song (remove all r’s)
A while loop statement in Python programming language repeatedly executes a target statement as long as a given condition is true. The risk of using ‘while’ is the possibility of triggering infinite loops.
For example, let’s print our song 9 times:
amount = 0 while (amount < 10): print(' '.join(song)) amount = amount + 1 else: print("Python can be a printing factory!")
What you’ve learned
- different operators