The MakeSentence(): finishes once it hits the return statement, so you have several print statements that execute after that seemingly repeated again?
You could have this return a list or tuple:
def MakeSentence(): #makes sentence by combining name, verb, and noun
"""
(None)->List
Returns a list with a random name, verb and noun
"""
x = [random_name(), random_verb(), random_noun()]
return x
You can make many of these, but for example, try this:
sample = MakeSentence()
And to print it in the format above:
print(sample[0] + " is " + sample[1] + " " + sample[2])
Hope this solves it for you!
How can I store the first random name, verb, and noun to be used in
further statements?
After running, you can see what is happening in the interpreter: that the function returns a list with three strings inside, and you can use the bracket notation [0], [1] and [2] to access each of these as shown below. These three things are available for you until or unless you over-write them.
>>> sample = MakeSentence()
>>> print(sample)
['Sean', 'eating', 'apples']
>>> print(sample[0] + " is " + sample[1] + " " + sample[2])
Sean is eating apples
If I wanted to get many samples, I could do this:
many_samples = [] # make a list to store many lists
for users in range(3): # to generate three samples: change to larger number if desired
many_samples.append(MakeSentence())
An example of the nested list might be something like this (but this is rearranged to make it easier to read):
>>> print(many_samples)
[
['Sean', 'eating', 'apples'],
['Jane', 'drinking', 'oranges'],
['Jim', 'chopping', 'chairs']
]
# to print out these in a format as you had in the example:
for each_elem in many_samples:
print(each_elem[0] + " is " + each_elem[1] + " " + each_elem[2])
so we are iterating through the list, and each element in the list is another list.
In each sub-list, we take the first (a position 0), second and third (at position 2) elements and have them plugged into our string output.
5
solved Keeping random name in Python