I am creating a random sentence generator that can apply the correct indefinite article (a, an) to the sentence. But I am getting results such as these: I eat a apple. I ride an bike. You eat an apple. "a" should come before the consonant, and "an" should come before the vowel: an apple; a bike. What am I doing wrong?
Import random
def main():
pronoun = ["I ", "You "]
verb = ["kick ", "ride", "eat "]
noun = [" ball.", " bike.", " apple.", " elephant."]
ind_art = "an" if random.choice(noun[0]).lower() in "aeiou" else "a"
a = random.choice(pronoun)
b = random.choice(verb)
c = ind_art
d = random.choice(noun)
print(a b c d)
main()
CodePudding user response:
When you call random.choice
it returns a new value each time. So the random word in the line where you create your ind_art
is a different word from the one that gets assigned to d
.
You need to reorder your code so that d
is used when determining the article.
d = random.choice(noun)
ind_art = "an" if d[0].lower() in "aeiou" else "a"
CodePudding user response:
I fixed some lines in your code. Now, it works fine.
import random
def main():
pronoun = ["I ", "You "]
verb = ["kick ", "ride ", "eat "]
noun = ["ball.", "bike.", "apple.", "elephant."]
ch = random.choice(noun).lower() # <===== fixed this line
# print(ch[0]) # test
ind_art = "an " if ch[0] in "aeiou" else "a " # <===== fixed this line
a = random.choice(pronoun)
b = random.choice(verb)
c = ind_art
# d = random.choice(noun) # <===== removed this line
print(a b c ch) # <===== replaced d with ch
main()