Wrap Your Code Into a Function
00:00
Let’s put all that code into a function. I’ll define a function that I’ll call make_poem()
,
00:11 and it’ll take as an argument a tuple that contains a list of nouns, a list of verbs, a list of adjectives, a list of prepositions, and a list of adverbs in that specific order.
00:21
So this is all hidden inside of just saying that it takes words
in here, right? There’s more descriptive ways of doing this with type hints, for example.
00:30
But in this case, I’m not going to bother you with that. We’re just going to assume that my user knows what they need to pass into this make_poem()
function.
00:40 Because realistically, the only user is going to be myself here. So that’s usually not a good reason to write your code in a way that’s not super descriptive, but I’ll stick with it for now.
00:52
I’m going here to indent all of the code that I wrote so far, which is creating this empty nouns
list, and then iterating over the initial nouns
list that actually contains the nouns that I’m going to access through the variable that I’m passing as an argument to the make_poem()
function.
01:13
I also need to call it somewhere. So I’ll say make_poem()
01:24
So now I’m passing in the words
tuple that I’ve defined on line 10. And then what is, it’s going to be part of the function. The function’s going to run in the local scope.
01:36
It’s going to create a new variable called nouns
that points to an empty list. Then it’ll do a loop three times where it picks out a random word from the nouns
list that’s nested inside of the words
tuple, and then remove that word from the nouns
list in the words
tuple, and then append it to the nouns
list in the local scope of my make_poem()
function.
02:03
All right. It’s mind-bending to explain it, but I hope you’re following along and that this makes sense. Let’s try it out. I’m printing out the nouns
, and so I should be getting the same result that I did earlier, now that I’m calling the function.
02:19 So let’s try it out. I get a list of three
02:24 nouns every time I call it, and these three nouns are different every time.
02:30 Great. We’ve created a little safety local scope where I can do things without having to worry about overriding anything up here.
Become a Member to join the conversation.