Python Essentials Training
5-day session

Overview
Understanding principles of Object Oriented Programming
Understanding the structure of a Python program
Understanding module, class and object
Understanding Polymorphism and Inheritance
Practical labs with Python 3.x Interprete
Duration
Five days - 40 hours (8 hours a day)
50% of lecture, 50% of practical labs.

Trainer
Audience
Professional embedded Software developers
Embedded developers.
People supporting large scale products.
Prerequisite
Knowledge of Shell Scripting programming
In particular, participants should be familiar with writing scripts in Unix
Shell Programming. Basic syntax and execution flow knowledge is required.
Shell Programming training agenda is available at
http://www.minhinc.com/training/li/advance-li-agenda.php

and can be downloaded from
http://www.minhinc.com/training/advance-li-agenda.pdf

Knowledge of Object Oriented Concepts
Oops concept like Abstraction, Inheritance, Polymorphism would help.

Setup
Machine with Python 3.x interpreter installed.
© www.minhinc.com
p1
Lecture
Lecture session will be course content presentation through the trainer.
Any source code example related to the topic will be demonstrated, it would
include executing the binaries.
Complete lecture material can be downloaded from
http://www.minhinc.com/training/advance-py-slides.pdf
Labs
Labs session would be completely hands on session where each example
(with example data and execution instruction) would be provided to the
students. Students can verify their results with the results provided in
the material.
Day 1 Morning

© www.MinhInc.com
p2
Day 1 Afternoon

     Lab
Day 2 Morning

Day 2 Afternoon

     Lab
© www.MinhInc.com
p3
Day 3 Morning

Day 3 Afternoon

     Lab
Day 4 Morning

© www.MinhInc.com
p4
Day 4 Afternoon

     Lab
Day 5 Morning

Day 5 Afternoon

     Lab
© www.MinhInc.com
p5
Python Essentials
Python Essenstials- Training Course
Minh, Inc.
DISCLAIMER

Text of this document is written in Bembo Std Otf(13 pt) font.

Code parts are written in Consolas (10 pts) font.

This training material is provided through Minh, Inc., B'lore, India
Pdf version of this document is available at http://www.minhinc.com/training/advance-py-slides.pdf
For suggestion(s) or complaint(s) write to us at sales@minhinc.com

Document modified on Jun-12-2021 

Document contains 41 pages.
 
Day 1 Morning

  1. Basic structure of Python program

Python is an interperative language. Python scripts are interpreted through python interpreter binary. On linux, path of python interpreter is /usr/bin/python<version>. For python3.8 it would be /usr/bin/python3.8
  
minhinc@minhinc:~/tmp$ ls -la /usr/bin | grep -i python3
lrwxrwxrwx  1 root root          56 Jan  5 10:52 apt-changelog -> ../lib/python3/dist-packages/mintcommon/apt_changelog.py
-rwxr-xr-x  1 root root        2336 Jun 20  2017 dh_python3-ply
lrwxrwxrwx  1 root root          23 Jan 27 21:11 pdb3.8 -> ../lib/python3.8/pdb.py
lrwxrwxrwx  1 root root          31 Jan  5 10:53 py3versions -> ../share/python3/py3versions.py
lrwxrwxrwx  1 root root           9 Jan  5 10:53 python3 -> python3.8
-rwxr-xr-x  1 root root     5486384 Jan 27 21:11 python3.8
lrwxrwxrwx  1 root root          33 Jan 27 21:11 python3.8-config -> x86_64-linux-gnu-python3.8-config
lrwxrwxrwx  1 root root          16 Mar 13  2020 python3-config -> python3.8-config
-rwxr-xr-x  1 root root        3240 Jan 27 21:11 x86_64-linux-gnu-python3.8-config
lrwxrwxrwx  1 root root          33 Mar 13  2020 x86_64-linux-gnu-python3-config -> x86_64-linux-gnu-python3.8-config 
  
Day 1 Morning
  1. Basic structure of Python program
Python interpreter can run in interactive mode. It provides command prompt 
>>>
and
...
.
>>>
prompts for python command where as three dots
...
is for multiline statements.
minhinc@minhinc:~/tmp/$ python3
Python 3.8.5 (default, Jan 27 2021, 15:41:15) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> class A:
...  pass
... 
>>> a=b=A()
>>> print(a is b)
True
>>> quit() 
When multiline statements are over, 'Enter' key needs to be pressed.
 
