下面的函數應該做你想要的。
def get_input(message, choices):
assert type(message) == type("string"), "Message must be a string"
assert type(choices) == type([]), "Choices must be an array"
choice = ""
out = message + " (" + "/".join(choices) + "): "
while True:
c = input(out)
if c in choices:
break
else:
print "Please enter a valid choice"
return c
簡單地調用它像下面這樣:
get_input("Gender", ["M","F"])
一些測試呼叫:
Gender (M/F): asdf
Please enter a valid choice
Gender (M/F): 234
Please enter a valid choice
Gender (M/F): 1
Please enter a valid choice
Gender (M/F): 534
Please enter a valid choice
Gender (M/F): zxcv
Please enter a valid choice
Gender (M/F): Ff
Please enter a valid choice
Gender (M/F): Mm
Please enter a valid choice
Gender (M/F): m
Please enter a valid choice
Gender (M/F): f
Please enter a valid choice
Gender (M/F): M
'M'