目錄
?
1、# and 結果為真,返回最后一個表達式的結果,若結果為假返回第一個為假的表達式的結果
2、# or 結果為真,返回第一個為真的表達式的結果,若結果為假,返回最后一個表達式的結果
3、應用[劍指 Offer 64. 求1+2+…+n]
1、# and 結果為真,返回最后一個表達式的結果,若結果為假返回第一個為假的表達式的結果
def test_and(a,b):return a and b
# 0 表示FALSE,非0表示True
print(test_and(0,1)) # and -> False -> 0(a)
print(test_and(1,0)) # and -> False -> 0(b)
print(test_and(False,0)) # and -> False -> False(a)
print(test_and(0,False)) # and -> False -> 0(a)
print(test_and(1,2)) # and -> True -> 2(b)
print(test_and(2,1)) # and -> True -> 1(b)
2、# or 結果為真,返回第一個為真的表達式的結果,若結果為假,返回最后一個表達式的結果
def test_or(a,b):return a or b
# 0 表示FALSE,非0表示True
print(test_or(0,1)) # or -> True -> 1(a)
print(test_or(1,0)) # or -> True -> 1(b)
print(test_or(2,1)) # or -> True -> 1(b)
print(test_or(1,2)) # or -> True -> 2(b)
print(test_or(False,0)) # or -> False -> 0(b)
print(test_or(0,False)) # or -> False -> False(b)
3、應用[劍指 Offer 64. 求1+2+…+n]
求 1+2+...+n
,要求不能使用乘除法、for、while、if、else、switch、case等關鍵字及條件判斷語句(A?B:C)。
for 循環用遞歸代替
if 用return 的and屬性來表示
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/5/20 12:54
# @Author : @linlianqin
# @Site :
# @File : 劍指 Offer 64. 求1+2+…+n.py
# @Software: PyCharm
# @description:
'''
求 1+2+...+n ,要求不能使用乘除法、for、while、if、else、switch、case等關鍵字及條件判斷語句(A?B:C)。
限制:1 <= n <= 10000'''class Solution:'''遞歸'''def sumNums(self, n: int) -> int:return n and n + self.sumNums(n - 1)print(Solution().sumNums(3))
?