1

在运行时,用户可以通过输入“c”或“v”来请求元音或辅音,否则会引发错误。

我将如何编辑代码以添加一个我认为可能是 isisntance 的捕获?

for i in range(9):
    x = input("letter("+str(i+1)+"), Would you like a consonant (c) or a vowel (v)? :")
    if x == 'c':
        randomLetters += getConsonant()
        print(randomLetters)
    elif x == 'v':
        randomLetters += getVowel()
        print(randomLetters)
return (randomLetters)

为感兴趣的人完成了代码,感谢您的回答帮助我完成了它。

for i in range(9):
    msg = "letter("+str(i+1)+"/9), Would you like a consonant (c) or a vowel (v)? :"
    x = input(msg)
    while x != "c" and x != "v":
        print("put a damn c or v in")
        x = input(msg)
    if x == 'c':
        randomLetters += getConsonant()
        print(randomLetters)
    elif x == 'v':
        randomLetters += getVowel()
        print(randomLetters)
return (randomLetters)
4

2 回答 2

0

假设您使用的是 Python 3.x,则input()返回一个字符串。所以:

for i in range(9):
    x = input("letter("+str(i+1)+"), Would you like a consonant (c) or a vowel (v)? :")
    if not x.isalpha(): raise TypeError('x can only have be a string')
    if x == 'c':
        randomLetters += getConsonant()
        print(randomLetters)
    elif x == 'v':
        randomLetters += getVowel()
        print(randomLetters)
return (randomLetters)

如果您只希望输入为“c”或“v”:

for i in range(9):
    while not x in ('c', 'v'):
        x = input("letter("+str(i+1)+"), Would you like a consonant (c) or a vowel (v)? :")
    if x == 'c':
        randomLetters += getConsonant()
        print(randomLetters)
    elif x == 'v':
        randomLetters += getVowel()
        print(randomLetters)
return (randomLetters)
于 2013-04-02T18:15:03.073 回答
0

您的代码存在一些问题:

  1. 无论输入如何,它都会移动到下一个字母。
  2. 当输入不是"c"or时,它不会处理这种情况"v"
  3. 它没有向用户提供有关无效输入的任何消息。

我在这里所做的:
在 for 循环中的每次迭代中,我们进入一个无限循环,该循环一直持续到给出有效输入为止。

  1. 取第一个输入,然后进入 while 循环。
  2. 对于有效输入,在“有效”处理之后,我们break进行 inf 循环,并移动到下一个字母。
  3. 对于无效输入,我们显示错误消息,再次输入,然后转到 2。

“固定”版本1

for i in range(1,10): # no need for the +1 in string.
    msg = "letter({0}), Would you like a (c)onsonant or a (v)owel? : ".format(i)
    x = input(msg) # raw_input(msg)
    while True: # infinite loop
        if x == 'c':
            randomLetters += getConsonant()
            print(randomLetters)
            break
        elif x == 'v':
            randomLetters += getVowel()
            print(randomLetters)
            break
        else: # x not in ['c','v']
            print('Invalid input, {0} is not valid'.format(x))
            x = input(msg) # get new input and repeat checks
return (randomLetters)

1 有一些额外的调整

于 2013-04-02T18:33:15.320 回答