Python Libraries

Python Libraries

Libraries in python are the collection of functions and methods which help the developer to write and perform the task without rewriting redundant code. The same library can be used across many projects. Python provides a lot of built-in functions which is very useful in every coding activity. Here we will discuss a few of them.

range(): range used to create a list containing arithmetic progression.

 for i in range(3):
       print(i)

Output:

0
1
2

To return a list between two integers.

 for i in range(1,3):
       print(i)

Output:

1
2 

To return a list between two integers with equal interval.

 for i in range(1,5,2):
       print(i)

Output:

1
3 

len():len() function used to calculate the length of a sequence.

 number_list = [10,30,2,4,1]
len(number_list)

Output:

5

filter(): filter() function used to filter or separate value from sequence.

 all_mumber = [1,2,3,4,5,6,7,8,9]
prime = filter(lambda x: x % 2, all_mumber)
print(list(prime))

Output:

[1, 3, 5, 7, 9] 

Python allows us to reuse the code by reusing the module. The following example describes how to use the module in other python class. Let’s say ’employee.py’ file has a class called ‘Bonus’.

 class Bonus:
    def __init__(self):
        self.profit_per = 0.1

    def calculate_bonus(self,salary):
        total_amount = salary + salary * self.profit_per
        return total_amount

Now to use the function ‘calculate_bonus’ in other python files, the user needs to import the class. Let’s say app.py is the class that needs to use the function ‘calculate_bonus’. Here the ‘Bonus’ class imported using the ‘import’ statement.

 from employee import Bonus
bonus = Bonus()
print(bonus.calculate_bonus(1000))

In this blog, you learned about Python Libraries.Please post your comments and errors, if you find any difficulties in python.

Leave a Reply