Python编码bat预热返回意外的True

Python编码bat预热返回意外的True,python,boolean-logic,Python,Boolean Logic,正在尝试以下问题: 如果是工作日,则参数工作日为真;如果我们在度假,则参数休假为真。如果不是工作日或者我们在度假,我们就睡懒觉。如果我们睡懒觉,返回True sleep_in(False, False) → True sleep_in(True, False) → False sleep_in(False, True) → True 我尝试运行以下代码来测试解决方案 weekday = 0 vacation = 5 def sleep_in(weekday, vacation): if

正在尝试以下问题:

如果是
工作日
,则参数
工作日
;如果我们在度假,则参数
休假
。如果不是工作日或者我们在度假,我们就睡懒觉。如果我们睡懒觉,返回
True

sleep_in(False, False) → True
sleep_in(True, False) → False
sleep_in(False, True) → True
我尝试运行以下代码来测试解决方案

weekday = 0
vacation = 5

def sleep_in(weekday, vacation):
  if not weekday or vacation:
    return True
  else:
    return False

x = sleep_in(0, 6)
print x
我期待着一个错误的结果。然而我正在变为现实!知道发生了什么吗?

所有Python对象都有一个布尔值;数值
0
视为假,每隔一个数字为真

因此,
0
为假,
6
为真,
not 0或6
的计算结果为
true
,因为
not 0
为真:

>>> not 0
True
请参见Python文档中的:

任何对象都可以测试真值,用于if或while条件,或作为下面布尔运算的操作数。以下值被认为是错误的:

[……]

  • 任何数字类型的零,例如0、0L、0.0、0j
因此,您不需要使用
if
语句;只需直接返回表达式结果:

基本上,您是在寻找第一个值和第二个值的
而不是
。我想先定义它们会更好。输出是正确的。或一艘班轮

x =lambda weekday,vacation: not weekday or vacation
print (x(0,0))

由于以下几个原因,您的代码无法工作。首先,您不需要将weekday和vacation定义为任何数字,因为它们已经将这些值传递给您,为true或false。此外,您只需检查工作日是否为!=如果为True,则假期为false,如果为True,则返回True。否则,您将返回false。就这么简单

    def sleep_in(weekday, vacation):

      if not weekday or vacation:
         return True
      return False

此外,它返回这个错误,因为在python中0被认为是false,6被认为是true,所以它认为您试图将它们设置为布尔值,从而覆盖给定的值。希望这有帮助

如果是工作日,参数weekday为True;如果我们在度假,参数vacation为True。如果不是工作日或者我们在度假,我们就睡在里。如果我们睡懒觉,返回True

粗体的语句本身就是暗示

if not weekday or vacation:
    return True
return False
    def sleep_in(weekday, vacation):

      if not weekday or vacation:
         return True
      return False
if not weekday or vacation:
    return True
return False