Boolean Functions
Boolean Functions
Boolean functions
A Boolean function
This is a function which returns a bool result (True or
False). The function can certainly work with any type of
data as parameter or local variable, but the result is
bool.
Its a good idea to name a bool function with a name
that asks a question is_Error or within_range. Then
the return value makes sense if is_Error returns True,
you would think there WAS an error.
There is almost always an if statement in a Boolean
function because the function can have two different
results, True or False.
def yes_no(ans):
result = False
if ans == y or ans == Y :
result = True
return result
If result did not get an initial value, the return statement will cause a
crash, because of name not defined, which tells you that you have an
error right there. Of course you can fix it by giving result an initial value
of True (or False, depending on your specifications)
A Shortcut
The previous function can actually be written in much
shorter form
def yes_no (ans):
return ans == y or ans ==Y
The expression in the return statement must be
evaluated before it can return. The relational operators
and logical operator will combine to give a bool value if
the parameter had a y in it, you get a True anything
else gives a False.