[Tutor] I don't understand this code

Peter Otten __peter__ at web.de
Wed Jul 14 13:08:01 CEST 2010


ZUXOXUS wrote:

> Hi,
> 
> I am a true beginner in programming, and im learning with
> inventwithpython.com.
> 
> There's something I dont understand, and i would really appreciate any
> help.
> 
> In chapter 9, the one about the Hangman game, I don't get the block of
> code in line 61
> 
> 59.  words = 'ant baboon badger bat bear'
> 60.
> 
>    1. def getRandomWord(wordList):
>    2.     # This function returns a random string from the passed list of
>    strings.
>    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.
> 
> On the other hand, the variable "wordList" is defined nowhere!
> 
> The code is ok, because the program runs ok. So there is somethings that i
> dont get.
> 
> Thank you very much in advance.

A value can have a different name inside a function when it is passed as a 
parameter. Consider the following session:

>>> def get_first_word(whatever_you_like):
...     return whatever_you_like[0]
...
>>> names = "peter paul mary".split()
>>> words = "nobody expects the spanish inquisition".split()
>>> get_first_word(names)
'peter'
>>> get_first_word(words)
'nobody'

Both the 'names' and the 'words' list of strings are referred to as 
'whatever_you_like' inside the get_first_word() function.

Peter



More information about the Tutor mailing list