-4

I'm learning Python and have cobbled together a random sentence generator to practise. How do I keep the first randomly-chosen name for the subsequent sections?

I have this:

def random_name():
    line_num = 0
    selected_line = ''
    with open('names.txt') as f:
        while 1:
            line = f.readline()
            if not line: break
            line_num += 1
            if random.uniform(0, line_num) < 1:
            selected_line = line
    return selected_line.strip()

Repeated for verb and noun. Then I define the sentence:

def MakeSentence(): #makes sentence by combining name, verb, and noun

x = random_name() + " is " + random_verb() + " " + random_noun()
return x

print("Type Yes to continue.")
print("\n")
print("Enter 'Q' to quit.")
print("\n")
response = 'x' #generic response as to not cause problems

while (response != 'Q'): #case switch kills it all

response = input("Would you like to continue?\n")
if response == 'Q':
    break
elif response == 'Yes':
    print(MakeSentence())

response = input("Is " + random_name() + " correct?\n")
if response == 'Q':
    break
elif response == 'Yes':
    print(random_name() + " is correct.\n")

1 Answers1

0

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.

srattigan
  • 665
  • 5
  • 17
  • Thank you. I've tried this but when I add [0] it ends up just printing the first letter of the name. What am I doing wrong? e.g. response = input("Is " + sample_name[0] + " correct?\n") gives: Is K correct? – afilmforthefuture Aug 28 '17 at 11:56
  • My aim was to show "How can I store the first random name, verb, and noun to be used in further statements?" If you just call the function random_name() to generate a name, then only a single string is returned. Accessing a character in a string is similar to accessing an element in a list, so if you get the string "Mike" assigned to a variable called 'name' and print out name[0], you will indeed only get the first character. I can add another comment or more detail, or another example if you need it? I've already added some detail and comments with additional code above. :) – srattigan Aug 28 '17 at 15:39
  • Thank you, srattigan. You've been very helpful :) – afilmforthefuture Aug 29 '17 at 19:15
  • If the answer above meets your question, could you please select it as the accepted answer? Many thanks, Sean. – srattigan Aug 29 '17 at 19:18
  • Thanks. The method above for creating the string works fine, and is easy to follow, but a more elegant method you might consider in a future revision is shown here: https://stackoverflow.com/questions/5082452/python-string-formatting-vs-format best of luck with it! – srattigan Aug 29 '17 at 20:38