表达方式("w" or "d")
将始终评估为"w"
。一般来说,在这里你想要一个in
:
while input1 not in ("w", "d"):
...
就处理输入为数字的情况而言,这是辅助函数的工作:
def string_is_number(s):
try:
float(s)
return True
except ValueError:
return False
现在您可以将其与上面的内容一起使用,将整个内容组合在一起:
while (not string_is_number(input1)) and (input1 not in ("w", "d")): ...
实际上可以进一步简化:
while not (string_is_number(input1) or (input1 in ("w", "d"))): ...
现在有一种完全不同的方法,您实际上可以使用递归函数来完成此类事情。将其与 python 的异常处理相结合,我们也许可以用几行代码组合出一个非常优雅的解决方案:
def prog_loop():
# prompt for user's input here:
input1 = raw_input("Enter a number, or 'w' or 'd':")
# See if we got a number
try:
number = float(input1)
except ValueError:
# Nope, wasn't a number. Check to see if it was in our
# whitelisted strings. If so, break early.
if input1 in ('w', 'd'):
return function_handle_w_d(input1)
else:
# Yes, we got a number. Use the number and exit early
return function_handle_number(number)
# haven't exited yet, so we didn't get a whitelisted string or a number
# I guess we need to try again...
return prog_loop()
只要您的用户不输入错误输入 1000 次,此操作就会起作用。