CodingBison

Modules are namespaces which contain a set of related methods. We have already seen the examples of modules: string, socket etc. In this section, we will list important methods of some of the common modules.

Math module

The ceil() method returns the integer ceiling, that is the smallest integer which is greater than (or equal to) the given integer. This method takes float as an input. Please note that we begin by importing the module.

 >>> import math
 >>> math.ceil(2.13)
 3.0
 >>> math.ceil(-2.13)
 -2.0
 >>> math.ceil(2.00)
 2.0
 >>> math.ceil("xyz")
 Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 TypeError: a float is required
 >>> 

The floor() function does the opposite of the ceil() function -- it returns the largest integer which is smaller than or equal to the given integer; this method also takes float as an input.

 >>> math.floor(2.0)
 2.0
 >>> math.floor(2.3)
 2.0
 >>> math.floor(-2.3)
 -3.0
 >>> 

The fabs() method returns the absolute value of a given number. Takes float as an input.

 >>> math.fabs(2.00)
 2.0
 >>> math.fabs(-2.00)
 2.0
 >>> 

pi and e are mathematical constants.

 >>> math.pi
 3.1415926535897931
 >>> math.e
 2.7182818284590451
 >>> 

This module supports common trigonometrical functions: sin, cos, tan etc. These functions take input in radians.

 >>> math.sin(math.pi/2)
 1.0
 >>> math.sin((math.pi)/2)
 1.0
 >>> math.sin((math.pi)/4)
 0.70710678118654746
 >>> math.sin(0)
 0.0
 >>> 
 >>> math.cos(math.pi/4)
 0.70710678118654757
 >>> math.cos(0)
 1.0
 >>> math.cos(math.pi/2)
 6.123233995736766e-17
 >>> 
 >>> math.tan(math.pi/4)
 0.99999999999999989
 >>> math.tan(0)
 0.0
 >>> math.tan(math.pi/2)
 16331239353195370.0
 >>> 

Math module also provides methods for power and logarithmic operations. The function, pow(x,y) returns x to the power y. The function, log(x,[base]) returns log of x with base as "base". By default, the base is math.e. sqrt(x) returns the square root of x. hypot(x,y) returns the hypotenuse of a right-angled triangle with two sides, x and y; it equals math.sqrt(x*x + y*y).

 >>> math.pow(10,2)
 100.0
 >>> math.pow(10,-2)
 0.01
 >>> 
 >>> math.log(math.e)
 1.0
 >>> math.log(math.e*math.e)
 2.0
 >>> math.log(100,10)
 2.0
 >>> math.log(0.00001,10)
 -5.0
 >>> 
 >>> math.sqrt(100)
 10.0
 >>> math.sqrt(1)
 1.0
 >>> 
 >>> math.hypot(3,4)
 5.0
 >>> 

For getting a complete list of functions available in math module, we can use dir(math)

 >>> dir(math)
 ['__doc__', '__file__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 
 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'exp', 
 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'hypot', 'isinf', 'isnan', 
 'ldexp', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 
 'sqrt', 'tan', 'tanh', 'trunc']
 >>> 

String module

We have already seen various functions provided by string module in the string section. Hence, in this section, we will simply provide the complete list of all the functions.

 >>> import string
 >>> dir(string)
 ['Formatter', 'Template', '_TemplateMetaclass', '__builtins__', '__doc__', '__file__', 
 '__name__', '__package__', '_float', '_idmap', '_idmapL', '_int', '_long', '_multimap', 
 '_re', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'atof', 'atof_error', 'atoi', 
 'atoi_error', 'atol', 'atol_error', 'capitalize', 'capwords', 'center', 'count', 'digits', 
 'expandtabs', 'find', 'hexdigits', 'index', 'index_error', 'join', 'joinfields', 'letters', 
 'ljust', 'lower', 'lowercase', 'lstrip', 'maketrans', 'octdigits', 'printable', 
 'punctuation', 'replace', 'rfind', 'rindex', 'rjust', 'rsplit', 'rstrip', 'split', 
 'splitfields', 'strip', 'swapcase', 'translate', 'upper', 'uppercase', 'whitespace', 'zfill']
 >>> 

os module

This module provides methods to access operating system functionalities from within Python. For example, we can check if the environment variable, "SHELL" is set or not.

 >>> import os
 >>> 
 >>> os.getenv("SHELL")
 '/bin/bash'
 >>> 
 >>> os.getenv("NEW_SHELL")
 >>> 
 >>> os.name
 'posix'
 >>>

system() is an important method available within the os module. It allows users to execute system commands from within Python.

 >>> os.system("whoami")
 jdoe
 0
 >>> 
 >>> os.system("wc joke.txt")
 6      23     167 joke.txt
 0
 >>> 
 >>> os.system("login")
 login: jdoe
 Password:
 Last login: Sun Dec 27 16:17:00 on ttys000
 term$ exit
 logout
 0
 >>> 

And we can even kill the Python interpreter using the method, abort()!

 >>> os.abort()
 Abort trap
 term$

