[英]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.