Commands can be entered through '-c' option on python interpretor. 
python3 -c 'print("hello world")'
would print "hello world". Above code can be written as
minhinc@minhinc:~/tmp$ python3 -c "exec('class A:\n pass\na=b=A()\nprint(a is b)')"
True 
  
Day 1 Morning
  1. Basic structure of Python program
Python programs can be written in a module. Module can be called as 
python3 -m <modulename>
. If module name is helloworld.py then it can be called as
python3 -m helloworld
. helloworld.py module must be in PYTHONPATH or sys.path. module can also be executed as script
python3 <scriptname>
. Here it would be
python3 helloworld.py
. In this case full path must be given.
minhinc@minhinc:~/tmp$ cat helloworld.py 
def func(): 
© www.minhinc.com
p6
 print('hello world')
 
func()
minhinc@minhinc:~/tmp$ python3 -m helloworld
hello world
minhinc@minhinc:~/tmp$ cd ..
minhinc@minhinc:~$ export PYTHONPATH=~/tmp:$PYTHONPATH
minhinc@minhinc:~$ python3 -m helloworld
hello world
minhinc@minhinc:~$ python3 tmp/helloworld.py 
hello world 
 
Python3 interpretor can also be invoked through argument '-i', interactive mode. This would execute the module or script and enter into interactive mode. More commands can be executed against the module/script afterwards.
  
minhinc@minhinc:~/tmp$ cat helloworld.py 
def func():
 print('hello world')
 
func()
minhinc@minhinc:~$ python3 -i tmp/helloworld.py 
hello world
>>> func()
hello world
minhinc@minhinc:~/tmp$ python3 -i -m helloworld
hello world
>>> func()
hello world
>>> quit() 
  
Day 1 Morning
  1. Basic structure of Python program
In interactive mode python3 executes main module. All code written belongs to main module. Module namespace contains '__name__' key which has value of '__main__'
  
minhinc@minhinc:~/tmp$ python3
Python 3.8.5 (default, Jan 27 2021, 15:41:15) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
>>> __name__
'__main__'
>>> quit()
minhinc@minhinc:~/tmp$ python3 -c 'print(__name__)'
__main__
minhinc@minhinc:~/tmp$ python3 -i -c 'print(__name__)'
__main__
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__'] 
 
Module or script that runs directly through python3 interpreter in scripting mode is main module. when interpreter runs with argument 
-i
then module or script runs as main module.
minhinc@minhinc:~/tmp$ cat helloworld.py 
def func():
 print('hello world')
 
func()
print('__name__ is',__name__)
minhinc@minhinc:~/tmp$ python3 -i -m helloworld
hello world
__name__ is __main__
>>> dir()
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'func']
>>> __name__
'__main__'
>>> quit()
minhinc@minhinc:~/tmp$ python3 -i helloworld.py
hello world 
© www.minhinc.com
p7
__name__ is __main__
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'func']
>>> __name__
'__main__' 
  
Day 1 Morning
  1. Basic structure of Python program
python interpreter import 'builtins' module when 'main' module loads. 
from builtins import * 
built types are imported in this fashion,i.e exceptions, string, int, tuple, list, dict, bool,classmethod,staticmethodl etc. 
minhinc@minhinc:~/tmp/MISC/gc$ python3
Python 3.8.5 (default, May 27 2021, 13:30:53) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import builtins
>>> dir(builtins) 
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip'] 
module package information like package installation path are provided through __spec__ key in the namespace 
import PySide6
>>> PySide6.__spec__
ModuleSpec(name='PySide6', loader=<_frozen_importlib_external.SourceFileLoader object at 0x7f3d524955b0>, origin='/usr/local/lib/python3.8/dist-packages/PySide6/__init__.py', submodule_search_locations=['/usr/local/lib/python3.8/dist-packages/PySide6']) 
python interpreter provide help service where list of library modules, keywords, symbols and topics can be listed. 
minhinc@minhinc:~/tmp/MISC/gc$ python3
Python 3.8.5 (default, May 27 2021, 13:30:53) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> help()
 
Welcome to Python 3.8's help utility!
 
If this is your first time using Python, you should definitely check out
the tutorial on the Internet at https://docs.python.org/3.8/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, symbols, or topics, type
"modules", "keywords", "symbols", or "topics".  Each module also comes
with a one-line summary of what it does; to list the modules whose name
or summary contain a given string such as "spam", type "modules spam".
 
help> modules
 
Please wait a moment while I gather a list of all available modules... 
Appearance          _version            enum                pylab
AptUrl              _warnings           errno               pylint
AtspiStateTracker   _weakref            fasteners           pymacaroons
AutoHide            _weakrefset         faulthandler        pyparsing
AutoShow            _xxsubinterpreters  fcntl               pyphen
ClickSimulator      _xxtestfuzz         fetchm              pypredict
CommandNotFound     _yaml               filecmp             pyrfc3339
Config              abc                 fileinput           pytz
ConfigUtils         agenda              fnmatch             queue
Crypto              aifc                formatter           quopri
DBusUtils           antigravity         fractions           random
Exceptions          apiclient           ftplib              re
GlobalKeyListener   apport              functools           read
HardwareSensorTracker apport_python_hook  gc                  readline
IconPalette         apt                 genericpath         redshift_gtk
Indicator           apt_clone           getconsole          reportlab
KbdWindow           apt_inst            getcontactm         reprlib
KeyCommon           apt_pkg             getopt              requests
KeyGtk              aptdaemon           getpass             requests_unixsocket
Keyboard            aptsources          gettext             resource
KeyboardPopups      argparse            gi                  rlcompleter
KeyboardWidget      array               glob                rsa
LanguageSupport     ast                 google_auth_httplib2 runpy
Layout              astroid             googleapiclient     samba
LayoutLoaderSVG     asynchat            grp                 scanext
LayoutView          asyncio             grpc                sched
MySQLdb             asyncore            gzip                secrets
NvidiaDetector      atexit              hashlib             secretstorage
Onboard             audioop             heapq               seed
OnboardGtk          base64              hmac                select
OpenSSL             bdb                 hpmudext            selectors 
© www.minhinc.com
p8
PAM                 binascii            html                selenium
PIL                 binhex              html5lib            sendmailm
PyICU               bisect              http                setproctitle
PyQt5               blinker             httplib2            settings
PySide6             brain_argparse      icu                 setuptools
Quirks              brain_attrs         idna                shelve
Scanner             brain_builtin_inference ifaddr              shiboken6
SnippetView         brain_collections   imaplib             shlex
Sound               brain_crypt         imghdr              shutil
SpellChecker        brain_curses        imp                 signal
TextChanges         brain_dataclasses   importlib           simplejson
TextContext         brain_dateutil      inspect             sip
TextDomain          brain_fstrings      io                  sipconfig
Timer               brain_functools     ipaddr              sipconfig_nd8
TouchHandles        brain_gi            ipaddress           site
TouchInput          brain_hashlib       isort               sitecustomize
UDevTracker         brain_http          itertools           six
UbuntuDrivers       brain_io            json                smtpd
Version             brain_mechanize     jwt                 smtplib
WPEngine            brain_multiprocessing kazam               sndhdr
WindowUtils         brain_namedtuple_enum keyring             socket
WordSuggestions     brain_nose          keyword             socketserver
XInput              brain_numpy_core_fromnumeric kiwisolver          soupsieve
Xlib                brain_numpy_core_function_base launchpadlib        speechd
__future__          brain_numpy_core_multiarray lazy_object_proxy   speechd_config
_abc                brain_numpy_core_numeric ldb                 spwd
_ast                brain_numpy_core_numerictypes lib2to3             sqlalchemy
_asyncio            brain_numpy_core_umath linecache           sqlite3
_bisect             brain_numpy_ndarray listwidgetm         sre_compile
_blake2             brain_numpy_random_mtrand locale              sre_constants
_bootlocale         brain_numpy_utils   lockfile            sre_parse
_bz2                brain_pkg_resources logging             ssl
_cffi_backend       brain_pytest        louis               stat
_codecs             brain_qt            lsb_release         statistics
_codecs_cn          brain_random        lxml                string
_codecs_hk          brain_re            lzma                stringprep
_codecs_iso2022     brain_six           macaroonbakery      struct
_codecs_jp          brain_ssl           mailbox             subprocess
_codecs_kr          brain_subprocess    mailcap             sunau
_codecs_tw          brain_threading     mako                symbol
_collections        brain_typing        markupsafe          symtable
_collections_abc    brain_uuid          marshal             sys
_compat_pickle      brlapi              math                sysconfig
_compression        bs4                 matplotlib          syslog
_contextvars        builtins            mccabe              systemd
_crypt              bz2                 mimetypes           t
_csv                cProfile            mintcommon          t1
_ctypes             cachecontrol        mintreport          tabnanny
_ctypes_test        cachetools          mmap                talloc
_curses             cairo               modulefinder        tarfile
_curses_panel       cairocffi           monotonic           tdb
_datetime           cairosvg            mpl_toolkits        telnetlib
_dbm                calendar            msgpack             tempfile
_dbus_bindings      canonical_equivalents multiprocessing     termios
_dbus_glib_bindings caribou             nacl                test
_decimal            certifi             netifaces           textwrap
_dummy_thread       cffi                netrc               this
_elementtree        cgi                 nis                 threading
_functools          cgitb               nntplib             time
_gdbm               chainm              nose                timeit
_hashlib            chardet             ntpath              tinycss2
_heapq              chunk               nturl2path          tkinter
_icu                click               numbers             token
_imp                cmath               numpy               tokenize
_io                 cmd                 oauth2client        toml
_json               code                oauthlib            trace
_ldb_text           codecs              opcode              traceback
_locale             codeop              operator            tracemalloc
_lsprof             collections         optparse            tt
_lzma               colorama            orca                tty
_markupbase         colorsys            os                  turtle
_md5                compileall          osk                 tw
_multibytecodec     concurrent          ossaudiodev         types
_multiprocessing    configobj           packaging           typing
_opcode             configparser        parser              uaclient
_operator           contextlib          parted              ufw
_osx_support        contextvars         pathlib             unicodedata
_ped                copy                pcardext            unidecode
_pickle             copyreg             pdb                 unittest
_posixshmem         crypt               pdfkit              uno
_posixsubprocess    cryptography        pep517              unohelper
_py_abc             cssselect2          pexpect             uritemplate
_pydecimal          csv                 pickle              urllib
_pyio               ctypes              pickletools         urllib3
_queue              cups                pip                 utils
_random             cupsext             pipes               uu
_sha1               cupshelpers         pkg_resources       uuid
_sha256             curl                pkgutil             validate
_sha3               curses              platform            venv
_sha512             cycler              plistlib            wadllib
_signal             databasem           ply                 warnings
_sitebuiltins       dataclasses         poplib              wave
_socket             datetime            posix               weakref
_sqlite3            dateutil            posixpath           weasyprint
_sre                dbm                 pprint              webbrowser
_ssl                dbpushpullm         problem_report      webencodings
_stat               dbus                profile             wheel
_statistics         deb822              progress            widgetm
_string             debian              pstats              wrapt
_strptime           debian_bundle       psutil              wsgiref
_struct             decimal             pty                 xapp
_symtable           defer               ptyprocess          xcffib
_sysconfigdata__linux_x86_64-linux-gnu definitions         pwd                 xdg
_sysconfigdata__x86_64-linux-gnu defusedxml          py_compile          xdrlib
_tdb_text           difflib             pyasn1              xkit
_testbuffer         dis                 pyasn1_modules      xml
_testcapi           distlib             pyatspi             xmlrpc
_testimportmultiple distro              pyclbr              xxlimited
_testinternalcapi   distutils           pycparser           xxsubtype
_testmultiphase     doctest             pycurl              yaml
_thread             dummy_threading     pydoc               zeroconf
_threading_local    easy_install        pydoc_data          zipapp
_tkinter            email               pyexpat             zipfile
_tracemalloc        encodings           pygtkcompat         zipimport
_uuid               entrypoints         pyinotify           zlib 
Enter any module name to get more help.  Or, type "modules spam" to search
for modules whose name or summary contain the string "spam".
 
help> keywords
 
Here is a list of the Python keywords.  Enter any keyword to get more help.
 
False               class               from                or
None                continue            global              pass
True                def                 if                  raise
and                 del                 import              return
as                  elif                in                  try
assert              else                is                  while
async               except              lambda              with
await               finally             nonlocal            yield
break               for                 not                 
 
help> symbols
 
Here is a list of the punctuation symbols which Python assigns special meaning
to. Enter any symbol to get more help.
  
© www.minhinc.com
p9
!=                  +                   <=                  __
"                   +=                  <>                  `
"""                 ,                   ==                  b"
%                   -                   >                   b'
%=                  -=                  >=                  f"
&                   .                   >>                  f'
&=                  ...                 >>=                 j
'                   /                   @                   r"
'''                 //                  J                   r'
(                   //=                 [                   u"
)                   /=                  \                   u'
*                   :                   ]                   |
**                  <                   ^                   |=
**=                 <<                  ^=                  ~
*=                  <<=                 _                   
 
help> topics
 
Here is a list of available topics.  Enter any topic name to get more help. 
ASSERTION           DELETION            LOOPING             SHIFTING
ASSIGNMENT          DICTIONARIES        MAPPINGMETHODS      SLICINGS
ATTRIBUTEMETHODS    DICTIONARYLITERALS  MAPPINGS            SPECIALATTRIBUTES
ATTRIBUTES          DYNAMICFEATURES     METHODS             SPECIALIDENTIFIERS
AUGMENTEDASSIGNMENT ELLIPSIS            MODULES             SPECIALMETHODS
BASICMETHODS        EXCEPTIONS          NAMESPACES          STRINGMETHODS
BINARY              EXECUTION           NONE                STRINGS
BITWISE             EXPRESSIONS         NUMBERMETHODS       SUBSCRIPTS
BOOLEAN             FLOAT               NUMBERS             TRACEBACKS
CALLABLEMETHODS     FORMATTING          OBJECTS             TRUTHVALUE
CALLS               FRAMEOBJECTS        OPERATORS           TUPLELITERALS
CLASSES             FRAMES              PACKAGES            TUPLES
CODEOBJECTS         FUNCTIONS           POWER               TYPEOBJECTS
COMPARISON          IDENTIFIERS         PRECEDENCE          TYPES
COMPLEX             IMPORTING           PRIVATENAMES        UNARY
CONDITIONAL         INTEGER             RETURNING           UNICODE
CONTEXTMANAGERS     LISTLITERALS        SCOPING             
CONVERSIONS         LISTS               SEQUENCEMETHODS     
DEBUGGING           LITERALS            SEQUENCES            
  
Day 1 Morning
  1. Basic structure of Python program
 namespace
Python runs only main script/module. All modules initialized recursively is based on modules imported in main script. One module gets initialized/loaded only once. Everything in python is object which leads to formation of namespace/dictionary. each name/variable defined, belongs to a certain namespace. it can be module, class or function namespace. 
from tkinter import Widget
i=10
j=10
class A:
 ca=20
 def func(arg1):
  global i;
  la=j
  def func1(arg2):
   nonlocal la
   print('nested function,globals -> {} locals -> {}'.format(globals(),locals()))
  func1(40)
  print('globals -> {} locals -> {}'.format(globals(),locals())) 
>>> A.func(20)  <--- func is name in A namespace
nested function,globals -> {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'Widget': <class 'tkinter.Widget'>, 'i': 10, 'j': 10, 'A': <class '__main__.A'>} locals -> {'arg2': 40, 'la': 10}
globals -> {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'Widget': <class 'tkinter.Widget'>, 'i': 10, 'j': 10, 'A': <class '__main__.A'>} locals -> {'arg1': 20, 'func1': <function A.func.<locals>.func1 at 0x7f114d5cb3a0>, 'la': 10}
>>> A.__dict__  <---- ca,func is name in A namespace
mappingproxy({'__module__': '__main__', 'ca': 20, 'func': <function A.func at 0x7f114cdeca60>, '__dict__': , '__weakref__': , '__doc__': None})
 
>>> A.func.__dict__  <--- A.func namespace is empty
{}
>>> globals()   <--- Widget,i,j,A names in global namespace 
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'Widget': <class 'tkinter.Widget'>, 'i': 10, 'j': 10, 'A': <class '__main__.A'>}
 
>>> globals()['A'].__dict__  # <---- A is name in global namespace 
mappingproxy({'__module__': '__main__', 'ca': 20, 'func': <function A.func at 0x7f114cdeca60>, '__dict__': , '__weakref__': , '__doc__': None}) 
© www.minhinc.com
p10
 
 
module namespace is also known as global namespace. global variable and imported modules are names in global/module namespace. 
 
 scope
 a variable/name is defined and bind to a namespace where as non bound variables which are non explictly scoped are indentified in a block or scope. a variable that is not bind to a namesapce is searched in a local block (if it is not explicitly namescoped by global,nonlocal) if not found then it is searched in global namespace and then in builtins namespace. 
i=10
j=20
class A:
 c=10
 def func():
  global j #<-- explictly global namespace binding is mentioned
  x=10 
  print(x,i,j,A.c) #<--- A.c is class namespace scoped 
        ^ ^ ^ ^
        | | | |
        | | | +----- c is expicitly  declared bound to class A namespace
        | | +---- j is explicitly delclared bound to global namespace
        | +----- 'free variable' as not found in local block/scope
        +----- x found in local block 
 if a name not found at all then 'NameError' is raises. if a variable is assigned in a scope inside a local scope of a function namespace and variable accessed in local scoped when variable couldnot be defined in scope inside local scope of function then UnboundLocalError (subclass of NameError) is raised. 
minhinc@minhinc:~/tmp/MISC/ffmpeg$ python3
Python 3.8.5 (default, May 27 2021, 13:30:53) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def func():
...  return i
... 
>>> func()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in func
NameError: name 'i' is not defined
>>> def func(j):
...  if j:
...   i=10
...  return i
... 
>>> func(0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in func
UnboundLocalError: local variable 'i' referenced before assignment 
 
'x' and 'i' name in function block/scope 'func()' is searched in local function scope as name binding is not specified. 'j' and A.c are namescoped so they would not be searched in function local scope. names not explicitly namescoped and not found in local block is declared 'free variables'. here 'i' is free name. if name is not found in local block it is then searched in global scope (not in class scope) and then in builtin module namespace.
 
<h>
*Python Identifiers
</h>
Identifiers are variables names, it can be class name, function name or any other variable names. It is generally in ASCII range (U+0001..U+007F). Identifiers can include uppercase lowercase letters, decimal numbers and underscrores. 
 
      +--------- class identifier
      |
      v
class A:
 pass
a=A()
^
|
+---- instance object identifier 
 
Following keywords can not be used as identifiers 
   False      await      else       import     pass
   None       break      except     in         raise
   True       class      finally    is         return
   and        continue   for        lambda     try
   as         def        from       nonlocal   while
   assert     del        global     not        with
   async      elif       if         or         yield 
© www.minhinc.com
p11
 
Following letter(s) have special meanings
  "_*" 
 "_" stores the previous arithmetic calculation results when script runs in interactive mode. "_" is available in builtins module. If not in interactive mode this identifier has no special meaning. There are chances when script runs both in scripting mode and interactive mode together,i.e. debugging the script 'python3 -i <scriptname>') 
minhinc@minhinc:~/tmp$ python3
Python 3.8.5 (default, May 27 2021, 13:30:53) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> i=10;j=20
>>> i*j
200
>>> 100+_
300 
  "__*__"
 System-defined names and also known by 'dunder' names. These names should be avoided and if used then should be proper documented. 
minhinc@minhinc:~/tmp$ python3
Python 3.8.5 (default, May 27 2021, 13:30:53) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__'] 
 
  "__*"
 class private names. Compiler modifies the identifiers by prepending '_<classname>' tag. 
class A:
 __ca_=10
 def __init__(self):
  self.__ma_=20
  self.__ca_=40 
>>> A._A__ca_
10
>>> a=A()
>>> a._A__ca_
40
>>> a._A__ma_
20 
 
See also 
public private attributes
Day 1 Morning
  1. Basic structure of Python program
Line indentation in python is mandatory. Every statement code block must be atleast one space right to its expression.
  
def func(number):
 for i in range(number):
  if i%2 == 0:
   print('i is even')
  else:
   print('i is odd') 
  
Day 1 Morning
  1. Basic structure of Python program
  
© www.minhinc.com
p12
Day 1 Morning
  1. Basic structure of Python program
comment in python starts from letter '#'. any thing following '#' is comment when '#' does not appear in any string. 
class A: # A is subclass of object and of type 'type'
 # def __init__ is class function with 'self' as 
# first argument when called as method
 def __init__(self):
  self.ma #ma is an attribute 
triple single quote and double quote can also be used as comment 
'''
class widget subclass QWidget and creates
a window. qapplication needs to get
instantiated first
'''
class widget(QWidget):
 def __init__(self):
  self.__init__()
''' 
  
Day 1 Morning
  1. Basic structure of Python program
© www.minhinc.com
p13