当它运行时,用户可以通过输入'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)
答案 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)
您的代码存在一些问题:
"c"
或"v"
,则不会处理此案例。我在这里做了什么:
在for循环的每次迭代中,我们进入一个无限循环,一直持续到有效输入为止。
break
inf循环,然后移动到下一个字母。 “固定”版本 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 进行一些额外的调整