The_Official_Raspberry_Pi_-_Beginner’s_Book_Vol1,_2018 (1)

(singke) #1
Chapter 5 Programming with Python 107

THE OFFICIAL RASPBERRY PI BEGINNER’S GUIDE


Start by deleting the code for drawing your parallelogram-based snowflakes: that’s
everything between and including the pat.color("cyan") instruction on line 10 through
to pat.right(36) on line 17. Leave the pat.color(random.choice(colours))
instruction, but add a hash symbol (#) at the start of the line. This is known as commenting
out an instruction, and means that Python will ignore it. You can use comments to add
explanations to your code, which will make it a lot easier to understand when you come back
to it a few months later or send it on to someone else!
Create your function, which will be called ‘branch’, by typing the following instruction onto
line 10, below pat.pendown():


def branch():

This defines your function, branch. When you press the ENTER key, Thonny will
automatically add indentation for the function’s instructions. Type the following, making sure
to pay close attention to indentation – because at one point you’re going to be nesting code
three indentation levels deep!


for i in range( 3 ):
for i in range( 3 ):
pat.forward( 30 )
pat.backward( 30 )
pat.right( 45 )
pat.left( 90 )
pat.backward( 30 )
pat.left( 45 )
pat.right( 90 )
pat.forward( 90 )

Finally, create a new loop at the bottom of your program – but above the commented-out
colour line – to run, or call, your new function:


for i in range( 8 ):
branch()
pat.left( 45 )
Free download pdf