Loops within Functions - Part 2

Loops inside functions! - Part 2

In the previous chapter, you have noted that
functions `right7′, `right8′, `right6′ are all
similar - the only difference is in the number with
which you are comparing `count’.

Look at the function below (there is no reason why it
is called `new_right’, you can use any other name):

def new_right(n):
    count = 0
    while count < n:
        count = count + 1
        right()

How is this function different?

We are writing an `n’ inside the brackets! And, we are
comparing count with this `n’!

Now, bring Neko to the top left corner and try the
following experiment at the Python prompt:

new_right(3)

Magic - Neko has moved right by 3 cells!

Now try:

new_right(4)

Yes - Neko has moved again, 4 cells to the right!

What is happening here?

Simple. When you write `new_right(3)’, the `n’ in the body
of the function gets the value 3 - so `count’ gets compared
with 3.

When you write `new_right(5)’, the `n’ in the body of the function
gets the value 5 - and `count’ gets compared with 5!

As you might have guessed, Computer Programmers have invented
some tricky words to describe this.

A programmer will say that `n’ is a `parameter’ to the function
`new_right’!

She will also say that when you write `new_right(4)’, you are
“passing 4 as value of parameter `n’”.

But we need not care too much about such big words!

You can put more than one value within the bracket. Here is
an example:

def sum(p, q):
    print p + q

Try doing:

>>> abc(10, 20)
30
>>>

Post a Comment

Your email is never published nor shared.