首页 > 解决方案 > 有什么方法可以返回将作为长度为 8 的字符串输出的随机辅音或元音?

问题描述

我对计算机科学完全陌生,不确定如何收集结果并将它们作为 8 个字符串返回给用户。

这是我根据用户要求为用户提供 8 个随机辅音或元音的代码。

count = 2
while count < 10:
char = input("v or c")
if char == "v":
    vow = ['a', 'e', 'i', 'o', 'u']
    v = random.choice(vow)
    print(v)
    count = count + 1

if char == "c":
    con = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 
't', 'v', 'w', 'x',
                 'y', 'z']
    c = random.choice(con)
    print(c)
    count = count + 1`

标签: python

解决方案


只需在列表或字符串中收集随机选项:

vowels = 'aeiou'  # random.choice can choose from any type of sequence
consonants = 'bcdfghjklmnpqrstvwxyz'
chars = []  # collects the choices
for _ in range(8):  # for loop if iteration count is known beforehand
    select_char = input("Please enter either v for a vowel or c for a consonant: ")
    if select_char == "v":
        chars.append(random.choice(vowels))
    else:
        chars.append(random.choice(consonants))

print(''.join(chars))

推荐阅读