Python语句中的布尔逻辑

2024-05-14 23:17:28 发布

您现在位置:Python中文网/ 问答频道 /正文

# 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,因为bOk=False;第二个闭集也应该返回False,因为b>;a是False。在

如能解释,不胜感激。在


Tags: andfalsetrueinputifisgivenint
3条回答

评论和其他答案已经涵盖了对操作错误的解释。我更愿意展示在一个更受限制的环境中(生产环境?)通常是如何完成的。在

代码没有经过全面测试,也不是最优雅的代码,但关键是:清理输入。总是这样。并以完全不同的方式提示用户选择问题(是/否、对/错)。在

在下面的示例中,bool prompt被清理为“这个值是唯一被视为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)))

希望这对我们有帮助,也很抱歉这么大的上市。处理用户输入总是一个棘手的任务。在

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

对于布尔字符串

   bool('')
=> False

   bool('false')
=> True

bool检查列表是否有对象。如果它是空的,它将返回False;如果不是空的,它将返回True。在

在您的例子中,bOk=bool(input())有一个值,因此bOk返回True,而不管它有什么对象。所以你的输出。在

您的代码适用于Python2.x,因为在Python2.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。在

^{pr2}$

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

“Python2到3转换工具将用eval(input())替换对input()的调用,用input()替换对raw_input()的调用。”

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

相关问题 更多 >

    热门问题