GoalTranslate a small program between blocks and text and explain how the parts match.
New words
translate · to rewrite a program in another language so that it does the same jobvariable · a named place where a program keeps a valuefor loop · a text-based way to repeat lines a set number of timesoutput · what a program shows or prints
Explanation
A program can be written in blocks or in text, and it does the same job. To translate a program, match the parts one by one. A set block that makes a variable matches a line such as total = 0. A repeat block matches a for line. A change block matches a line that works out the new value, such as total = total + 5. A say block matches a print line. In Python, range(3) gives 3 rounds. The lines that belong inside a loop or an if are indented. After translating, trace the new program to check that it gives the same result. A robot or a sensor board can be programmed in either kind of language.
Worked examples
Python
1total = 02for i inrange(3):
3 total = total + 54print(total)
Output
15
This is the text-based version of the blocks in the picture above. Each line matches one block, and the output is 15.
Blocks
Text
set [total] to (0)
total = 0
repeat (3)
for i in range(3):
change [total] by (5)
total = total + 5
say (total)
print(total)
The parts of the two programs match one by one. Tracing the program gives total = 5, then 10, then 15.
Selection is translated in the same way. The if line ends with a colon and the lines inside are indented. With score = 12 the program prints big.
Class activity
Translation cards (no computer): write six block phrases on cards and the six matching lines of text on other cards, for example ‘repeat (4)’ and ‘for i in range(4):’, ‘say (n)’ and ‘print(n)’, ‘set [n] to (2)’ and ‘n = 2’. Shuffle them and match the pairs with a friend. Then write a three-line program in blocks and let your friend translate it into text. Trace both versions with the same numbers. If you have a computer or tablet, ask an adult to help you run a very short Python program.
Practice
1
Translate this program into Python and say what it prints.
n = 2, then for i in range(4): n = n * 2, then print(n). In Python * means multiply, like the * block in Scratch. The value of n goes 4, 8, 16, 32, so it prints 32.
2
Write the blocks for this Python program and say what it prints.
set [count] to (10), repeat (3) with change [count] by (-2), say (count). It prints 4, because 10 − 2 − 2 − 2 = 4.
3
Translate these blocks into Python and say what the program prints.
temp = 18, then if temp > 25: print("hot"), else: print("cool"), with the print lines indented. 18 > 25 is false, so it prints cool.
4
Mia says ‘block languages are not real programming’. What would you say to her?
Block languages teach the same ideas as text languages: sequence, selection, loops and variables. They are a good start, and what you learn helps with text languages later.