Python 语句中的布尔逻辑

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。第一个闭集应该 return False 因为 bOk = False,第二个闭集也应该 return False 因为 b > a 是 False。

解释将不胜感激。

布尔值是两个常量对象False和True。

对于布尔字符串

   bool('')
=> False

   bool('false')
=> True

布尔检查列表是否有对象。如果它是空的,它将 return False,如果不是空的,它将 return True。

在您的例子中,bOk = bool(input()) 有一个值,因此 bOk returns 为真,无论它有什么对象。因此你的输出。

您的代码适用于 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

但是在Python3.x中,input()等于raw_input(),所以bOk等于bool("False"),等于True。

>>> bOk=bool(input())
False
>>> print(bOk and c > b)
True
>>> bOk
True

您可以将 input() 更改为 eval(input())。

"The Python 2 to 3 conversion tool will replace calls to input() with eval(input()) and raw_input() with input()."

参考https://www.python.org/dev/peps/pep-3111/

评论和其他答案已经涵盖了对 OP 错误的解释。我宁愿展示事情通常是如何在更受限制的上下文(生产?)中完成的。

代码没有经过全面测试,也不是最优雅的代码,但要点是:清理输入。总是。并以完全不同的方式提示用户选择问题(yes/no、true/false)。

在下面的示例中,bool 提示已清理为 "this value is the only value that is treated as True; all other values are 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)))

希望对您有所帮助,对于如此庞大的清单,我们深表歉意。处理用户输入始终是一项棘手的任务。