函數也可以返回布爾值(True或False),這種情況便於隱藏函數內部的復雜測試。例如:
#!/bin/python
def is_divisible(x, y):
if x % y == 0:
return True
else:
return False
print is_divisible(6, 3)
$ python a.py
True
一般情況下都給這種布爾函數起個獨特的名字,比如要有判斷意味的提示,is_divisible這個函數就去判斷x能否被y整除,而對應地返回真或假。
雙等號運算符的返回結果是一個布爾值,所以我們可以用下面的方法來簡化剛剛的函數:
$ cat a.py
#!/bin/python
def divisible(x, y):
return x % y == 0
print divisible(6, 3)
$ python a.py
True
布爾函數經常用於條件語句:
if is_divisible(x, y) == True:
print('x is divisible by y'
上面的例子,可以這樣寫來做調試:
$ cat a.py
#!/bin/python
def divisible(x, y):
return x % y == 0
x = 6
y = 3
if divisible(x, y) == True:
print('x is divisible by y')
$ python a.py
x is divisible by y
結束。