Douglas G. Wright III
Douglas G. Wright III

Reputation: 11

Puzzling out how a simple python 2.7 program works

I'm super new to this and I'm trying to puzzle my way through is code and I'm stuck, I don't know how the program is referencing the lists I've copied/created. At the end it makes a new list called 'words'. I don't understand how 'words' is getting my previous lists inside of it.

'''
Making silly Sentences Game
'''
name = ['Bob', 'Rachel', 'Don']
verb = ['slaps', 'steals', 'jumps over']
noun = ['jello', 'car', 'U-571']

from random import randint 

def pick (words):
    num_words = len(words)

    num_picked = randint(0, num_words -1)

    word_picked = words[num_picked] **#THIS BIT HERE!!! How does it know what 'words' is?**

    return word_picked

print (pick(name),pick(verb), 'a', pick(noun))

This is my first post so, I'm almost certain it's in the wrong place. Please be gentle.

Upvotes: 0

Views: 36

Answers (2)

Daniel Roseman
Daniel Roseman

Reputation: 600026

It knows what words is because you told it.

When you did def pick(words) you defined a function which takes one argument, words. This means that whatever you pass as that argument will be available as words inside the function.

Now, when you called pick(name), you passed in the value name as the argument. So the value that was known as name is passed into the function, which receives it as words.

Upvotes: 1

Robin Davis
Robin Davis

Reputation: 632

This has to do with scope. The line word_picked = words[num_picked] can "see" words because it is in the scope of the function pick(), which takes a single arguments words. So when you call pick(name), within the scope of pick(), words is now pointing to name.

Upvotes: 1

Related Questions