Programming

with Snakes (part 5)
and Turtles

Colours


You can fill a shape with a colour using the following commands:

# set the colour to use as to "fill in" the shape
fillcolor('yellow')

# everything after this command (and before the
# end-fill command) will be filled with colour
begin_fill()

# everything after this will not be filled in
end_fill() 

Being Lazy


Sometimes you want to do the same thing over and over again but with slight changes.

Programming languages have something called "loops" that allow you to do just that.

A loop allows you to run the same set of commands multiple times and (in the case of the "for" loop) have a variable that changes on each loop iteration.

Python "for" Loop


In Python, the "for" loop has the following format

for <variable name> in range(<start>, <end>, <increment>):
  # loop commands are indented
  # a consistent number of spaces 

<variable name>    is the variable that is going to change
<start>    is the starting value for <variable name>
<end>    is the ending value
<increment>    is the amount to add to <variable name> on each iteration

Values inside of the loop


for sideLength in range(10, 100, 20):  print sideLength

The following will be output in the terminal window:

10
30
50
70
90

    Values inside of the loop


    for index in range(1, 5):  print index

    The following will be output in the terminal window:

    1
    2
    3
    4

    If <increment> is not specified  then Python assumes 1.

    Values inside of the loop


    for nickels in range(3, 5):  pennies = nickels * 5  print pennies

    The following will be output in the terminal window:

    15
    20

    Everything that is in the loop is indented the same number of spaces. Spacing in Python is important.

    Ending a Loop


    for <variable name> in range(<start>, <end>, <increment>):
      # loop commands are indented
      # a consistent number of spaces 

    A Python "for" loop ends when <variable name> is equal to or greater than <end>

    Another way of thinking of it is that <variable name> will take the values "up to but not including" <end>

    "For" Example


    for sideLength in range(10, 100, 20): 

    1. set sideLength to 10
    2. check if sideLength < 100; if it is, goto 3; if it is not, goto 6
    3. do all the commands in the loop (not shown)
    4. add 20 to sideLength (i.e. sideLength = sideLength + 20)
    5. goto 2.
    6. do the next command after the loop

    Some Samples


    I have created a program that draws a number of nested squares (click link to download code). There are lots of comments describing what is happening.

    There is another that draws a spiral (click link to download code).

    There are some additional tips in the code comments.

    Programming in Python - Part 5

    By gordie

    Programming in Python - Part 5

    • 839