[英]Boolean logic in Python statement
# Given three ints, a b c, print True if b is greater than a,
# and c is greater than b. However, with the exception that if
# "bOk" is True, b does not need to be greater than a.
a = int(input())
b = int(input())
c = int(input())
bOk = bool(input())
print(((bOk and c > b) or (b > a and c > b)))
我的程序适用于“ 3 2 4 False”以外的所有组合
我不明白为什么此组合会显示True。 由于bOk = False,因此第一个封闭集应返回False,并且由于b> a为False,因此第二个封闭集也应返回False。
解释将不胜感激。
布尔值是两个常量对象False和True。
对于布尔字符串
bool('')
=> False
bool('false')
=> True
布尔检查列表中是否有对象。 如果为空,则返回False;如果非空,则返回True。
在您的情况下,bOk = bool(input())具有一个值,因此bOk返回True,无论它具有什么对象。 这样就得到了输出。
评论和其他答案已经涵盖了OP错误的解释。 我宁愿显示通常如何在更受限的上下文中完成工作(生产?)。
尽管重点是:清理输入,但代码尚未经过全面测试,也不是最精美的代码。 总是。 并以完全不同的方式提示用户输入选择问题(是/否,是/否)。
在下面的示例中,布尔提示被清除为“此值是唯一被视为True的值;所有其他值为False”。
#!/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)))
希望能为您带来如此巨大的成功,对此感到抱歉。 处理用户输入始终是一项棘手的任务。
您的代码在Python 2.x上有效,因为在Python 2.x中,input()等于eval(raw_input(prompt))。
>>> a=int(input())
3
>>> b=int(input())
2
>>> c=int(input())
4
>>> bOk=bool(input())
False
>>> print(bOk and c > b)
False
>>> bOk
False
>>> print(((bOk and c > b) or (b > a and c > b)))
False
但是在Python 3.x中,input()等于raw_input(),因此bOk等于bool(“ False”),等于True。
>>> bOk=bool(input())
False
>>> print(bOk and c > b)
True
>>> bOk
True
您可以将input()更改为eval(input())。
“ Python 2到3转换工具将把对input()的调用替换为eval(input()),并将raw_input()替换为input()。”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.