Here is a complete list. We encourage readers to explore some of these on their own!

 >>> dir(os)
 ['EX_CANTCREAT', 'EX_CONFIG', 'EX_DATAERR', 'EX_IOERR', 'EX_NOHOST', 'EX_NOINPUT', 
 'EX_NOPERM', 'EX_NOUSER', 'EX_OK', 'EX_OSERR', 'EX_OSFILE', 'EX_PROTOCOL', 
 'EX_SOFTWARE', 'EX_TEMPFAIL', 'EX_UNAVAILABLE', 'EX_USAGE', 'F_OK', 'NGROUPS_MAX', 
 'O_APPEND', 'O_ASYNC', 'O_CREAT', 'O_DIRECTORY', 'O_DSYNC', 'O_EXCL', 'O_EXLOCK', 
 'O_NDELAY', 'O_NOCTTY', 'O_NOFOLLOW', 'O_NONBLOCK', 'O_RDONLY', 'O_RDWR', 'O_SHLOCK', 
 'O_SYNC', 'O_TRUNC', 'O_WRONLY', 'P_NOWAIT', 'P_NOWAITO', 'P_WAIT', 'R_OK', 'SEEK_CUR', 
 'SEEK_END', 'SEEK_SET', 'TMP_MAX', 'UserDict', 'WCONTINUED', 'WCOREDUMP', 'WEXITSTATUS', 
 'WIFCONTINUED', 'WIFEXITED', 'WIFSIGNALED', 'WIFSTOPPED', 'WNOHANG', 'WSTOPSIG', 
 'WTERMSIG', 'WUNTRACED', 'W_OK', 'X_OK', '_Environ', '__all__', '__builtins__', 
 '__doc__', '__file__', '__name__', '__package__', '_copy_reg', '_execvpe', '_exists', 
 '_exit', '_get_exports_list', '_make_stat_result', '_make_statvfs_result', 
 '_pickle_stat_result', '_pickle_statvfs_result', '_spawnvef', 'abort', 'access', 
 'altsep', 'chdir', 'chflags', 'chmod', 'chown', 'chroot', 'close', 'closerange', 
 'confstr', 'confstr_names', 'ctermid', 'curdir', 'defpath', 'devnull', 'dup', 'dup2', 
 'environ', 'errno', 'error', 'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 
 'execvp', 'execvpe', 'extsep', 'fchdir', 'fchmod', 'fchown', 'fdopen', 'fork', 'forkpty', 
 'fpathconf', 'fstat', 'fstatvfs', 'fsync', 'ftruncate', 'getcwd', 'getcwdu', 'getegid', 
 'getenv', 'geteuid', 'getgid', 'getgroups', 'getloadavg', 'getlogin', 'getpgid', 
 'getpgrp', 'getpid', 'getppid', 'getsid', 'getuid', 'isatty', 'kill', 'killpg', 
 'lchflags', 'lchmod', 'lchown', 'linesep', 'link', 'listdir', 'lseek', 'lstat', 'major', 
 'makedev', 'makedirs', 'minor', 'mkdir', 'mkfifo', 'mknod', 'name', 'nice', 'open', 
 'openpty', 'pardir', 'path', 'pathconf', 'pathconf_names', 'pathsep', 'pipe', 'popen', 
 'popen2', 'popen3', 'popen4', 'putenv', 'read', 'readlink', 'remove', 'removedirs', 
 'rename', 'renames', 'rmdir', 'sep', 'setegid', 'seteuid', 'setgid', 'setgroups', 
 'setpgid', 'setpgrp', 'setregid', 'setreuid', 'setsid', 'setuid', 'spawnl', 'spawnle', 
 'spawnlp', 'spawnlpe', 'spawnv', 'spawnve', 'spawnvp', 'spawnvpe', 'stat', 
 'stat_float_times', 'stat_result', 'statvfs', 'statvfs_result', 'strerror', 'symlink', 
 'sys', 'sysconf', 'sysconf_names', 'system', 'tcgetpgrp', 'tcsetpgrp', 'tempnam', 
 'times', 'tmpfile', 'tmpnam', 'ttyname', 'umask', 'uname', 'unlink', 'unsetenv', 
 'urandom', 'utime', 'wait', 'wait3', 'wait4', 'waitpid', 'walk', 'write']
 >>> 

sys module

Python uses this module to provide access to variables and methods used by the Python interpreter.

platform() prints the current platform on which this code is being run. For MAC OS X:

 >>> import sys
 >>> sys.platform
 'darwin'
 >>> 

If we want to know the version number of the Python interpreter being used, we can use the version command.

 >>> sys.version
 '2.6.1 (r261:67515, Jul  7 2009, 23:51:51) \n[GCC 4.2.1 (Apple Inc. build 5646)]'
 >>> 

We can play with the stdout/stdin/stderr streams. If we write to stdout, it shows directly on the terminal.

 >>> sys.stdout.write("Hi there \n")
 Hi there 
 >>> 
 >>> sys.stderr.write("This is an error\n")
 This is an error
 >>> 
 >>> 
 >>> sys.stdin.readline()
 This is a line. Please read it to me
 'This is a line. Please read it to me\n'
 >>> 

If we are running a program where we require a large number of recursions (a given function calls itself), then we might hit the default limit. We can set this limit as follows:

 >>> sys.getrecursionlimit()
 1000
 >>> sys.setrecursionlimit(10000)
 >>> sys.getrecursionlimit()
 10000
 >>> 

Here is a complete list:

 >>> dir(sys)
 ['__displayhook__', '__doc__', '__excepthook__', '__name__', '__package__', '__stderr__', 
 '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_getframe', 
 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 
 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_clear', 'exc_info', 'exc_type', 
 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 
 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding', 
 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'gettrace', 'hexversion', 
 'last_traceback', 'last_type', 'last_value', 'maxint', 'maxsize', 'maxunicode', 
 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 
 'prefix', 'ps1', 'ps2', 'py3kwarning', 'setcheckinterval', 'setdlopenflags', 'setprofile', 
 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 
 'version_info', 'warnoptions']
 >>> 




comments powered by Disqus