Functions can return boolean values, which is often convenient for hiding complicated tests inside functions. For example:
def isDivisible(x, y):
if x % y == 0:
return 1 # it's true
else:
return 0 # it's false
We can make the function more concise by taking advantage of the fact that the condition of the if statement is itself a boolean expression. We can return it directly, avoiding the if statement altogether:
def isDivisible(x, y): return x % y == 0
>>> isDivisible(6, 4) 0 >>> isDivisible(6, 3) 1
if isDivisible(x, y): print "x is divisible by y" else: print "x is not divisible by y"
if isDivisible(x, y) == 1:
As an exercise, write a function isBetween(x, y, z) that returns 1 ifor 0 otherwise.