Concept of Library and Packages in Python - 10
Definition
A library is a collection of pre-written modules that provide useful functions and tools to perform different tasks without writing the code from scratch. Python provides many built-in libraries, and programmers can also install additional libraries for specialized tasks.
Examples of Popular Python Libraries
TensorFlow
TensorFlow is an open-source Python library developed by Google for Artificial Intelligence (AI) and Machine Learning (ML). It is mainly used to create and train intelligent computer programs.
Matplotlib
Matplotlib is a Python library used to create graphs, charts, and data visualizations. It helps represent data in an easy-to-understand graphical form.
Pandas
Pandas is a Python library used for data analysis and data manipulation. It provides powerful tools to organize, clean, and process large sets of data efficiently.
2. Module
Definition
A module is a single Python file (.py) that contains functions, variables, and classes related to a specific purpose. Modules help organize programs into smaller and reusable parts.
Examples
- math
- random
- os
- calendar
3. Package
Definition
A package is a collection of related modules stored inside a folder. It helps organize multiple modules into a structured hierarchy. Packages make large Python programs easier to manage and maintain.
Example
The NumPy package contains many modules for mathematical and numerical operations.
Importing and Using Standard Libraries
Introduction
Python provides many standard libraries that are already included with Python. These libraries contain useful modules and functions that help programmers perform common tasks such as mathematical calculations, generating random numbers, working with dates, handling files, and more.
To use a module from the standard library, it must first be imported into the program.
1. Importing an Entire Library Module
Explanation
The import keyword is used to import the entire module. After importing, the module name must be written before using its functions.
Syntax
import module_name
Example
import math
print(math.sqrt(25))
print(math.factorial(5))
Output
5.0
120
Explanation
Here, the entire math module is imported. The functions sqrt() and factorial() are accessed using math. before their names.
2. Importing Specific Functions or Items from a Module
Explanation
Instead of importing the whole module, only the required functions or variables can be imported. This allows the functions to be used directly without writing the module name.
Syntax
from module_name import function_name
Example
from math import sqrt, factorial
print(sqrt(36))
print(factorial(4))
Output
6.0
24
Explanation
Only the sqrt() and factorial() functions are imported from the math module, so they can be used directly without writing math..
3. Importing Modules with Aliases
Explanation
A module can be imported with a shorter or custom name using the as keyword. This makes the code shorter and easier to write.
Syntax
import module_name as alias_name
Example
import math as m
print(m.sqrt(49))
print(m.pi)
Output
7.0
3.141592653589793
Explanation
The math module is imported with the alias m. All functions and variables are accessed using m instead of math.
4. Importing Everything from a Module
Explanation
The * symbol imports all public functions, variables, and classes from a module. After importing, they can be used directly without the module name.
Syntax
from module_name import *
Example
from math import *
print(sqrt(64))
print(factorial(6))
print(pi)
Output
8.0
720
3.141592653589793
Explanation
All functions and constants from the math module are imported. Therefore, sqrt(), factorial(), and pi can be used directly without writing math..
Note
Although from module_name import * is allowed, it is generally not recommended in large programs because it may cause name conflicts and make the code less readable.
Math ModuleIntroduction
The Math Module is a built-in Python module that provides various mathematical functions and constants. It is commonly used to perform complex mathematical calculations such as finding square roots, factorials, powers, greatest common divisors, and more.
Before using the functions of the math module, it must be imported using the import statement.
import math
Common Functions of the Math Module
| Function | Description |
|---|---|
| ceil(x) | Returns the smallest integer greater than or equal to the given number. |
| fabs(x) | Returns the absolute (positive) value of a number. |
| factorial(x) | Returns the factorial of a positive integer. |
| gcd(a, b) | Returns the Greatest Common Divisor (GCD) of two numbers. |
| fmod(x, y) | Returns the remainder when x is divided by y. |
| pow(x, y) | Returns x raised to the power of y. |
| sqrt(x) | Returns the square root of a number. |
Random Module
Introduction
The Random Module is a built-in Python module used to generate random numbers and make random selections. It is useful in games, simulations, password generation, and many other applications.
Before using the random module, it must be imported.
import random
Common Functions of the Random Module
| Function | Description |
|---|---|
| seed() | Initializes the random number generator with a specific value. |
| randrange() | Returns a random number from a specified range. |
| randint() | Returns a random integer between two specified numbers (inclusive). |
| choice() | Returns a randomly selected element from a sequence such as a list or tuple. |
| choices() | Returns a list of randomly selected elements from a sequence. |
| sample() | Returns a specified number of unique random elements from a sequence. |
| random() | Returns a random floating-point number between 0.0 and 1.0. |
| shuffle() | Randomly rearranges the elements of a list. |
Matplotlib Module
Introduction
Matplotlib is a popular Python library used for creating graphs, charts, and other data visualizations. It helps present data in a clear and graphical format, making it easier to understand patterns and trends.
The most commonly used module in Matplotlib is pyplot, which provides functions for creating different types of charts.
import matplotlib.pyplot as plt
Sample Math functions in Python usage
from math import *
print("Ceiling value of 1.3:", ceil(1.3))
print("Absolute value of -3.5:", fabs(-3.5))
print("Factorial of 5:", factorial(5))
print("HCF of 4 and 6 is:", gcd(4,6))
print("Remainder when 6 is divided by 4 is:", fmod(6,4))
print("4 to the power of 3.5 is:", pow(4,3.5))
print("Square root of 10 is:", sqrt(10))
Output:
Ceiling value of 1.3: 2
Absolute value of -3.5: 3.5
Factorial of 5: 120
HCF of 4 and 6 is: 2
Remainder when 6 is divided by 4 is: 2.0
4 to the power of 3.5 is: 128.0
Square root of 10 is: 3.1622776601683795
Sample Random functions in Python usage
import random
random.seed(9)
print(random.random())
print(random.randrange(4,9))
print(random.randint(4,9))
print(random.choice([1,2,3,4,4,5,5,6,7,7,8]))
print(random.choices([1,2,3,4,4,5,5,6,7,7,8]))
print(random.sample([1,2,3,4,4,5,5,6,7,7,8],3))
a_list=[1,2,3,4,4,5,5,6,7,7,8]
random.shuffle(a_list)
print(a_list)
Output:
0.46300735781502145
6
6
3
[3]
[8, 1, 5]
[3, 8, 7, 4, 1, 5, 4, 5, 2, 6, 7]
Note: How is randrange different from randint function in random module?
Randrange works like a range in for loop in (start, stop condition, step value) pattern while Randint works in a listed for in [x,y] where both x and y points are included.
Book Exercise Solutions from Qn 1 to 8
1# Calculate square root
from math import sqrt
n=int(input("Enter a number:"))
print("Square root of ",n," is:",sqrt(n))
2# Calculate factorial
from math import factorial
n=int(input("Enter a number:"))
print("Factorial of ",n," is:",factorial(n))
3# Calculate cosine 60
from math import pi,cos
print("Cosine of 60 degrees is:",cos(pi/3))
4# Calculate power
from math import pow
base=int(input("Enter base value:"))
power=int(input("Enter power value:"))
print("Result:", pow(base,power))
5# Generate randome integer from 1 to 50.
from random import randint
print(randint(1,50))
6# Shuffle list of 10 integers
from random import shuffle
random_list=[1,4,3,2,6,5,8,7,9,8]
shuffle(random_list)
print(random_list)
7# Guessing random number from 1-20.
from random import randint
correct=randint(1,20)
result=True
while result:
guess=int(input("Enter guess(1-20):"))
if guess==correct:
print("Correct guess!")
result=False
else:
print("Keep Guessing")
8# Generate and store in list, 5 random numbers(1-50)
from random import randint
new_list=[]
for i in range(5):
generated_number=randint(1,50)
new_list.append(generated_number)
print(new_list)