首页 > 解决方案 > 如何使用random.choice 和alternation 循环?

问题描述

我正在尝试创建一个随机名称生成器,其中名称的长度为 8 个字符。我希望它在 1-2 个元音和 1-2 个辅音之间交替,直到达到 8 个字符长度。

找到答案,弄乱了这里代码的更新,所以我不得不删除它,但复选标记是正确的方法。

标签: python

解决方案


您应该使用while循环代替if语句。

import random

vowels=('a', 'e', 'i', 'o', 'u', 'y')
consonants=('b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p',
            'q', 'r', 's', 't', 'v', 'w', 'x', 'z')


full_name = random.choice(vowels) + random.choice(consonants)

while len(full_name) < 8:
    full_name += random.choice(vowels) + random.choice(consonants)
else:
    print(full_name)

推荐阅读