mercredi 26 octobre 2016

Use the same Random Generated Number Several Times

I'm writing a code where the user inputs a sentence, inputting one word at a time. When they type 'exit', the code returns "Your original sentence was sentence. Word number (generate random number) is (the word that corresponds to that number)".

For example, the sentence is "This is a cool code", it'll return "Your original sentence was This is a cool code. Word number 3 is a.

Right now, my code gets two different random numbers and words and says 'list index out of range' when the sentence has more than 4 words. How should I fix this and get it to work properly?

def sentenceSplit():
    print ('Think of a sentence')
    print ('Type the sentence one word at a time pressing enter after each word')
    print ("When you have finished the sentence enter 'exit'")
    print ('')
sentence = []
while True:
    word = input('')
    print ('Accepted', word)
    if word == 'exit':
                print ('')
                print ('Your original sentence was')
                outputString = " ".join(sentence)
                print (outputString)
                wordCount = int(len(outputString))
                pleaseWork =  (random.randint(0,wordCount))
                print('Word number ',pleaseWork,' is ', (sentence[pleaseWork]))

                break
    sentence.append(word)




Aucun commentaire:

Enregistrer un commentaire