我问用户他们是否想要先行并使用输入验证,以便只接受“y”“Y”“n”或“N”作为有效回复。我运行它时,我的代码似乎崩溃了。
choice = raw_input("Would you like to go first or not? (y/Y or n/N): ")
print ""
try:
valid_choice = False
while not valid_choice:
if choice == "y" or choice == "Y":
users_turn = True
valid_choice = True
elif choice == "n" or choice == "N":
users_turn = False
valid_choice = True
break
else:
print "Invalid Choice."
except NameError:
print "You can only enter y/Y or n/N"
答案 0 :(得分:2)
question = "Would you like to go first or not? (y/Y or n/N): "
choice = raw_input(question)
while choice not in ['y', 'Y', 'n', 'N']:
print 'Invalid choice'
choice = raw_input(question)
users_turn = choice in ['y', 'Y']
话虽如此,我应该说控制台应用程序使用(Y/n)
来表示它接受字母y
或n
作为响应是一种常见模式大小写),但大写字母表示默认选项。
因此,如果您在第一次要求输入问题时可以信任用户做出决定,您可以设置默认响应并将其编码为:
choice = raw_input('Would you like to go first? (Y/n)')
users_turn = choice.lower() not in ['n', 'no']
答案 1 :(得分:0)
作为埃利亚斯回答的替代方案,我想提出以下内容:
while True:
choice = raw_input("Would you like to go first or not? (y/Y or n/N): ")
if choice in ["y", "Y", "n", "N"]:
break
print "Invalid choice"
users_turn = choice in ["y", "Y"]
最好不要重复询问行,但更糟糕的是while True
/ break
语法有点难看(如果Python有do
那就太好了...... while
喜欢C,但唉)。为自己选择最喜欢的。 :)
此外,只是要指出您自己的代码中的一些错误:
try
... except NameError
块完全是多余的,因为代码中的任何内容都不会抛出NameError
,尤其是不会发出实际用户错误的信号。else
行有错误的缩进。就目前而言,它与while
块而不是if
/ elif
块匹配,导致您很可能不想要的行为。break
块中的elif
是多余的,因为当您将while
设置为valid_choice
时,True
循环将会退出。答案 2 :(得分:0)
def get_one_of(prompt, options, default=None):
options = set(options)
while True:
val = raw_input(prompt)
if val == '' and default is not None:
return default
elif val in options:
return val
response = get_one_of('Do you want to go first? [Yn] ', 'yYnN', 'y')
users_turn = response in 'yY'