Catch只允许在for语句中使用2种输入类型

时间:2013-04-02 18:12:03

标签: python python-3.x

当它运行时,用户可以通过输入'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)

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

您的代码存在一些问题:

  1. 无论输入如何,它都会转到下一个字母。
  2. 如果输入不是"c""v",则不会处理此案例。
  3. 它没有向用户提供有关无效输入的任何消息。
  4. 我在这里做了什么:
    在for循环的每次迭代中,我们进入一个无限循环,一直持续到有效输入为止。

    1. 取第一个输入,然后输入while循环。
    2. 对于有效输入,在“有效”处理之后,我们break inf循环,然后移动到下一个字母。
    3. 对于无效输入,我们显示错误消息,再次输入,然后转到2.
    4. “固定”版本 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 进行一些额外的调整