简体   繁体   English

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)))

My program works for all combinations besides "3 2 4 False" 我的程序适用于“ 3 2 4 False”以外的所有组合

I don't understand why it prints True for this combination. 我不明白为什么此组合会显示True。 The first closed set should return False since bOk = False, and the second closed set should return False as well since b > a is False. 由于bOk = False,因此第一个封闭集应返回False,并且由于b> a为False,因此第二个封闭集也应返回False。

Explanation would be much appreciated. 解释将不胜感激。

Boolean values are the two constant objects False and True. 布尔值是两个常量对象False和True。

For Boolean Strings 对于布尔字符串

   bool('')
=> False

   bool('false')
=> True

The bool checks whether the list has an object or not. 布尔检查列表中是否有对象。 If it is empty it will return False, if anything but empty, it will return True. 如果为空,则返回False;如果非空,则返回True。

In your case, bOk = bool(input()), has a value, therefore bOk returns True, regardless of what object it has. 在您的情况下,bOk = bool(input())具有一个值,因此bOk返回True,无论它具有什么对象。 And thus the output you have. 这样就得到了输出。

Comments and other answers already covered explanation of OPs mistake. 评论和其他答案已经涵盖了OP错误的解释。 I'll rather show how things are usually done in a more restricted context (production?). 我宁愿显示通常如何在更受限的上下文中完成工作(生产?)。

Code is not fully tested and is not the most elegant though the point is: sanitize input. 尽管重点是:清理输入,但代码尚未经过全面测试,也不是最精美的代码。 Always. 总是。 And prompt user for choice questions (yes/no, true/false) in a completely different way. 并以完全不同的方式提示用户输入选择问题(是/否,是/否)。

In the below example bool prompt sanitized as "this value is the only value that is treated as True; all other values are False". 在下面的示例中,布尔提示被清除为“此值是唯一被视为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)))

Hope that helps and sorry for such a huge listing. 希望能为您带来如此巨大的成功,对此感到抱歉。 Processing user input is always a tricky task. 处理用户输入始终是一项棘手的任务。

Your codes works on Python 2.x, because in Python 2.x, input() equals eval(raw_input(prompt)). 您的代码在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

But in Python 3.x, input() equals raw_input(), so bOk equals bool("False"), equals True. 但是在Python 3.x中,input()等于raw_input(),因此bOk等于bool(“ False”),等于True。

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

You can change input() to eval(input()). 您可以将input()更改为eval(input())。

"The Python 2 to 3 conversion tool will replace calls to input() with eval(input()) and raw_input() with input()." “ Python 2到3转换工具将把对input()的调用替换为eval(input()),并将raw_input()替换为input()。”

Refer to https://www.python.org/dev/peps/pep-3111/ 请参阅https://www.python.org/dev/peps/pep-3111/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM