In [ ]:
# modules
# module is a collection of functions/variables which can be used later.
# f1.py - fun1,fun2,fun3,fun4,fun5
# f2.py - fun1,fun2,fun3,f1.fun1
# this makes sure we dont have to deal with program namespaces.

In [ ]:
# why do you save your program as .py ?
# if you dont save your program as a .py , you cannot use it as module in future.

In [1]:
# modules
help()


Welcome to Python 2.7!  This is the online help utility.

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/2.7/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules.  To quit this help utility and
return to the interpreter, just type "quit".

To get a list of available modules, keywords, or topics, type "modules",
"keywords", or "topics".  Each module also comes with a one-line summary
of what it does; to list the modules whose summaries contain a given word
such as "spam", type "modules spam".

help> modules

Please wait a moment while I gather a list of all available modules...

/usr/local/lib/python2.7/dist-packages/IPython/kernel/__init__.py:13: ShimWarning: The `IPython.kernel` package has been deprecated. You should import from ipykernel or jupyter_client instead.
  "You should import from ipykernel or jupyter_client instead.", ShimWarning)
/usr/lib/python2.7/dist-packages/gobject/constants.py:24: Warning: g_boxed_type_register_static: assertion 'g_type_from_name (name) == 0' failed
  import gobject._gobject
No handlers could be found for logger "oneconf.distributor"
/usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:127: RuntimeWarning: PyOS_InputHook is not available for interactive use of PyGTK
  set_interactive(1)
ANSI                apt                 gtkunixprint        requests
AptUrl              apt_inst            gzip                resource
BaseHTTPServer      apt_pkg             hashlib             rexec
Bastion             aptdaemon           heapq               rfc822
BeautifulSoup       aptsources          hmac                rlcompleter
BeautifulSoupTests  argparse            hotshot             rmagic
CDROM               array               html5lib            robotparser
CGIHTTPServer       ast                 htmlentitydefs      runpy
Canvas              asynchat            htmllib             samba
CommandNotFound     asyncore            httplib             sched
ConfigParser        atexit              httplib2            screen
Cookie              atk                 idlelib             select
Crypto              audiodev            ihooks              serial
DLFCN               audioop             imaplib             sessioninstaller
Dialog              autoreload          imghdr              sets
DocXMLRPCServer     axi                 imp                 setuptools
Exscript            backports           importlib           sexy
Exscriptd           backports_abc       imputil             sgmllib
FSM                 base64              inspect             sha
FileDialog          bdb                 io                  shelve
FixTk               binascii            ipykernel           shlex
HTMLParser          binhex              ipython_genutils    shutil
IN                  bisect              ipywidgets          shutil_backports
IPython             bonobo              itertools           signal
Image               bpdb                jinja2              simplegeneric
ImageChops          bpython             json                singledispatch
ImageColor          bsddb               jsonschema          singledispatch_helpers
ImageCrackCode      bz2                 jupyter             sip
ImageDraw           cPickle             jupyter_client      sipconfig
ImageEnhance        cProfile            jupyter_console     sipconfig_nd
ImageFile           cStringIO           jupyter_core        site
ImageFileIO         cairo               keyword             sitecustomize
ImageFilter         calendar            ldb                 six
ImageFont           caribou             lib2to3             smbc
ImageGL             certifi             libxml2             smtpd
ImageGrab           cgi                 libxml2mod          smtplib
ImageMath           cgitb               linecache           sndhdr
ImageOps            chardet             linuxaudiodev       socket
ImagePalette        chunk               locale              spwd
ImagePath           cmath               lockfile            spyderlib
ImageQt             cmd                 logging             spyderplugins
ImageSequence       code                lsb_release         sqlite3
ImageStat           codecs              lxml                sre
ImageTk             codeop              macpath             sre_compile
ImageWin            collections         macurl2path         sre_constants
MimeWriter          colorama            mailbox             sre_parse
MySQLdb             colorsys            mailcap             ssl
ORBit               commands            mako                stat
OpenSSL             compileall          markupbase          statvfs
PAM                 compiler            markupsafe          storemagic
PIL                 configglue          marshal             string
PSDraw              configobj           math                stringold
PngImagePlugin      configparser        md5                 stringprep
PyQt4               contextlib          mhlib               strop
Queue               cookielib           mimetools           struct
ScrolledText        copy                mimetypes           subprocess
SimpleDialog        copy_reg            mimify              sunau
SimpleHTTPServer    crypt               mistune             sunaudio
SimpleXMLRPCServer  csv                 mmap                symbol
SocketServer        ctypes              modulefinder        sympyprinting
StringIO            cups                multifile           symtable
TYPES               cupshelpers         multiprocessing     sys
Tix                 curl                mutex               sysconfig
TkExscript          curses              mysql               syslog
Tkconstants         cv                  nbconvert           tabnanny
Tkdnd               cv2                 nbformat            talloc
Tkinter             cythonmagic         netrc               tarfile
UbuntuSystemService datetime            new                 tdb
UserDict            dbhash              nis                 telnetlib
UserList            dbm                 nntplib             tempfile
UserString          dbus                notebook            terminado
_LWPCookieJar       deb822              ntdb                termios
_MozillaCookieJar   debconf             ntpath              test
__builtin__         debian              nturl2path          tests
__future__          debian_bundle       numbers             textwrap
_abcoll             debtagshw           numpy               this
_ast                decimal             oauthlib            thread
_bisect             decorator           oneconf             threading
_bsddb              defer               opcode              tidy
_codecs             difflib             operator            time
_codecs_cn          dircache            optparse            timeit
_codecs_hk          dirspec             os                  tkColorChooser
_codecs_iso2022     dis                 os2emxpath          tkCommonDialog
_codecs_jp          distlib             ossaudiodev         tkFileDialog
_codecs_kr          distutils           pango               tkFont
_codecs_tw          django              pangocairo          tkMessageBox
_collections        dns                 paramiko            tkSimpleDialog
_csv                doctest             parser              toaiff
_ctypes             drv_libxml2         parted              token
_ctypes_test        dsextras            pathlib2            tokenize
_curses             dumbdbm             pdb                 tornado
_curses_panel       dummy_thread        pexpect             trace
_dbus_bindings      dummy_threading     pickle              traceback
_dbus_glib_bindings duplicity           pickleshare         traitlets
_elementtree        easy_install        pickletools         ttk
_functools          email               pip                 tty
_hashlib            encodings           pipes               turtle
_heapq              entrypoints         piston_mini_client  twisted
_hotshot            errno               pkg_resources       types
_io                 exceptions          pkgutil             ubuntu_sso
_json               fabfile             platform            unicodedata
_locale             fabric              plistlib            unittest
_lsprof             fcntl               popen2              urllib
_markerlib          fdpexpect           poplib              urllib2
_md5                feedparser          posix               urllib3
_multibytecodec     filecmp             posixfile           urlparse
_multiprocessing    fileinput           posixpath           user
_mysql              fnmatch             pprint              uu
_mysql_exceptions   formatter           profile             uuid
_osx_support        fpectl              prompt_toolkit      validate
_ped                fpformat            pstats              virtualenv
_pyio               fractions           pty                 vte
_random             ftplib              ptyprocess          warnings
_sha                functools           pwd                 wave
_sha256             functools32         pxssh               wcwidth
_sha512             future_builtins     py_compile          weakref
_smbc               gc                  pyatspi             webbrowser
_socket             gconf               pyclbr              webkit
_sqlite3            gdbm                pycurl              whichdb
_sre                genericpath         pydoc               widgetsnbextension
_ssl                getopt              pydoc_data          wsgiref
_strptime           getpass             pyexpat             xapian
_struct             gettext             pygments            xdg
_symtable           gi                  pygtk               xdrlib
_sysconfigdata      gio                 pygtkcompat         xml
_sysconfigdata_nd   glib                pyinotify           xmllib
_testcapi           glob                pynotify            xmlrpclib
_threading_local    gnome               pyodbc              xxsubtype
_tkinter            gnomecanvas         pysqlite2           zipfile
_warnings           gnomekeyring        qtconsole           zipimport
_weakref            gnomevfs            quopri              zlib
_weakrefset         gobject             random              zmq
abc                 google              re                  zope
aifc                grp                 readline            
antigravity         gtk                 reportlab           
anydbm              gtksourceview2      repr                

Enter any module name to get more help.  Or, type "modules spam" to search
for modules whose descriptions contain the word "spam".

help> quit

You are now leaving help and returning to the Python interpreter.
If you want to ask for help on a particular object directly from the
interpreter, you can type "help(object)".  Executing "help('string')"
has the same effect as typing a particular string at the help> prompt.

In [2]:
# math
import math

In [3]:
print dir(math)
# or
# math.<tab> in ipython


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

In [4]:
print math.pi


3.14159265359

In [5]:
print help(math.pow)


Help on built-in function pow in module math:

pow(...)
    pow(x, y)
    
    Return x**y (x to the power of y).

None

In [6]:
print math.pow(2,3)


8.0

In [ ]:
# type 2

In [7]:
import math as m

In [8]:
print m.pi
print m.pow(2,3)


3.14159265359
8.0

In [9]:
# type 3

In [10]:
# your are making pi and pow part of local namespace
from math import pi,pow
print pi
print pow(2,3)


3.14159265359
8.0

In [11]:
# type 4
# DONT TRY THIS AT HOME AND OFFICE.
# from math import *

In [ ]:
# location of first.py under modules folder
In [4]: pwd Out[4]: u'/home/tcloudost/Documents/git_repositories/python-batches/batch-58/modules' In [5]: ls first.py Learning_Modules.ipynb In [6]: import first as f In [7]: print dir(f) ['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'my_add', 'my_div', 'my_multi', 'my_sub', 'version'] In [8]: f.my_add? Signature: f.my_add(a, b) Docstring: This is for addition of number/strings File: ~/Documents/git_repositories/python-batches/batch-58/modules/first.py Type: function In [9]: f.my_sub? Signature: f.my_sub(a, b) Docstring: This is for substraction of number File: ~/Documents/git_repositories/python-batches/batch-58/modules/first.py Type: function In [10]: f.version Out[10]: 1.0 In [11]: f.my_add(1,2) Out[11]: 3 In [12]: f.my_add('linux','rocks') Out[12]: 'linuxrocks' # made a modification of version=2.0 in my first.py program. In [13]: f.version Out[13]: 1.0 In [14]: import first as f In [15]: f.version Out[15]: 1.0 In [16]: ls first.py first.pyc Learning_Modules.ipynb In [17]: reload(f) Out[17]: In [18]: f.version Out[18]: 2.0 tcloudost@tcloudost-VirtualBox ~/Documents/git_repositories/python-batches/batch-58/modules $ file first.pyc first.pyc: python 2.7 byte-compiled tcloudost@tcloudost-VirtualBox ~/Documents/git_repositories/python-batches/batch-58/modules $ cat fist.pyc cat: fist.pyc: No such file or directory tcloudost@tcloudost-VirtualBox ~/Documents/git_repositories/python-batches/batch-58/modules $ cat first.pyc * .pyc file is platform independent and can be imported without a .py file. * .pyc can be regenerated provided we have .py file. * .py cannot be regenerated, so dont delete it.
Modules :ls first.py first.pyc Learning_Modules.ipynb Modules :ipython Python 2.7.6 (default, Jun 22 2015, 17:58:13) Type "copyright", "credits" or "license" for more information. IPython 5.1.0 -- An enhanced Interactive Python. ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object', use 'object??' for extra details. In [1]: import first as f Launching a Missile. In [2]:
In [2]: f.my_add Out[2]: In [3]: def g(): ...: pass ...: In [4]: g Out[4]: In [5]: globals Out[5]: In [6]: globals() Out[6]: {'In': ['', u'import first as f', u'f.my_add', u'def g():\n pass', u'g', u'globals', u'globals()'], 'Out': {2: , 4: , 5: }, '_': , '_2': , '_4': , '_5': , '__': , '___': , '__builtin__': , '__builtins__': , '__doc__': 'Automatically created module for IPython interactive environment', '__name__': '__main__', '__package__': None, '_dh': [u'/home/tcloudost/Documents/git_repositories/python-batches/batch-58/modules'], '_i': u'globals', '_i1': u'import first as f', '_i2': u'f.my_add', '_i3': u'def g():\n pass', '_i4': u'g', '_i5': u'globals', '_i6': u'globals()', '_ih': ['', u'import first as f', u'f.my_add', u'def g():\n pass', u'g', u'globals', u'globals()'], '_ii': u'g', '_iii': u'def g():\n pass', '_oh': {2: , 4: , 5: }, '_sh': , 'exit': , 'f': , 'g': , 'get_ipython': >, 'quit': }
In [1]: import first as f In [2]: f. f.my_add f.my_sub f.my_div f.version f.my_multi Modules : Modules :python first.py Launching a Missile. Modules :
-- created a second.py file in same folder and it worked fine --- Modules :ls first.py first.pyc Learning_Modules.ipynb second.py Modules : Modules :python second.py addition of two numbers is 5 addition of two strings is linuxrocks Modules : Modules :ls -l total 40 drwxr-xr-x 2 tcloudost tcloudost 4096 Feb 24 08:45 extra -rw-r--r-- 1 tcloudost tcloudost 408 Feb 24 08:39 first.py -rw-r--r-- 1 tcloudost tcloudost 1216 Feb 24 08:43 first.pyc -rw-r--r-- 1 tcloudost tcloudost 24107 Feb 24 08:39 Learning_Modules.ipynb -rw-r--r-- 1 tcloudost tcloudost 300 Feb 24 08:44 second.py --- created a new folder - extra and moved first.py to extra folder --- Modules :ls -l total 40 drwxr-xr-x 2 tcloudost tcloudost 4096 Feb 24 08:45 extra -rw-r--r-- 1 tcloudost tcloudost 408 Feb 24 08:39 first.py -rw-r--r-- 1 tcloudost tcloudost 1216 Feb 24 08:43 first.pyc -rw-r--r-- 1 tcloudost tcloudost 24107 Feb 24 08:39 Learning_Modules.ipynb -rw-r--r-- 1 tcloudost tcloudost 300 Feb 24 08:44 second.py Modules :mv first.py extra/ Modules : Modules :ls extra first.pyc Learning_Modules.ipynb second.py Modules : Modules :python second.py addition of two numbers is 5 addition of two strings is linuxrocks Modules : Modules :ls extra first.pyc Learning_Modules.ipynb second.py Modules : Modules :rm -f first.pyc Modules : Modules :python second.py Traceback (most recent call last): File "second.py", line 3, in import first as f ImportError: No module named first
# os specific # yum install django or apt-get install django # installation of a module # pip install # ex: pip install django (latest version) # ex: pip install django==1.8 # easy_install # easy_install # setuptools
# virtualenv Installation of virtual env: https://virtualenv.pypa.io/en/stable/installation/ tcloudost@tcloudost-VirtualBox ~/Documents/git_repositories/python-batches/batch-58 $ python Python 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import excel Traceback (most recent call last): File "", line 1, in ImportError: No module named excel >>> Modules : pwd /home/tcloudost/Documents/git_repositories/python-batches/batch-58/modules Modules : virtualenv sheets New python executable in sheets/bin/python Installing setuptools, pip...done. Modules : Modules : ls extra Learning_Modules.ipynb second.py sheets Modules : Modules : source sheets/bin/activate (sheets)Modules : ls sheets bin include lib local (sheets)Modules : (sheets)Modules : pip freeze argparse==1.2.1 wsgiref==0.1.2 (sheets)Modules : #http_port (sheets)Modules : #https_port (sheets)Modules : (sheets)Modules : pip install excel Downloading/unpacking excel Downloading excel-1.0.0.tar.gz Running setup.py (path:/home/tcloudost/Documents/git_repositories/python-batches/batch-58/modules/sheets/build/excel/setup.py) egg_info for package excel Downloading/unpacking xlrd (from excel) Downloading xlrd-1.0.0.tar.gz (2.6MB): 2.6MB downloaded Running setup.py (path:/home/tcloudost/Documents/git_repositories/python-batches/batch-58/modules/sheets/build/xlrd/setup.py) egg_info for package xlrd warning: no files found matching 'README.html' Installing collected packages: excel, xlrd Running setup.py install for excel Running setup.py install for xlrd changing mode of build/scripts-2.7/runxlrd.py from 644 to 755 warning: no files found matching 'README.html' changing mode of /home/tcloudost/Documents/git_repositories/python-batches/batch-58/modules/sheets/bin/runxlrd.py to 755 Successfully installed excel xlrd Cleaning up... (sheets)Modules : pip freeze argparse==1.2.1 excel==1.0.0 wsgiref==0.1.2 xlrd==1.0.0 (sheets)Modules : python Python 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import excel >>> quit() (sheets)Modules : deactivate Modules : Modules : ls extra Learning_Modules.ipynb second.py sheets Modules : # pydoc Modules : pydoc first Modules : pydoc math
# package # https://docs.python.org/2/tutorial/modules.html#packages # https://docs.python.org/2/installing/index.html # https://docs.python.org/2/distributing/index.html # https://docs.python.org/2/distutils/ # how to create a package. * first create a OS folder and within in create lin,sol,aix,hpux # mkdir OS # mkdir OS/{lin,sol,aix,hpux} # later create first.py,second.py,third.py and fourth.py inside it. # please see these files from your git location. # from OS folder when you try to import lin you fail. Modules : ipython Python 2.7.6 (default, Jun 22 2015, 17:58:13) Type "copyright", "credits" or "license" for more information. IPython 5.1.0 -- An enhanced Interactive Python. ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object', use 'object??' for extra details. In [1]: import lin --------------------------------------------------------------------------- ImportError Traceback (most recent call last) in () ----> 1 import lin ImportError: No module named lin # also create a __init__.py under your lin folder to import the files under the lin folder. # cat __init__.py import first import second import third import fourth In [2]: import lin In [3]: lin.first.my_first_lin1() Out[3]: 'this is my first lin1 function' In [4]: lin.second.my_first_lin2() Out[4]: 'this is my first lin2 function' # Later copy the content of lin to sol. # cp sol/*.py lin/*.py # Make sure your __init__.py looks a this. Modules Tree: cat OS/sol/__init__.py import first import second import third # when you import the sol you will see only first,second and third getting imported. Modules : python Python 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sol >>> print dir(sol) ['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', 'first', 'second', 'third'] >>> # the best part is we can explicitly import the fourth module too. In [1]: import sol In [2]: from sol import fourth In [3]: sol. sol.first sol.second sol.fourth sol.third example: -------- tcloudost@tcloudost-VirtualBox /usr/lib/python2.7/xml $ ls dom etree __init__.py __init__.pyc parsers sax tcloudost@tcloudost-VirtualBox /usr/lib/python2.7/xml $ ls dom domreg.py expatbuilder.pyc minicompat.py minidom.pyc pulldom.py xmlbuilder.pyc domreg.pyc __init__.py minicompat.pyc NodeFilter.py pulldom.pyc expatbuilder.py __init__.pyc minidom.py NodeFilter.pyc xmlbuilder.py tcloudost@tcloudost-VirtualBox /usr/lib/python2.7/xml $ ls etree cElementTree.py ElementInclude.py ElementPath.py ElementTree.py __init__.py cElementTree.pyc ElementInclude.pyc ElementPath.pyc ElementTree.pyc __init__.pyc tcloudost@tcloudost-VirtualBox /usr/lib/python2.7/xml $ ls parsers expat.py expat.pyc __init__.py __init__.pyc tcloudost@tcloudost-VirtualBox /usr/lib/python2.7/xml $ ls sax _exceptions.py expatreader.py handler.py __init__.py saxutils.py xmlreader.py _exceptions.pyc expatreader.pyc handler.pyc __init__.pyc saxutils.pyc xmlreader.pyc tcloudost@tcloudost-VirtualBox /usr/lib/python2.7/xml $ tcloudost@tcloudost-VirtualBox /usr/lib/python2.7/xml $ pwd /usr/lib/python2.7/xml tcloudost@tcloudost-VirtualBox /usr/lib/python2.7/xml $

In [ ]:
# exercises
https://github.com/zhiwehu/Python-programming-exercises/blob/master/100%2B%20Python%20challenging%20programming%20exercises.txt