From blocks to text: the same ideas in Python
Be able to translate a block program into Python line by line.
Prerequisites
Intuition
Everything you can do in Scratch exists in Python — the same ideas, different notation.
| Block | Python |
|---|---|
say «Hi» | print("Hi") |
set score to 0 | score = 0 |
change score by 1 | score = score + 1 |
repeat 10 times | for i in range(10): |
forever | while True: |
if <condition> then | if condition: |
wait 1 second | time.sleep(1) |
ask «Name?» | name = input("Name? ") |
The new part is the indentation: in Scratch the block wraps around whatever belongs to the loop; in Python it is marked with four spaces.
Code
The block program:
when green flag clicked
set score to 0
repeat 5 times
change score by 2
say score
say «Done!»
The same thing in Python:
score = 0
for i in range(5):
score = score + 2
print(score)
print("Done!")
Output: 2, 4, 6, 8, 10, Done!
Notice that print("Done!") sits outside the indentation, so it runs once. Had it been indented it would have printed five times. Indentation is not decoration — it is the program.
Mastery means
- Translates a block program into Python
- Recognises the same concepts in both forms
Sign in to do the exercises and build your mastery up.
Sources
- Scratch Wiki (CC BY-SA 4.0) — CC BY-SA 4.0
- The Python documentation (PSF licence) — PSF