The Same Loop in Python
Everything you have learned here transfers. To prove it, here is the same square in Star Blocks and in Python, side by side. The words move around and the brackets become a colon, but the idea, repeat these two moves four times, does not change at all.
π‘ The idea
Languages differ in punctuation, not in ideas: a loop is a loop everywhere.
- Star Blocks: repeat 4 [ forward 100 right 90 ] draws the square below.
- Python - try this on a computer at home. Line 1: import turtle
- Python line 2: for i in range(4): and the colon at the end opens the block.
- Python line 3, indented by four spaces: turtle.forward(100)
- Python line 4, indented by the same four spaces: turtle.right(90)
- Python line 5, back at the left margin: turtle.done()
- So the square brackets become a colon plus indentation, and range(4) is Python's way of saying four times.
- import turtle loads a ready-made library of drawing commands, which is why every command starts with turtle.
π Words to know
- syntax
- the punctuation and spelling rules of a language
- indentation
- the spaces at the start of a line, which Python uses to mark a block
- library
- ready-made code you import, such as turtle
- range
- Python's way of saying how many times to repeat
π Watch this
The Star Blocks square. The Python version above draws exactly the same square on a home computer.
repeat 4 [ forward 100 right 90 ]
βοΈ Your turn
- Run the Star Blocks square here and be sure you know what each part does.
- Copy the six Python lines into a notebook, keeping the indentation exactly right.
- Match them up: which Star Blocks word became which Python word?
- Now write the hexagon in Star Blocks below.
- Write the Python hexagon too: for i in range(6): then turtle.forward(80) and turtle.right(60), both indented by four spaces.
- At home, save your file as square.py and run it with python square.py
π― Challenge: Write the hexagon in Star Blocks here, then write the same loop in Python in your notebook and check your indentation line by line.
Show me one answer
repeat 6 [ forward 80 right 60 ]
Your program