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")