A Module is a file containing functions, variables and classes.
eg: Create a module named printNumbers.py as,
def printForward(n):
for i in range(n):
print(i+1)
def printBackwards(n):
for i in range(n):
print(n-i)
This can be imported to other files as,
import printNumbers as pn # module import
pn.printForward(5)
or,
from printNumbers import printForward # function import
printForward(5)
In order to view all the functions inside a module, use dir.
dir(printNumbers)
A module can be executed as a script if the below code is added,
if __name__ == "__main__":
printForward(5)
Built-in Functions
Python provides some built-in functions which can be used directly without importing.
eg: any(), print(), list(), input(), id(), len(), type(), iter(), sum().
Built-in Modules
Built-in modules can be used directly without installing. Some common built-in modules are,
1. math
This module is for mathematical operations. It has functions like ceil(), cos(), factorial(), prod(), isfinite(), sqrt(), pow(), isnan() and constants like nan, pi.
import math
print(math.sqrt(16))
2. os
This module performs many tasks of operating system. It has the functions mkdir(), chdir(), rmdir(), listdir() and getcwd().
import os
os.mkdir("d:\\tempdir")
os.chdir("d:\\temp")
os.getcwd() #returns 'd:\\temp'
3. random
It has various methods to return a random number.
import random
random.random() # Returns a random float number between 0.0 to 1.0.
random.randint(1,100) # Returns a random integer between the specified integers
random.randrange(1,10,2) # Returns a random element from the range created by start, stop and step.
random.choice([12,23,45,67,65,43]) # Returns a randomly selected element from a sequence object such as string, list or tuple
numbers=[12,23,45,67,65,43]
random.shuffle(numbers) # This functions randomly reorders elements in a list.
4. statistics
This provides various statistical modules.
mean() to find arithmetic mean of numbers in a list.
median() to get the middle value.
mode() for most repeated.
stdev() for standard deviation.
import statistics
lst = [2,5,3,2,8,3,9,4,2,5,6]
print(statistics.mode(lst))
print(statistics.stdev(lst))
5. requests
This allows us to make HTTP requests.
import requests
url = 'https://www.w3schools.com/python/demopage.php'
x = requests.get(url)
myobj = {'somekey': 'somevalue'}
x = requests.post(url, json = myobj)
6. re
This module is for regex expressions. Most functions take in two parameters - pattern and text.
import re
text = "The dog is barking. The dog is sleeping."
result = re.search("dog", text) # result.start() gives starting index
result = re.sub("dog", "cat", text) # substitute
result = re.split("\s", text) # split at space
result = re.match("\S+@\S+\.\S+" , text) # email pattern, result.group(1) gives first match
In the pattern = "^[A-Za-z]{2}[0-9]+$", ^ stands for start, [ ] for characterset, { } for repeat, + for one or more and $ stands for end. Also, * is for 0 or more, ? for 0 or 1, (a|b) for either 'a' or 'b' and /d is for digit.
7. unittest
Testing can be done for a single statement as,
assert sum([ 2, 3, 5]) == 10, "Should be 10"
But for multiple statements, we need the unittest module.
import unittest
class TestingSum(unittest.TestCase):
def test_sum(self):
self.assertEqual(sum([2, 3, 5]), 10, "It should be 10")
def test_sum_tuple(self):
self.assertEqual(sum((1, 3, 5)), 10, "It should be 10")
if __name__ == '__main__':
unittest.main()
Other built-in modules are,
threading - adds multithreading capabilities to a class as,
class ClickTheMouse(threading.Thread):
sys - for managing Python runtime environment. eg:sys.path, sys.argv
collections - provides alternatives to built-in containers. eg: namedtuple(), OrderedDict(), deque()
time - time.ctime() gives the current time.
email - for managing email messages
gc - for garbage collector
html - for manipulating html requests.
json - to create json notations
pickle, marshal - for serialization
locale - to set locale
logging - to add logs
sched - for schedulers
No comments:
Post a Comment