[Tutor] I don't understand this code

Alan Gauld alan.gauld at btinternet.com
Wed Jul 14 14:21:39 CEST 2010


"ZUXOXUS" <zuxoxus at gmail.com> wrote

> 59.  words = 'ant baboon badger bat bear'
> 
>   1. def getRandomWord(wordList):
>   3.     wordIndex = random.randint(0, len(wordList) - 1)
>   4.     return wordList[wordIndex]
> 
> 
> The thing is, the "passed list of strings" is called "words", not
> "wordList", so I see it shouldn't work.

Note that wordList appears in the def line.
Have you studied functions yet? (I'm not familiar with your tutorial)
If so you should have read about parammeters or arguments?
parameters are local; variables within the function that take on 
the values passed to the function.

So if we define a function to return the square of a number:

def square(x):
     return x*x

We define the functon to have a parameter x.

When we call the function we must pass in a value for x:

foo = 20
bar = square(foo)

Notice that we pass foo to square() but the value inside 
the function is called x.

Now lets look again at your example:

>   1. def getRandomWord(wordList):
>   3.     wordIndex = random.randint(0, len(wordList) - 1)
>   4.     return wordList[wordIndex]

It has a parameter called wordList. That will take on the 
value passed into it and the reyrn value will be a random 
item from that list.

> On the other hand, the variable "wordList" is defined nowhere!

Yes it is, in the function definition.

So when you call it with

getRandomWord(words)

wordList takes on the value of words.

You can find an alternative explanation of functions, parameters 
and arguments in the "Modules and Functions" topic of my tutorial.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/





More information about the Tutor mailing list