Coding Curriculum - Python

Constructing the Grid

During this lesson, we will teach you some tips that will help us to construct the grid.

Using the len() function with dictionaries. If we have a list that contains dictionaries, we can use a for loop to access every single element in that dictionary and if we want to find the length of a string in that dictionary, we use len(itemName["key"]).

entries = [{"question":"…", "answer": "…"},
{"question":"…", "answer": "…"}]
for each_item in entries:
print len(each_item["answer"])

# Outputs: 3 3

Remember this because we will use it a lot when creating the grid. Next we will be learning a new function, called join().

entries = [{"question":"…", "answer": "…"},
{"question":"…", "answer": "…"}]
for each_item in entries:
print "-".join(each_item["answer"])
# Outputs: .-.-. .-.-.

The function takes in a string and return a string with each element separated by a string separator ("-" is the separator in this case). We use this when we want to print out a list, but we do not want those annoying commas.

Finally for the last part of the lesson, we will have a look at using the range() function in a for loop.

entries = [{"question":"…", "answer": "…"},
{"question":"…", "answer": "…"}]
for each_item in range(3):
print "."
# Outputs: . . .

The range() function works well in complement with the for loop. It is used to repeat something a certain number of times. For example in this case, it starts at 0 (we, programmers, always start counting from 0) and it stops at 2. This is because we are not including 3.

So first each_item will be 0 (which is smaller than 3), then for the second time, it will be 1 (which is still smaller than 3). For the third iteration, each_item is set to 2 (Still smaller). Finally, each_item is set to 3, which is not smaller than 3 and therefore it does not enter the loop.

Congratulations for completing this lesson. It is time to look at the worksheet!