Fruitful Functions in Python: Composition and Boolean Functions
Fruitful functions in python help the coder to develop efficient and bug-free code. It will also help your python scripts be more presentable and easier to understand.
Welcome! to the second part of Fruitful Functions of Python. This blog is going to cover 2 more topics, Composition & Boolean Functions. Also, if you haven't read the first part which was about Return Values & Incremental Developments do read it as it will make this blog easier to understand.
Composition
Composition is an ability where the user can call one function from another. Let’s form an example where we create a function that takes two points, the centre of the circle and a point on the perimeter, and then shows the area of the circle as the result.
The centre of the circle can be assumed as xc
and yc
, and let the perimeter point be xp
and yp
. Now we first find the radius of the circle, which is the distance between two points of the circle. Below is the function:
radius= distance(xc, yc, xp, yp)
The next step is to find are with the radius:
result= area(radius)
Now is the final step where we will encapsulate these functions,
def circle_area(xc, yc, xp, yp):
radius = distance(xc, yc, xp, yp)
result = area(radius)
return result
Here if you notice the first two lines of code, it shows how we have called a function in a function which is also known as Encapsulation. There is one more option of encapsulation :
def circle_are(xc, yc, xp, yp):
return area(distance(xc,yc, xp, yp))
As you can see it makes our code smaller and efficient as we are assigning fewer variables than before.
Boolean Functions
Returning boolean values in a function makes it convenient for hiding complicated tests. Let's take a look at a basic example of how a boolean function looks:
def divide(a,b):
if a%b==0:
return True
else:
return False
Here this function can show only two results either True or False, boolean functions are known for these direct results.
The == operator in the above code is used in a boolean function to make it more concise by returning the result directly. They also use conditional statements to show the result in the form of boolean.
Another way of forming the boolean function is as follows:
if is_divisible(x, y) == True:
print "x is divisible by y"
So we can keep these two functions types in mind while writing a script as it can make the code more efficient and easier to understand. Stay tuned for more episodes on Fruitful Functions of Python.