def sum10(a, b):
if sum([a, b]) % 10 == 0: return True; return False
print sum10(7, 3)
print sum10(-13, -17)
print sum10(3, 8)
结果是:
True
True
None
不是我期望的:
True
True
False
有什么想法吗?
def sum10(a, b):
if sum([a, b]) % 10 == 0: return True; return False
print sum10(7, 3)
print sum10(-13, -17)
print sum10(3, 8)
结果是:
True
True
None
不是我期望的:
True
True
False
有什么想法吗?
你的代码
def sum10(a, b):
if sum([a, b]) % 10 == 0: return True; return False
等同于
def sum10(a, b):
if sum([a, b]) % 10 == 0:
return True; return False
所以return False
不会被评估。
其中一些(可能无穷无尽的)替代方案:
if sum([a, b]) % 10 == 0:
return True
return False
或者 return sum([a, b]) % 10 == 0
return True if sum([a, b]) % 10 == 0 else False
或者 return False if (a+b) % 10 else True
或者(在我看来最易读的)
return not (a + b) % 10
这就是您想要的。
def sum10(a, b):
return sum([a, b]) % 10 == 0
Python中的三元If
表达式工作方式如下:
<True Statment> if <Conditional Expression> else <False Statement>
例如
True if sum([a,b]) % 10 == 0 else False
我也可以建议使用加号运算符吗?
True if (a+b) % 10 == 0 else False
如果您想要if-else的一行代码,应该按照以下方式编写:
return True if sum([a, b]) % 10 == 0 else False
def sum10(a, b):
return sum([a, b])%10 == 0
我认为return False
从未被执行,因为它在if语句内部而不是外部。
因此,当您在if条件中得到true时,您将执行return True
,但永远不会执行第二个语句。
不要立即返回True或False,你可以尝试将结果存储在布尔变量中,然后在最后返回该变量。例如:
def sum(a,b):
bool result
if sum([a, b]) % 10 == 0:
bool=True
else:
bool=False
return bool