dimanche 27 août 2017

Python - keeping random name

This is my first question. I hope I'm doing it right! I hope it's not too basic.

I'm learning Python and have cobbled together a random sentence generator to practise.

The current code chooses a new random_name each time.

I want to keep the first randomly-chosen name for the subsequent sections.

I've tried a few options but keep getting errors. Can someone help me store the first random name, verb, and noun to be used in further statements?

import random
import fileinput

#choose randoms

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

def random_verb():
    line_num = 0
    selected_line = ''
    with open('verbs.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()

def random_noun():
    line_num = 0
    selected_line = ''
    with open('nouns.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()

#functions

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

#prompt given with responses used to control flow
response = input("Would you like to continue?\n")
if response == 'Q':
    break
elif response == 'Yes':
    print(MakeSentence())

#prompt given with responses used to control flow
response = input("Is " + random_name() + " correct?\n")
if response == 'Q':
    break
elif response == 'Yes':
    print(random_name() + " is correct.\n")




Aucun commentaire:

Enregistrer un commentaire