Loops within Functions - Part 1

You know how to write a loop to make Neko run eight places to
the right. The trouble is, you will have to repeatedly type
this loop whenever you wish to make Neko run eight places to the
right.

But we know an easy way out of this problem.

Just put the loop inside a function!

Go back and read chapter 5 once again if you have forgotten
what a function is!

Here is what you do:

def right8():
    count = 0
    while count < 8:
        right()
        count = count + 1

Here is what you will see at the Python prompt:

>>> def right8():
...     count = 1
...     while count < 9:
...         right()
...         count = count + 1
...
>>>

Now, whenever you want to move Neko to the right by 8 cells, simply
type `right8()’ at the Python prompt!

You have to be a bit careful when typing this. The lines `count = 1′
and `while count < 9′ are typed after typing a single `tab’;
but the lines in the body of the `while loop’ have to be typed after
typing two `tabs’.

Why?

Because, when you type a `tab’ before a line, Python considers
that line to be inside the `body’ of a function or a loop! Don’t
worry if you are starting to feel confused … everything will
become clear soon!

Another problem

Now we have another problem. Let’s say we have already written
a function `right8′ - now say you want to write two other functions
`right7′ and `right6′ which will move Neko to the right by seven
and six places respectively.

Here is `right7′:

def right7():
    count = 0
    while count < 7:
        right()
        count = count + 1

And, here is `right6′:

def right6():
    count = 0
    while count < 6:
        right()
        count = count + 1

This is stupid, isn’t it? Having to type things again and again
and again … computers are supposed to make things easy for us -
not difficult!

There is a very easy way out of this problem … read the next
chapter to find out!

Post a Comment

Your email is never published nor shared.