Advertisement
here2share

Python - Built-In Modules

Oct 5th, 2019
822
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 14.72 KB | None | 0 0
  1. Python - Built-In Modules
  2.  
  3. '''
  4. In programming terminology, function is a separate, complete and reusable software component. Long and complex logic in a program is broken into smaller, independent and reusable blocks of instructions usually called a module, a subroutine or function. It is designed to perform a specific task that is a part of entire process. This approach towards software development is called modular programming.
  5.  
  6. Such a program has a main routine through which smaller independent modules (functions) are called upon. Each When called, a function performs a specified task and returns the control back to the calling routine, optionally along with result of its process.
  7.  
  8. Python interpreter has a number of built-in functions. They are always available for use in every interpreter session. Many of them have been discussed in previously. For example print() and input() for I/O, number conversion functions (int(), float(), complex()), data type conversions (list(), tuple(), set()) etc. Here is complete list of Python's built-in functions:
  9. Built-in Functions
  10. abs()  delattr()  hash()  memoryview()  set()  all()  dict()  help()  min()  setattr()  any()  dir()  hex()  next()  slice()
  11. ascii()  divmod()  id()  object()  sorted()  bin()  enumerate()  input()  oct()  staticmethod()  bool()  eval()  int()  open()  str()  breakpoint()  exec()  isinstance()  ord()  sum()  bytearray()  filter()  issubclass()  pow()  super()  bytes()  float()  iter()  print()  tuple()  callable()  format()  len()  property()  type()  chr()  frozenset()  list()  range()  vars()  classmethod()  getattr()  locals()  repr()  zip()  compile()  globals()  map()  reversed()  __import__()  complex()  hasattr()  max()
  12.    
  13.  
  14. Other functions will come up in later chapters of this tutorial.
  15.  
  16. In addition to built-in functions, a large number of pre-defined functions are also available as a part of libraries bundled with Python distributions. However they are not available for use automatically. These functions are defined in modules. A module is a file containing definition of functions, classes, variables, constants or any other Python object. Standard distribution of Python contains a large number of modules, generally known as built-in modules. Each built-in module contains resources for certain specific functionalities such as OS management, disk IO, networking, database connectivity etc.
  17. '''
  18.  
  19. Most of the times, built-in modules are written in C and integrated with Python interpreter.
  20.  
  21. A built-in module may be a Python script (with .py extension) containing useful utilities.
  22.  
  23. To display list of all available modules, use following command in Python console:
  24.  
  25. >>> help('modules')
  26.  
  27. Resources from other modules are loaded by import statement. The general format of using a function in any module is like this:
  28.  
  29. import module
  30.  
  31. module.function([arguments if any])
  32.  
  33. The sqrt() function in math module returns square root of a number.
  34.  
  35. >>> import math
  36. >>> math.sqrt(100)
  37. 10.0
  38.  
  39. In this chapter we shall discuss some of the frequently used functions from certain built-in modules.
  40.  
  41.     os module
  42.     random module
  43.     math module
  44.     time module
  45.     sys module
  46.     collections module
  47.     statistics module
  48.  
  49. os module
  50.  
  51. This module has functions to perform many tasks of operating system.
  52. mkdir():
  53.  
  54. We can create a new directory using mkdir() function from os module.
  55.  
  56. >>> import os
  57. >>> os.mkdir("d:\\tempdir")
  58.  
  59. A new directory corresponding to path in string argument in the function will be created. If we open D drive in Windows explorer we should notice tempdir folder created.
  60. chdir():
  61.  
  62. To change current working directory to use chdir() function.
  63.  
  64. >>> import os
  65. >>> os.chdir("d:\\temp")
  66.  
  67. getcwd():
  68.  
  69. This function in returns name off current working directory.
  70.  
  71. >>> os.getcwd()
  72. 'd:\\temp'
  73.  
  74. Directory paths can also be relative. If current directory is set to D drive and then to temp without mentioning preceding path, then also current working directory will be changed to d:\temp
  75.  
  76. >>> os.chdir("d:\\")
  77. >>> os.getcwd()
  78. 'd:\\'
  79. >>> os.chdir("temp")
  80. >>> os.getcwd()
  81. 'd:\\temp'
  82.  
  83. In order to set current directory to parent directory use ".." as the argument to chdir() function.
  84.  
  85. >>> os.chdir("d:\\temp")
  86. >>> os.getcwd()
  87. 'd:\\temp'
  88. >>> os.chdir("..")
  89. >>> os.getcwd()
  90. 'd:\\'
  91.  
  92. rmdir():
  93.  
  94. The rmdir() function in os module removes a specified directory either with absolute or relative path. However it should not be the current working directory and it should be empty.
  95.  
  96. >>> os.chdir("tempdir")
  97. >>> os.getcwd()
  98. 'd:\\tempdir'
  99. >>> os.rmdir("d:\\temp")
  100. PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'd:\\temp'
  101. >>> os.chdir("..")
  102. >>> os.rmdir("temp")
  103.  
  104. listdir():
  105.  
  106. The os module has listdir() function which returns list of all files in specified directory.
  107.  
  108. >>> os.listdir("c:\\Users")
  109. ['acer', 'All Users', 'Default', 'Default User', 'desktop.ini', 'Public']
  110.  
  111. random module
  112.  
  113. Python’s standard library contains random module which defines various functions for handling randomization. Python uses a pseudo-random generator based upon Mersenne Twister algorithm that produces 53-bit precision floats. Functions in this module depend on pseudo-random number generator function random() which generates a random float number between 0.0 and 1.0.
  114.  
  115. random.random(): Returns a random float number between 0.0 to 1.0. The function doesn’t need any arguments
  116.  
  117. >>> import random
  118. >>> random.random()
  119. 0.755173688207591
  120.  
  121. Other functions in random module are described here:
  122.  
  123. random.randint(): Returns a random integer between the specified integers
  124.  
  125. >>> import random
  126. >>> random.randint(1,100)
  127. 58
  128. >>> random.randint(1,100)
  129. 91
  130.  
  131. random.randrange(): Returns a random element from the range created by start, stop and step arguments. The start , stop and step parameters behave similar to range() function.
  132.  
  133. >>> random.randrange(1,10)
  134. 2
  135. >>> random.randrange(1,10,2)
  136. 3
  137. >>> random.randrange(0,101,10)
  138. 40
  139.  
  140. random.choice(): Returns a randomly selected element from a sequence object such as string, list or tuple. An empty sequence as argument raises IndexError
  141.  
  142. >>> import random
  143. >>> random.choice('computer')
  144. 'o'
  145. >>> random.choice([12,23,45,67,65,43])
  146. 65
  147. >>> random.choice((12,23,45,67,65,43))
  148. 23
  149.  
  150. random.shuffle(): This functions randomly reorders elements in a list.
  151.  
  152. >>> numbers=[12,23,45,67,65,43]
  153. >>> random.shuffle(numbers)
  154. >>> numbers
  155. [23, 12, 43, 65, 67, 45]
  156. >>> random.shuffle(numbers)
  157. >>> numbers
  158. [23, 43, 65, 45, 12, 67]
  159.  
  160. math module
  161.  
  162. This module presents commonly required mathematical functions.
  163.  
  164.     trigonometric functions
  165.     representation functions
  166.     logarithmic functions
  167.     angle conversion functions
  168.  
  169. In addition, two mathematical constants are also defined in this module.
  170.  
  171. Pie π which is defined as ratio of circumference to diameter of a circle and its value is 3.141592653589793, is available in math module.
  172.  
  173. >>> import math
  174. >>> math.pi
  175. 3.141592653589793
  176.  
  177. Another mathematical constant in this module is e. It is called Euler’s number and is a base of natural logarithm. Its value is 2.718281828459045
  178.  
  179. >>> math.e
  180. 2.718281828459045
  181.  
  182. This module contains functions for calculating various trigonometric ratios for a given angle. The functions (sin, cos, tan etc.) need angle in radians as argument. We on the other hand are used to express angle in degrees. The math module presents two angle conversion functions (degrees() and radians()) to convert angle in degrees to radians and vice versa.
  183. Trigonometric functions:
  184.  
  185. radians(): converts angle in degrees to radians.(Note: π radians is equivalent to 180 degrees)
  186.  
  187. >>> math.radians(30)
  188. 0.5235987755982988
  189.  
  190. degrees(): converts angle in radians to degree.
  191.  
  192. >>> math.degrees(math.pi/6)
  193. 29.999999999999996
  194.  
  195. Following statements show sin, cos and tan ratios for angle of 30 degrees (0.5235987755982988 radians)
  196.  
  197. >> math.sin(0.5235987755982988)
  198. 0.49999999999999994
  199. >>> math.cos(0.5235987755982988)
  200. 0.8660254037844387
  201. >>> math.tan(0.5235987755982988)
  202. 0.5773502691896257
  203.  
  204. sin(30) 0.5  0.49999999999999994
  205. cos(30) 3/2      0.8660254037844387)
  206. tan(30) 1/2  0. 5773502691896257
  207.  
  208. math.log(): returns natural logarithm of given number. Natural logarithm is calculated to the base e.
  209.  
  210. math.log10(): returns base-10 logarithm or standard logarithm of given number.
  211.  
  212. >>> math.log10(10)
  213. 1.0
  214.  
  215. math.exp(): returns a float number after raising e (math.e) to given number. exp(x) is equivalent to e**x
  216.  
  217. >>> math.log10(10)
  218. 1.0
  219. >>> math.e**10
  220. 22026.465794806703
  221.  
  222. math.pow(): This function receives two float arguments, raises first to second and returns the result. pow(4,4) is equivalent to 4**4
  223.  
  224. >>> math.pow(4,4)
  225. 256.0
  226. >>> 4**4
  227. 256
  228.  
  229. math.sqrt(): This function computes square root of given number
  230.  
  231. >>> math.sqrt(100)
  232. 10.0
  233. >>> math.sqrt(3)
  234. 1.7320508075688772
  235.  
  236. Representation functions:
  237.  
  238. The ceil() function approximates given number to smallest integer greater than or equal to given floating point number. The floor() function returns a largest integer less than or equal to given number
  239.  
  240. >>> math.ceil(4.5867)
  241. 5
  242. >>> math.floor(4.5687)
  243. 4
  244.  
  245. sys module
  246.  
  247. This module provides functions and variables used to manipulate different parts of the Python runtime environment.
  248. sys.argv
  249.  
  250. This return list of command line arguments passed to a Python script.  Item at 0th index of this list is always the name of the script. Rest of the arguments are stored at subsequent indices.
  251.  
  252. Here is a Python script (test.py) consuming two arguments from command line.
  253.  
  254. import sys
  255. print ("My name is {}. I am {} years old".format(sys.argv[1], sys.argv[2]))
  256.  
  257. This script is executed from command line as follows:
  258.  
  259. C:\python37>python tmp.py Anil 23
  260. My name is Anil. I am 23 years old
  261.  
  262. sys.exit
  263.  
  264. This causes program to end and return to either Python console or command prompt. It is used to safely exit from program in case of exception.
  265. sys.maxsize
  266.  
  267. It returns the largest integer a variable can take.
  268.  
  269. >>> import sys
  270. >>> sys.maxsize
  271. 9223372036854775807
  272.  
  273. sys.path
  274.  
  275. This is an environment variable that returns search path for all Python modules.
  276.  
  277. >>> sys.path
  278. ['', 'C:\\python37\\Lib\\idlelib', 'C:\\python37\\python36.zip', 'C:\\python37\\DLLs', 'C:\\python37\\lib', 'C:\\python37', 'C:\\Users\\acer\\AppData\\Roaming\\Python\\Python37\\site-packages', 'C:\\python37\\lib\\site-packages']
  279.  
  280. sys.stdin, sys.stdout, sys.stderr
  281.  
  282. These are file objects used by the interpreter for standard input, output and errors. stdin is used for all interactive input (Python shell). stdout is used for the output of print() and of input(). The interpreter’s prompts and error messages go to stderr.
  283. sys.version
  284.  
  285. This attribute displays a string containing version number of current Python interpreter.
  286. collections module
  287.  
  288. This module provides alternatives to built-in container data types such as list, tuple and dict.
  289. namedtuple() function
  290.  
  291. This function is a factory function that returns object of  a tuple subclass with named fields. Any valid Python identifier may be used for a field name except for names starting with an underscore.
  292.  
  293. collections.namedtuple(typename, field-list)
  294.  
  295. The typename parameter is the subclass of tuple. Its object has attributes mentioned in field list. These field attributes can be accessed by lookup as well as by its index.
  296.  
  297. Following statement declares a employee namedtuple having name, age and salary as fields
  298.  
  299. >>> import collections
  300. >>> employee=collections.namedtuple('employee', [name, age, salary])
  301. To create a new object of this namedtuple
  302. >>> e1=employee("Ravi", 251, 20000)
  303.  
  304. Values of the field can be accessible by attribute lookup
  305.  
  306. >>> e1.name
  307. 'Ravi'
  308.  
  309. Or by index
  310.  
  311. >>> e1[0]
  312. 'Ravi'
  313.  
  314. OrderedDict() function
  315.  
  316. Ordered dictionary is similar to a normal dictionary. However, normal dictionary the order of insertion of keys in it whereas ordered dictionary object remembers the same. The key-value pairs in normal dictionary object appear in arbitrary order.
  317.  
  318. >>> d1={}
  319. >>> d1['A']=20
  320. >>> d1['B']=30
  321. >>> d1['C']=40
  322. >>> d1['D']=50
  323.  
  324. We then traverse the dictionary by a for loop,
  325.  
  326. >>> for k,v in d1.items():
  327. print (k,v)
  328.  
  329. A 20
  330. B 30
  331. D 50
  332. C 40
  333.  
  334. But in case of OrderedDict object:
  335.  
  336. >>> import collections
  337. >>> d2=collections.OrderedDict()
  338. >>> d2['A']=20
  339. >>> d2['B']=30
  340. >>> d2['C']=40
  341. >>> d2['D']=50
  342.  
  343. Key-value pairs will appear in the order of their insertion.
  344.  
  345. >>> for k,v in d2.items():
  346. print (k,v)
  347. A 20
  348. B 30
  349. C 40
  350. D 50
  351.  
  352. deque() function
  353.  
  354. A deque object supports append and pop operation from both ends of a list. It is more memory efficient than a normal list object because in a normal list, removing one of iem causes all items to its right to be shifted towards left. Hence it is very slow.
  355.  
  356. >>> q=collections.deque([10,20,30,40])
  357. >>> q.appendleft(110)
  358. >>> q
  359. deque([110, 10, 20, 30, 40])
  360. >>> q.append(41)
  361. >>> q
  362. deque([0, 10, 20, 30, 40, 41])
  363. >>> q.pop()
  364. 40
  365. >>> q
  366. deque([0, 10, 20, 30, 40])
  367. >>> q.popleft()
  368. 110
  369. >>> q
  370. deque([10, 20, 30, 40])
  371.  
  372. statistics module
  373.  
  374. This module provides following statistical functions :
  375.  
  376. mean() : calculate arithmetic mean of numbers in a list
  377.  
  378. >>> import statistics
  379. >>> statistics.mean([2,5,6,9])
  380. 5.5
  381.  
  382. median() : returns middle value of numeric data in a list. For odd items in list, it returns value at (n+1)/2 position. For even values, average of values at n/2 and (n/2)+1 positions is returned.
  383.  
  384. >>> import statistics
  385. >>> statistics.median([1,2,3,8,9])
  386. 3
  387. >>> statistics.median([1,2,3,7,8,9])
  388. 5.0
  389.  
  390. mode(): returns most repeated data point in the list.
  391.  
  392. >>> import statistics
  393. >>> statistics.mode([2,5,3,2,8,3,9,4,2,5,6])
  394. 2
  395.  
  396. stdev() : calculates standard deviation on given sample in the form of list.
  397.  
  398. >>> import statistics
  399. >>> statistics.stdev([1,1.5,2,2.5,3,3.5,4,4.5,5])
  400. 1.3693063937629153
  401.  
  402. time module
  403.  
  404. This module has many time related functions.
  405.  
  406. time():
  407.  
  408. This function returns current system time in ticks. The ticks is number of seconds elapsed after epoch time i.e. 12.00 am, January 1, 1970.
  409.  
  410. >>> time.time()
  411. 1544348359.1183174
  412.  
  413. localtime():
  414.  
  415. This function translates time in ticks in a time tuple notation.
  416.  
  417. >>> tk=time.time()
  418. >>> time.localtime(tk)
  419. time.struct_time(tm_year=2018, tm_mon=12, tm_mday=9, tm_hour=15, tm_min=11, tm_sec=25, tm_wday=6, tm_yday=343, tm_isdst=0)
  420.  
  421. asctime():
  422.  
  423. This functions returns a readable format of local time
  424.  
  425. >>> tk=time.time()
  426. >>> tp=time.localtime(tk)
  427. >>> time.asctime(tp)
  428. 'Sun Dec  9 15:11:25 2018'
  429.  
  430. ctime():
  431.  
  432. This function returns string representation of system's current time
  433.  
  434. >>> time.ctime()
  435. 'Sun Dec  9 15:17:40 2018'
  436.  
  437. sleep():
  438.  
  439. This function halts current program execution for a specified duration in seconds.
  440.  
  441. >>> time.ctime()
  442. 'Sun Dec  9 15:19:14 2018'
  443. >>> time.sleep(20)
  444. >>> time.ctime()
  445. 'Sun Dec  9 15:19:34 2018'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement