<p>评论和其他答案已经涵盖了对操作错误的解释。我更愿意展示在一个更受限制的环境中(生产环境?)通常是如何完成的。在</p>
<p>代码没有经过全面测试,也不是最优雅的代码,但关键是:清理输入。总是这样。并以完全不同的方式提示用户选择问题(是/否、对/错)。在</p>
<p>在下面的示例中,bool prompt被清理为“这个值是唯一被视为True的值;所有其他值都是False”。在</p>
<pre><code>#!/usr/bin/env python
"""Just an example."""
def input_type(prompt, type_):
"""Prompt a user to input a certain type of data.
For a sake of simplicity type_ is limited to int and str.
:param prompt: prompt message to print
:param type_: type of a data required
:type prompt: str
:type type_: int or bool
:return: data of a required type retrieved from STDIN
:rtype: type_
"""
accepted_types = [int, str]
if isinstance(prompt, str):
if any(type_ == atype for atype in accepted_types):
while True:
user_input = input(prompt)
try:
return type_(user_input)
except ValueError:
continue
else:
errmsg = 'Requested type is unsupported by this function: %s'
errmsg = errmsg % type_.__name__
else:
errmsg = 'Prompt must be a string: got %s instead'
errmsg = errmsg % type(prompt).__name__
raise Exception(errmsg)
def input_bool(prompt, as_true):
"""Prompt user to answer positively or negatively.
:param prompt: prompt message to print
:param as_true: value to interpret as True
:type prompt: str
:type as_true: str
:return: user answer
:rtype: bool
"""
if isinstance(as_true, str):
return input_type(prompt, str) == as_true
else:
errmsg = "'as_true' argument must be a string: got %s instead"
errmsg = errmsg % type(as_true).__name__
raise Exception(errmsg)
if __name__ == '__main__':
a = input_type('Enter first integer: ', int)
b = input_type('Enter second integer: ', int)
c = input_type('Enter third integer: ', int)
bOk = input_bool('Enter boolean value (True/False): ', 'true')
# Result
print(((bOk and c > b) or (b > a and c > b)))
</code></pre>
<p>希望这对我们有帮助,也很抱歉这么大的上市。处理用户输入总是一个棘手的任务。在</p>