Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random Phrase Creator

I want to create a program that will generate a random phrase by creating 10 random integers that are from 1 to 20, and depending on each variables integer, a certain word or phrase will be produced. Is there an easier way to do it than the following:

#This is a random phrase generator
import random
Rand1 = random.randint (1, 20)
Rand2 = random.randint (1, 20)
Rand3 = random.randint (1, 20)
Rand4 = random.randint (1, 20)
Rand5 = random.randint (1, 20)
Rand6 = random.randint (1, 20)
Rand7 = random.randint (1, 20)
Rand8 = random.randint (1, 20)
Rand9 = random.randint (1, 20)
Rand10 = random.randint (1, 20)
    if Rand1 ==1:
        print ('Squirrel')

and so on... P.S. Using Python 3

Thank you for the helpful advice. I am new to python, and it is very helpful to have people who can help me create better code. If anyone cares, I used this for a program that talks to you, and offers you the chance to hear jokes and play several games. Have a nice day.

PPS I ended up going with:

import random
words = 'squirrel orca ceiling crayon boot grocery jump' .split()
def getRandomWord(wordList):
    # This function returns a random string from the passed list of strings.
    wordIndex = random.randint(0, len(wordList) - 1)
    return wordList[wordIndex]
potato = getRandomWord(words)
print (potato) # plus of course all the other words... this is just the base.
like image 353
John Campbell Avatar asked Jan 28 '26 21:01

John Campbell


1 Answers

Sure. Use Python lists and/or dictionaries. If you choose from one group:

words = ['Some', 'words', 'any', 'number', 'of', 'them']
choices = [random.choice(words) for _ in range(10)]
print(' '.join(choices))

If not, you can use a nested list:

words = [['Sam', 'Joe'], ['likes', 'hates'], ['apples', 'drugs', 'jogging']]
choices = [random.choice(group) for group in words]
print(' '.join(choices))

This can be extended to any number of groups and words in each group.

like image 60
Lev Levitsky Avatar answered Jan 30 '26 13:01

Lev Levitsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!