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.
