[Tutor] Function help
Peter Otten
__peter__ at web.de
Sun Feb 23 10:26:59 CET 2014
Scott W Dunning wrote:
>
> On Feb 23, 2014, at 1:12 AM, Scott W Dunning <swdunning at cox.net> wrote:
>
>> I am VERY new to python (programming too). I had a question regarding
>> functions. Is there a way to call a function multiple times without
>> recalling it over and over. Meaning is there a way I can call a function
>> and then add *5 or something like that? I am trying to code an American
>> Flag using turtle for class so I’ll post the code I have so far below.
>> As you can see towards the bottom I recall the functions to draw the
>> stars, fill in color and give it spacing. I was wondering if there was a
>> way to cut down on all that some how?
>>
>> Thanks for any help!
The example helps a lot! And of course this process of "cutting down",
achieving complex tasks by doing simple things repetetively is what
programmers do all the time. There is even a principle called "DRY" (don't
repeat yourself) meaning that if you have to write something twice in your
code you are doing it wrong.
Looking at
> fillstar(red)
> space(25)
> fillstar(red)
> space(25)
> fillstar(red)
> space(25)
> fillstar(red)
> space(25)
> fillstar(red)
> space(25)
a programmer would think "for loop" immediately
for i in range(5):
fillstar(red)
space(25)
and as this sequence occurs more than once in your code you should make it a
function. For example:
def star_row():
for i in range(5):
fillstar(red)
space(25)
If you want to make rows with more or less stars, or stars in other colors
you could add parameters:
def star_row(numstars, starcolor):
for i in range(numstars):
fillstar(starcolor)
space(25)
Your code will then become
star_row(6, red)
row(25)
star_row(5, red)
row(25)
...
which still shows a repetetive pattern and thus you can simplify it with
another loop. You should be able to find a way to write that loop with two
star_row() calls on a single iteration, but can you do it with a single call
too?
More information about the Tutor
mailing list