Coding Curriculum - Python

Using while loops

'while' loops are useful when you want to repeat an action a certain number of times. Let's say the computer knew you had 5 different cupcake flavours, but it didn't know which ones. Therefore, the computer needs to ask you 5 times the name of the flavours, so it can create the list.

listOfFlavours = [] # At first, the list is empty
flavourNumber = 1 # You start at the 1st flavour, but remember it has index 0 
while flavourNumber < 5:
flavour = raw_input("What is flavour "  + str(flavourNumber) + "?")
listOfFlavours.append(flavour)
flavourNumber = flavourNumber+1

This loop will keep going and asking you for flavours until the flavourNumber isn't less than 5. Also, the str() function will convert the number flavourNumber into a character, so that it can be added to the string. For the first loop, the output will be:

What is flavour 1?
# You can say: chocolate

Now your list looks like this:

listOfFlavours = ['chocolate']

Awesome, now you have enough functions to start the first worksheet! Let's go.