Python – Teknonauts https://teknonauts.com Stay Tuned With Technology Thu, 15 Jul 2021 09:01:58 +0000 en-US hourly 1 https://wordpress.org/?v=5.7.5 https://teknonauts.com/wp-content/uploads/2021/01/cropped-teknonauts_favicon_original-1.png Python – Teknonauts https://teknonauts.com 32 32 #30 Python Programming – Modules, Package and Object-Oriented Programming https://teknonauts.com/python-programming-06/ https://teknonauts.com/python-programming-06/#respond Wed, 14 Jul 2021 08:32:47 +0000 https://teknonauts.com/?p=4298

Python modules

  • Module is a python file which contains python data members i.e., statements and definitions.
  • A file containing Python code, for e.g.: fax.py, is called a module and its module name would be fax.
  • Like functions, modules help us to break down large python programs into small manageable and organized files. Furthermore, modules provide reusability of code.

How to create a module?

  • Module is a python script file, let us create one function definition below fax module
File : fax.py
def  calc(a1,a2):  # function calc will receive two arguments
          total=a1+a2
          print  “Sum of total value:”,total

Note : In the above code, there is no function call. It contains only definition.

How to import modules in Python?

 We can import the definitions present inside a module to another module or the interactive interpreter in Python.

  • We use the import keyword to do this. 
  • To import our previously defined module fax, we type the following in the Python prompt.

>>> import fax

· Using the module name we can access the function using dot (.) operation. for example:

>>> fax.calc(10,20)

30

>>>fax.calc(1.45,3.56)

5.01

· Within a module, the module’s name is available as the value of the global variable __name__. 

>>>fax.__name__

‘fax’

Advantage of modules

  • Code reusability
  • We may want to split single script (or) definition into multiple file for easier maintenance  
  • We can import a module on demand.
  • Each module has its own private symbol table, which is used as the global symbol table by all functions defined in the module.
  • Modules can import other modules
  • Open the below link will get list of python standard modules https://docs.python.org/3/py-modindex.html 
  • These files are in the Lib directory inside the location where you installed Python.
  • Standard modules can be imported the same way as we import our user-defined modules.
  •  There are various ways to import modules.

Python import statement

We can import a module using import statement and can access the definitions inside it using the dot operator as described above.

Here is an example.

# import statement example

# to import standard module math

import math

print(“The value of pi is”, math.pi)

When you run the program, the output will be:

The value of pi is 3.141592653589793

Import with renaming

  • We can import a module by renaming it as follows.
  • # import module by renaming it
  • import math as m     # alias (or) symbolic name
  • print(“The value of pi is”, m.pi)
  • We have renamed the math module as m
  • This can save us typing time in some cases.
  • Note that the name math is now not recognized in our scope.
  • Hence, math.pi is invalid, m.pi is the correct implementation.

Python from…import statement

  • We can import specific names from a module without importing the module as a whole. Here is an example.

# import only pi from math module

from math import pi

print(“The value of pi is”, pi)

  • We have imported only the attribute pi from the module.
  • In such case we don’t use the dot operator.
  • We can also import multiple attributes as follows.
>>> from math import pi, e
>>> pi
3.141592653589793
>>> e
2.718281828459045

Import all names

  •  We can import all names (definitions) from a module using the following construct.
  • # import all names from the standard module math
from math import *
print("The value of pi is", pi)
  • Now we have imported all the definitions from the math module.
  • This makes all names except those beginning with an underscore, visible in our scope.
  • However, Importing everything with the asterisk (*) symbol is not a good programming practice.
  • This can lead to duplicate definitions for an identifier. It also hampers the readability of our code.

Python Module Search Path

  • While importing a module, Python looks at several places.
  • Interpreter first looks for a built-in module then (if not found) into a list of directories defined in sys.path.
  • The search is performed in this order.
    •  The current directory.
    • PYTHONPATH (an environment variable with a list of directory).
    • The installation-dependent default directory.

What is sys.path ?

C:\Users\python>python
Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:42:59) [MSC v.1500 32 bit (
Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', 'C:\\Python27\\Lib', 'C:\\Python27\\DLLs', 'C:\\Python27\\Lib\\lib-tk',
'C:\\Users\\python', 'C:\\Windows\\system32\\python27.zip',
 'C:\\Python27\\lib\\plat-win', 'C:\\Python27', 'C:\\Python27\\lib\\site-packages']
>>>
>>>

Module path list in linux os

Example :

root@awadheshpdwivedi]#  pwd

/root/python/modules/example

Creating one module file name called report.py

File : report.py

import os
def  display() :
         print “Current vmreport status :-“
        os.system(“vmstat”)
        print “Current CPU Load balance:-“
        os.system(“uptime”)

Importing report.py file into an external file

File : p1.py

import  report

report.display()

root@awadheshpdwivedi]#  ls

p1.py  report.py

root@awadheshpdwivedi]# python p1.py

#  display vmstat and uptime command result to the screen

  •  After completing the execution, again type ls command from linux command line (or) dir command in windows operating system.

root@awadheshpdwivedi]#  ls

p1.py  report.py report.pyc

· The report.pyc file contain a ready-“byte-compiled” version of the module report.

· Test the file type in linux command line

root@awadheshpdwivedi]#  file  report.pyc   

# file is a linux command – it’s determine file type

report.pyc :python 2.7 byte-compiled

· Normally, you don’t need to do anything to create the report.pyc file.

· Whenever report.py is successfully compiled, an attempt is made to write the compiled version to report.pyc.

· Now let us create one sub directory under your current working directory.

root@awadheshpdwivedi]#  mkdir L1

root@awadheshpdwivedi]# ls

L1  p1.py report.py report.pyc

· Now let us move the report.py file into L1 sub directory

root@awadheshpdwivedi]# mv report.py L1

root@awadheshpdwivedi]# ls

L1 p1.py  report.pyc

· Now there is no report.py file , but report.pyc file is available in current working directory. So script (p1.py ) will execute as follows.

root@awadheshpdwivedi]# python p1.py

# Display system commands

# Execution done successfully

 #Deleting report.pyc file from current working directory

root@awadheshpdwivedi]# rm report.pyc

L1 p1.py

· Now there is no report.py and report.pyc files in my current working directory.

· If you run the p1.py file now, we will get an error message.

· We can’t always keep module file and script files in same directory.

· But sometimes we load external modules or in built module such as os or sys.The os.py or sys.py  files are not in our current working directory.

. If we import os module in to script , the file loads successfully. Let’s see them in detail.

Example :

root@awadheshpdwivedi]# ls

L1 p1.py  

· Now let us create one more file name called p2.py

File :p2.py

import os

os.system(“uptime”)

· Before executing this file (p2.py) ,list out all the available files.

root@awadheshpdwivedi]# ls

L1 p1.py  p2.py

· Note down there is no os.py or os.pyc file in our current working directory. But if we run the program p2.py  it will execute successfully, there is no import or attribute errors

root@awadheshpdwivedi]#  python p2.py

# Execute successfully

# display uptime command result to #screen.

  • The reason behind is that, whenever we are interpreting python file, interpreter searches the module file from sys.path variable .
  • The sys.path is list type of variable.
  • This is equivalent to $PATH in shell command line ,@INC in perl script , $LOAD_PATH in ruby.

root@awadheshpdwivedi]# python

import sys

sys.path

  • Look at the result which is list type of data structure. So we can use all list functions and list manipulation.
  • The sys.path variable contains the current directory (. ) , installed python path.
  • We can use append or insert functions to insert our external module file into sys.path.

Example

File : p3.py

import  sys

sys.path.append(“/root/python/modules/L1”)

import report

report.display()

root@krosumlabs day1]#  ls

L1  p1.py p2.py p3.py

# note there is no report.py file

  • We added (appended) L1 directory ( which contains module files) into sys.path variable ,so now python interpreter look at (“/root/python/modules/day1/L1) where report.py file is present. So it will load successfully.
  • If you want to make permanent update use PYTHONPATH variable.

What is PYTHONPATH ?

  • The PYTHONPATH is an environment variable, consisting of a list of directories.
  • The syntax of PYTHONPATH is the same as that of the shell variable PATH.
  • Here is a typical PYTHONPATH from a Windows system ?

set PYTHONPATH = c:\python20\lib;

· In linux operating system

open a  login profile file (.profile or .bash_rc )

export PYTHONPATH=”/root/python/modules/day1/L1”

Now open new shell , test the belowscript

File :p4.py

import report

report.display()

  • Run the p4.py file , the script will execute successfully.
  • Compare p3.py and p4.py file, understand the sys.path and PYTHONPATH variable usages.

Reloading a module

  • The Python interpreter imports a module only once during a session.
  • This makes things more efficient.
  • Suppose we have the following code in a module named my_module.
# This module shows the effect of
#  multiple imports and reload
  print("This code got executed")

Now we see the effect of multiple imports.

>>> import my_module
This code got executed
>>> import my_module
>>> import my_module
  • We can see that our code got executed only once. This goes to say that our module was imported only once.
  • Now if our module changed during the course of the program, we would have to reload it.
  • One way to do this is to restart the interpreter. But this does not help much.
  • Python provides a neat way of doing this. We can use the reload() function inside the imp module to reload a module. This is how its done.
>>> import imp
>>> import my_module
This code got executed
>>> import my_module
>>> imp.reload(my_module)
This code got executed

dir() built-in function

  • We can use the dir() function to find out names that are defined inside a module.
  • For example, we have defined a function add() in the module example that we had in the beginning.
>>> dir(example)
['__builtins__',
'__cached__',
'__doc__',
'__file__',
'__initializing__',
'__loader__',
'__name__',
'__package__',
'add']
  • Here, we can see a sorted list of names (along with add).
  • All other names that begin with an underscore are default Python attributes associated with the module (we did not define them our self).
  • For example, the_name_attribute contains the name of the module.
>>> import example
>>> example.__name__
'example'
  • All the names defined in our current namespace can be found out using the dir() function without any arguments.
>>> a = 1
>>> b = "hello"
>>> import math
>>> dir()
['__builtins__', '__doc__', '__name__', 'a', 'b', 'math', 'pyscripter']

Python Package

  • Python package is a hierarchical file directory structure.
  • We don’t usually store all of our files in our computer in the same location.
  • We use a well-organized hierarchy of directories for easier access.
  • Similar files are kept in the same directory, for example, we may keep all the songs in the “music” directory.
  • Analogous to this, Python has packages for directories and modules for files.
  • As our application program grows larger in size with a lot of modules, we place similar modules in one package and different modules in different packages.
  • This makes a project (program) easy to manage and conceptually clear.
  • Similar, as a directory can contain sub-directories and files, a Python package can have sub-packages and modules.
  • A directory must contain a file named init.py in order for Python to consider it as a package.
  • This file can be left empty but we generally place the initialization code for that package in this file.

Package structure

  • Create a directory Demo and under the Demo directory let us create a package structure that holds the below format.
root@awadhesh ~]#mkdir  Demo
root@awadhesh  ~] # cd Demo
root@awadhesh  Demo]#mkdir   Fax
  • Under Fax directory there are three python scripts such as p1.py ,p2.py and p3.py.
  • Each file contains several functions. Instead of loading these individual files and functions, we are creating Fax as a package which will initialize all the functions under init.py file.
  • We can import modules from a package using the dot (.) operator. To import particular names from a module directory , use following syntax :-
from module import functions

from module import functions

Go to Fax directory

root@awadhesh Demo]#   cd   Fax
 
· Create an initialization file __init__.py.
root@awadhesh  Fax]#  vi __init__.py
from p1.py import f1,f2,f3
from p2.py import calc,bc
from p3.py import view,report,result
# save and exit
  • Now move to the parent directory Demo and create one new python script file,say demo_package.py and import the package Fax inside it.
root@awadhesh Demo]#   vi  demo_package.py
import  Fax  #  Now Fax is a package which encapsulates a collection of modules and methods
Fax.f1()  # to invoke f1() method
Fax.calc()   # to invoke calc() method
  • While importing packages, Python looks in to the list of directories defined in sys.path, similar to module search path.

Object Oriented Programming in Python

  • Python is an object oriented programming language.
  • It is a way of organizing the program, which is to combine the data and functionality and wrap them inside something called an object.
  • Classes and objects are the two main aspects of object oriented programming.
  • The class becomes a new type where objects are their instances.
  • The class defines a data type, which contains variables, properties and methods.
  • A class describes the abstract characteristics of a real-life thing.
  • Object is simply a collection of data (variables) and methods (functions) that act on those data whereas class is a blueprint for the object.

Defining a Class in Python

  • In Python, we define a class using the keyword class.
  • Class which contains collection of variables and methods preferably called as data members.
  • A class creates a new local namespace where all its data members are defined.
>>> class Box:
...            pass
>>> Box
>>> type(Box)
<__main__.Box instance at 0x0247D440>

Creating an Object in Python

  • A class is used to create new object instances (instantiation).
  • These class objects allow us to access the different attributes of the class.
  • The procedure to create an object looks very similar to a function call.

Syntax:-

Example :-

>>> class Box:
...        name="Krosum"
>>> obj=Box()
>>> type(obj)
>>> obj.name
'Krosum'
obj.name is interpreted as Box.name
 >>> class Box:
...         name="Krosum"
...         code=34
...         ips=['10.20.30.40','10.20.30.50']
...         books={'subject1':'programming python','subject2':'Python Essentials'}
 

>>> obj=Box()
>>> type(obj.name)
>>> type(obj.code)
>>> type(obj.ips)
>>> type(obj.books)
>>> print "Hello",obj.name
Hello Krosum
>>> print "Total no.of IPs",len(obj.ips)
Total no.of IPs 2
>>> # adding new items to the existing list
>>> obj.ips.append("127.0.0.1")
>>> # List of updated IPs
>>> print obj.ips
['10.20.30.40', '10.20.30.50', '127.0.0.1']
>>> #accessing dictionary values
>>> print obj.books['subject1']
Programming python
>>> # modifying existing dictionary value
>>> obj.books['subject1']="PYTHON PROGRAMMING GUIDE"
>>> # adding new subject to the existing dictionary
>>> obj.books['subject3']="Network Python Program"
>>> # List of all the keys(subjects) from dictionary (books)
>>> obj.books.keys()
['subject1', 'subject2', 'subject3']
# List of all the values (subjects) from dictionary (books)
>>> obj.books.values()
['PYTHON PROGRAMMING GUIDE', 'Python Essentials', 'Network Python Program']

From the above examples, we have accessed the class data members through the class instance (object).

We can create more than one object from a single class.

Each such object contains an individual reference (memory).

>>> class Box:
...        name=""
...        fname=""
 
>>> obj1=Box()    # object1 is created
>>> obj2=Box()    # object2 is created
>>> obj3=Box()    # object3 is created
>>> obj1.name="User A"
>>> obj1.fname="/etc/passwd"
>>> obj2.name="User B"
>>> obj2.fname="/var/log/auth.log"
>>> obj3.name="User C"
>>> obj3.fname="/home/userC/temp.txt"
>>> print "User Name:",obj1.name,"\tFile name:",obj1.fname
User Name: User A       File name: /etc/passwd
>>> print "User Name:",obj2.name,"\tFile name:",obj2.fname
User Name: User B       File name: /var/log/auth.log
>>> print "User Name:",obj3.name,"\tFile name:",obj3.fname
User Name: User C       File name: /home/userC/temp.txt
Now let us see how to access class function (methods) using class instance.
>>> class Box:
...        name="Krosum"
...        DBs=['oracle','sql','mysql']
 

...     def    hello():
...             print "Im hello function from Box class"
>>>
>>> obj=Box()
>>> obj.name
'Krosum'
>>> obj.DBs
['oracle', 'sql', 'mysql']
>>> obj.DBs[-1]
'mysql'
>>> obj.hello()
Traceback (most recent call last):
  File "", line 1, in
TypeError: hello() takes no arguments (1 given)
>>>
Here, we didn’t pass any argument but it displays ‘ TypeError: hello () takes no arguments (1 given)’
Whenever an object calls its method, the object itself is passed as the first argument, i.e) the form object.method() is internally translated into ClassName.method(object).
>>> obj.hello()    #  Box.hello(obj)   # like function call with single argument
In general, calling a method with a list of n arguments is equivalent to calling the corresponding function with an argument list with method's object as its first argument.
For these reasons, the first argument of the function inside class (method definition) must be the object itself.
This is conventionally called self.
 
>>> class Box:
...     def hello(self):
...             print "Im hello method from Box class"
>>> obj=Box()
>>> obj.hello()
Im hello function from Box class
Note that an the argument (self) is passed in the method definition inside the class but still, we called the method simply as object.hello() without any arguments.
Here, obj.hello()  is interpreted as  hello(obj)
>>> class Box:
...            def hello(self):
...                   print "Im hello function",self
>>>
>>> obj=Box()
>>> obj.hello()
Im hello function <__main__.Box instance at 0x023DD620>
>>> obj
<__main__.Box instance at 0x023DD620>
Note the above result. Both self and obj refers to same location.
So self is just an object placeholder.
obj.name is same as  self.name
>>> class Box:
...           name="Vikas"
...           def hello(self):
...                     print "From hello function",self.name
>>>
>>> obj=Box()     # creating object
>>> obj.hello()  # object.method(  )
From hello function Vikas
We have already discussed that the class variables can be accessed only through class name or class instance.
>>> class Box:
...             name="Krosum"
...             def hello(self):
...                       print "Hello function",name  # Display Name Error
>>> obj=Box()
>>> obj.hello()
Hello function
Traceback (most recent call last):
  File "", line 1, in
  File "", line 4, in hello
NameError: global name 'name' is not defined
 
Here the class variable name has to be accessed as self.name
Variables in python are generally classified as Class variables, Instance variables and Private variables.
 
Class variables 
Class variables are defined only within a class definition.
We can access and use a class variable directly inside the class.
Example:
>>> class Box:
...        username="Krosum"    
...        Filename="/etc/passwd"
...     print "From Box Class username:",username
...     print "From Box Class Filename:",Filename
From Box Class username: Krosum
From Box Class Filename: /etc/passwd
From the above example username and Filename are class variables which are placed inside a class directly.
We can access class variables from outside the class definition, using class name or class instance (object)
 
Example :
>>> class Box:
...        username="Krosum"    
...        Filename="/etc/passwd"
>>> obj=Box()
>>> print “username:”,obj.username
Krosum
>>> print “Filename:”,obj.Filename
/etc/passwd
>>> print “username:”,Box.username
Krosum
>>>print “Filename:”,Box.Filename
/etc/passwd

Instance variable

  • Instance variables are the variables placed inside the class member function.
  • We can use instance variable only within the class member function.
  • We can’t use instance variable either out of the class or out of the class member functions.

Examples

class Box:
     book="Core Python Programming" # class variable
     def getdata(self,author,price,vol):   
             print "Book name:",self.book
             print "Author name:",author
             print "Price:",price
             print "Volume:",vol
#  author , price, vol are instance variables
# we can’t use instance variables outside the class function
 
 obj=Box()
 obj.getdata ("Mr.Guido van rossum",467.67,1.0)
 
Book name: Core Python Programming
Author name: Mr.Guido van rossum
Price: 467.67
Volume: 1.0
 
=> We can initialize instance variable to class variable
class Box:
        name="Mr.Krosum" # class varaible
        price=""     # class variable
        volume=""   # class variable
        def getdata(self,p,v):
                self.price=p    # instance --> class variable
                self.volume=v  # instance --> class variable
       def display(self):
             print "User name:",self.name # class variable
             print "Price name:",self.price # class variable
             print "Voulme:",self.volume # class variable
 

obj=Box()
obj.getdata(1000.34,1.0)
obj.display()
# Run the above script in command line
C:\Users\KrosumLabs>python p1.py
User name: Mr.Krosum
Price name: 1000.34
Volume: 1.0

Private variable

Class variable that begins with double underscore (__) are called special variable as they have special meaning

>>> class Emp:
...     name="Mr.Xerox"
...     __password="abc"       #  private variable  can’t be accessed from    outside the class
...     def display(self):
...             print self.name
...             print self.__password
 
>>> obj=Emp()
>>> obj.display()
Mr.Xerox
abc
>>> obj.name
'Mr.Xerox'
>>> obj.__password
Traceback (most recent call last):
  File "", line 1, in
AttributeError: Emp instance has no attribute '__password'

Constructors in Python

  • A class functions that begins with double underscore (__) are called special functions as they have special meaning.
  • Of one particular interest is the __init__()function. This special function gets called whenever a new object of that class is instantiated.
  • This type of function is also called constructors in Object Oriented Programming (OOP). We normally use it to initialize all the variables.
Example  1:-
>>> class Box:
                    def display(self):
                    print "Im display function"
 
>>> obj=Box()
>>> obj.display() # object.method() call
Im display function
 
Example 2:-
>>> class Box:
                  def __init__(self):
                          print   "Im Initialization function block"
>>> obj=Box()
Im Initialization function block  ## didn't used object.method(), __init__() automatically initialized
 

Example 3:-
>>> class Emp:
                name=" "
                dept=" "
                def   __init__(self):   # automatically initialized constructor block
                          self.name="Mr.John Paul"
                         self.dept="Sales"
                def   display(self):    # non  constructor block
                           print  "Emp Details:"
                          print "Name:",self.name
                          print "Dept:",self.dept
 
>>> obj=Emp()   # object  is initialized
>>> obj.display()   # object.method() call
Emp Details:
Name: Mr.John Paul
Dept: Sales

Destructors in Python

  • Destructors are called when an object gets destroyed.
  • The destructor is defined using __del__(self).
  • __del__(self)  method is only called on destruction of the object.
>>> class Box:
                 def __init__(self):
                        print "Im Constructor" 
                def __del__(self):
                        print   "Im Destructor"
>>> obj=Box()
Im Constructor 
>>> del(obj)
  Im Destructor
  • In the example, the obj is created and manually deleted; therefore, both messages will be displayed.
  • However, if you comment out the last line  del (obj), the destructor will not be called immediately.
  • Instead, the Garbage Collector (GC) will take care of the deletion automatically.

Python Inheritance

What is inheritance?

  • Inheritance is one of the OOPs feature.
  • The Reusability of existing class means that it refers to the concept of defining a new class with little or no modification to an existing class.
  • The new class is called child class or derived class.
  • Existing class is called parent class or base class.

Python Inheritance Syntax

class BaseClass :

           Body of base class
class DerivedClass ( BaseClass ):

          Body of derived class
  • Derived class inherits features from the base class, adding new features to it.
  • This results into re-usability of code.

Example :

import  os
class  Parent:
          def   display(self):
                   print    “Display mounted file system details :”
                   os.system(“df –Th”)
class Child(Parent) :   # Inheritance – Extending Parent class data members
          def  view(self):
                   print  “Current process details :-“
                   os.system(“ps –f”)
obj=Child()
obj.view()
obj.display()  # using child class object, calling parent data member
 
Example :
class  Parent :
def   display(self):
                    print “This is display block from Parent class”
 
class Child(Parent):
          def   display(self):
                   print “This is display block from Child class”
 
obj=Child()
obj.display()  #  This is display block from Child class

Method Overriding in Python

  • In the above example, notice that display( )method was defined in both classes, Parent as well Child.
  • When this happens, the method in the derived class overrides that in the base class.
  • Generally when overriding a base method, we tend to extend the definition.
  • The same is being done by calling the method in base class from the one in derived class.
class Parent():
          def display(self):
                      print “This is display block from Parent class”
class Child(P):
          def display(self):
                     print “This is display block from Child class”
                   Parent.display (self)   # calling Parent class display method
obj=Child()
obj.display() 

Python Multiple Inheritance

  • A class can be derived from more than one base classes, this is called multiple inheritance
  • In multiple inheritances, the features of all the base classes are inherited into the derived class.

Syntax

class Parent1:
           pass
class Parent2:
          pass
class Child(Parent1, Parent2):
           pass
  • The class Child inherits from both Parent1 and Parent2.

Multilevel Inheritance in Python

  • We can also inherit the features from a derived class. This is called multilevel inheritance. It can be of any depth in Python.
  • In multilevel inheritance, features of the base class and the derived class are inherited into the new derived class.

Syntax

class Parent1:
          pass
class Parent2(Parent1):
          pass
class Child(Parent2):
          pass

Here, Parent2 is derived from Parent1, and Child is derived from Parent2.

Using super() method  

class GrandParent(object):                                                      
         def act(self):                                                              
              print 'grandpa act'                                                     
class Parent(GrandParent):                                                      
         def act(self):                                                              
              print 'parent act'                                                      
class Child(Parent):                                                            
        def act(self):                                                              
              super (Child.__bases__[0], self) . act()                                   
              print 'child act'                                                       
 
instance = Child()                                                              
instance.act()

Built-In Class Attributes

  • Every Python class keeps the following built-in attributes and  they can be accessed using dot operator like any other attribute.
  •  __dict__         Dictionary containing the class’s namespace.
  •  __doc__         Class documentation string or none, if undefined.
  • __name__      Class name.
  • __module__   Module name in which the class is defined. ( This attribute is “__main__” in interactive mode.)
  • __bases__     A possibly empty tuple containing the base classes,in the order of their occurrence in the base class list.

Example 1 :

>>> class Box:
...     ' sample class document, this is Box class'
>>> Box.__doc__
' sample class document, this is Box class'
 
>>> Box.__dict__
{'__module__': '__main__', '__doc__': ' sample class document, this is Box class'}

Example 2 :

>>> class Box:
...     ' sample document message from Box class'
...     count=10
...     LIST=['data1','data2']
...
>>> Box.__doc__
' sample document message from Box class'
>>>
>>> Box.__dict__
{'count': 10, '__module__': '__main__', 'LIST': ['data1', 'data2'], '__doc__': '
 sample document message from Box class'}
>>> Box.__name__
'Box'
>>>
>>> Box.__module__
'__main__'
>>> Box.__bases__
()
>>>

 

Example 3:

>>> class Parent:
... pass
>>> class Child1(Parent):
... pass
>>> class Child2(Child1):
... pass
>>> obj=Child2()
>>>
>>> Child2.__bases__
>>> Child1.__bases__
>>> Parent.__bases__
()

Example 4:

File : Fax.py

class C1:
          def f1(self):
                   print "f1 func"
Import Fax.py file into external python file ( p2.py )
File: p2.py
import Fax
obj=Fax.C1()
obj.f1()
print Fax.C1.__name__  
print Fax.C1.__module__
Run the above (p2.py) file in command line.
C:\Users\awadheshpdwivedi>python   p2.py
f1 func
C1
Fax

Example 5:

  • __name__ is a variable automatically set in an executing python program.
>>> print __name__
__main__
>>>
  • If you import your module from another program, __name__ will be set to the name of the module.
  • If you run your program directly, __name__ will be set to __main__.
if __name__ == "__main__name___" :
  # will run only if module directly runs
             print  "I am being run directly"
else:
  # will run only if module imported
             print  "I am being imported" 

Python Iterators

  • Iterator in Python is simply an object that can be iterated upon.
  • An object which will return data, one element at a time.
  • Python iterator object must implement two special methods,

      __iter__()and __next__(), collectively called the iterator protocol.

  • An object is called iterable if we can get an iterator from it.

Most of built-in containers in Python like: list, tuple, string etc. are iterables.

  • The iter() function (which in turn calls the __iter__() method) returns an iterator from them.
>>> dbs=['oracle','sql','db2','server2000']
>>> obj=iter(dbs)
>>> obj    
>>> for v in obj:
               v
'oracle'
'sql'
'db2'
'server2000'
=>   We use the next() function to manually iterate through all the items of an iterator.
=>   When we reach the end and there is no more data to be returned,
       it will raise StopIteration
 
>>> dbs=['oracle','sql','db2','server2000']
>>> obj=iter(dbs)
>>> next(obj)
'oracle'
>>> next(obj)
'sql'
>>> next(obj)
'db2'
>>> next(obj)
'server2000'
>>> next(obj)
Traceback (most recent call last):
  File "", line 1, in
StopIteration 

Python Generator

  • A generator is a function that returns an object (iterator) which we can iterate over (one value at a time).

How to create a generator in Python?

  • It is as easy as defining a normal function with yield statement instead of a return statement.
  • If a function contains at least one yield statement (it may contain other yield or returnstatements),it becomes a generator function.
  • Both yield and return will return some value from a function.
  • The difference is that, while a return statement terminates a function entirely, yield statement pauses the function saving all its states and later continues from there on successive calls.

Differences between Generator function and a Normal function

  • Here is how a generator function differs from a normal function.
  • Generator function contains one or more yield statement.
  • When called, it returns an object (iterator) but does not start execution immediately.
  • Methods like __iter__() and __next__() are implemented automatically.

So we can iterate through the items using next().

  • Once the function yields, the function is paused and the control is transferred to the caller.
  • Local variables and their states are remembered between successive calls.
  • Finally, when the function terminates, StopIteration is raised automatically on further calls.

Example

>>> def   f1():
...          n=1
...          yield n
...          n+=1
...          print "2nd n"
...          yield n
>>>      f1()
 
>>> r1=f1()
>>> r1
>>>
>>> next(r1)
1
>>> next(r1)
2nd n
2
>>> next(r1)

Traceback (most recent call last):
  File "", line 1, in
StopIteration
  • Unlike normal functions, the local variables are not destroyed when the function yields.
  • Furthermore, the generator object can be iterated only once.

Python Generators with a Loop

  • Normally, generator functions are implemented with a loop having a suitable terminating condition.
  • Let’s take an example of a generator that reverses a string.
def    rev_str(my_str):
           length = len(my_str)
           for i in range(length - 1,-1,-1):
                      yield  my_str[i]
 
         for char in rev_str("hello"):
                         print(char)

# For loop to reverse the string

# Output:

# o

# l

# l

# e

# h

Why generators in Python?

There are several reasons which make generators an attractive implementation to go for.

1.  Easy to Implement

  •  Generators can be implemented in a clear and concise way as compared to their iterator class counterpart.
  • Following is an example to implement a sequence of power of 2’s using iterator class.
class   PowTwo:
    def    __init__ self, max = 0 :
             self.max = max
 
    def     __iter__(self):
             self.n = 0
            return self
 
    def   __next__(self):
          if   self.n > self.max:
                 raise StopIteration
 
        result = 2 ** self.n
        self.n += 1
        return result
  • This was lengthy. Now let’s do the same using a generator function.
def    PowTwoGen(max = 0):
         n = 0
        while n < max>
               yield 2 ** n
               n += 1
  • Since, generators keep track of details automatically; it was concise and much cleaner in implementation.

2.  Memory Efficient

  • A normal function to return a sequence will create the entire sequence in memory before returning the result. This is overkill if the number of items in the sequence is very large.
  • Generator implementation of such sequence is memory friendly and is preferred since it only produces one item at a time.

3. Represent Infinite Stream

  • Generators are excellent medium to represent an infinite stream of data.
  • Infinite streams cannot be stored in memory and since generators produce only one item at a time, it can represent infinite stream of data.
  • The following example can generate all the even numbers (at least in theory).
def    all_even():
           n = 0
           while True:
                 yield n
                 n += 2

4.  Pipelining Generators

  • Generators can be used to pipeline a series of operations. This is best illustrated using an example.
  • Suppose we have a log file from a famous fast food chain. The log file has a column (4th column) that keeps track of the number of pizza being sold every hour and we want to sum it to find the total pizzas sold in 5 years.
  • Assume everything is in string and numbers that are not available are

marked as ‘N/A’.

A generator implementation of this could be as follows.

with  open('sells.log') as file:
         pizza_col  =  (line[3] for line in file)
         per_hour  =  (int(x) for x in pizza_col if x != 'N/A')
         print("Total pizzas sold  =  ",sum(per_hour))

Python Generator Expression

  • Simple generators can be easily created on the fly using generator expressions. It makes building generators easy.
  • Same as lambda function creates an anonymous function, generator expression creates an anonymous generator function.
  • The syntax for generator expression is similar to that of a list comprehension in Python. But the square brackets are replaced with round parentheses.
  • The major difference between a list comprehension and a generator expression is that while list comprehension        produces the entire list, generator expression produces one item at a time.
# Initialize the list
my_list = [1, 3, 6, 10]

# square each term using list comprehension

[x**2 for x in my_list]

# Output: [1, 9, 36, 100]
# same thing can be done using generator expression
(x**2 for x in my_list)

# Output:

generator object genexpr at 0x0000000002EBDAF8

Reference

https://www.python.org/

https://www.anaconda.com/

Continue exploring at Teknonauts.com

]]>
https://teknonauts.com/python-programming-06/feed/ 0
#29 Python Programming – Python Function, File Dictionary and Exception Handing https://teknonauts.com/python-programming-05/ https://teknonauts.com/python-programming-05/#respond Wed, 14 Jul 2021 07:45:49 +0000 https://teknonauts.com/?p=4295

Python Function

  Python functions are classified into two types

  • Built-in functions (or) library functions ( example: print(),sort(),list() etc., )
  •  User defined functions – which are created by user.

When you creating user-defined functions don’t use python keywords.

Definition

  • A function is a block of code (or) script .
  • A python function is defined as a group of statements (or) script placed inside another statement or scripts.
  • The main advantage of using function is its reusability in our working script.
  • Whenever we want to repeat a particular operation again and again, functions allow us to write the definition once and call function more than one time.

Function advantages

  • Provide reusable code /script, delivering enhanced modularity for your application.
  • Easy way to debug your script
  • Improve script scalability
  • Allows to import more than one external program
  • The Function operation block,  previously mentioned as definition block ( action block ) will use def keyword
  • Function call is nothing but to invoke a function. In python function call has bottom-up approach.

Function definition syntax

def   function_name() :

           Function definition block

Syntax rules

  • Function name must begin with keyword def
  • Function name is case sensitive .Also avoid the usage of python keywords as a function name.
  • The function definition must end with colon :
  • All other lines inside a function, placed after the function definition are indented.

How to call a function ?

Let’s start with an example function hello().

def   hello() :
         print “This is hello function block”

Calling a function definition (or) invoking a function is nothing but writing a function name, followed by open and close parentheses ( ).

hello()  # This is simple function call
print  “Exit From script”

Whenever python interprets the line hello (), the hello function block will execute and after completing the execution, the control will return back to the script section

Example :

def   hello ( ) :
              print “This is hello function block”
print “B4 function call”
hello() # simple function call
print “After function call”

Output:-

B4 function call

This is hello function block

After function call

Function definitions can be placed in any order. But its execution is based on the order of the function calls

File : p1.py

import os    #  import  python os module file into local script
def    view( ):
          print “This is view function block”
          print “display list of mounted file system details :”
          os.system(“df –Th”)  # df –Th is a unix like operating system command
          print  “Exit from view function”
 
def   display() :
         print “This is display block”
         print “Current process details”
         os.system(“ps –f”)
         print “Exit from display function”
 
print   “Im Script Section “
display()  # 1st call  
view()  # 2nd call
print “Exit From script”

Nested function calls

  • Nested function calls are similar to nested structures where the function calls are placed inside another function.
  • These nested structures are applied in many situations which includes dependency-based actions and stack applications.
  • Let’s have an example
def  functionA() :
           print  “Im functionA”
           functionB() # nested call
 
def functionB():
          print “Im functionB”
          functionC()  # nested call
 
def functionC():
          print “Im functionC”
 
functionA()  # This is main script call
print “Exit from function block”

Output :-

Im functionA

Im functionB

Im functionC

Exit From function block

Function call with arguments

While passing arguments to a function, those arguments should be placed in the correct positional order.

def  hello(a1,a2) :  
          print “1st argument :”,a1
          print “2nd argument:”,a2
          print “Arguments types are :”
          print type(a1)
          print type(a2)


hello(10,20)                                       # arguments are numbers
hello(“/etc/passwd”, “/var/log/auth.log”)   # arguments are string
hello(“data1”,”data2”)                             # arguments are string
hello([‘one’,’two’,’three’],(“three”,”four”))         # arguments are list and tuple
hello({‘key1’:’Value1’,’key2’:’Value2’}, [10,20,30]) # arguments are dict and list

In python, the arguments passed inside a function are classified as

  1. Required arguments
  2. Keyword arguments
  3. Default arguments
  4. Variable-length arguments

Required arguments

  •  These are the function arguments that have to be passed to a function in correct positional order.
  • The order of the arguments should match in both function call and function definition.
  • In case of any mismatch, the python return an error (Type Error) message and exits from the script without continuing to the next statement.

File : p1.py

print "I am python"
def a():  #  No arguments are given
          print "This is a block"
a(10,20)  #  call with two arguments
for v in [1,2,3,4,5]:
          print v
print "Exit from block"

Output :

I am python

Traceback (most recent call last):

  File “a.py”, line 5, in

    a(10,20)

TypeError: a() takes no arguments (2 given)

  • In the above example, the control stops executing the next looping statements placed after the function call.
  • Using exception handling technique we can handle this exception and can make the control move forward to the next statement of execution.
  • Here, the number of arguments (count) in the function call should also match exactly with the number of arguments in function definition.
def   display(a1,a2):

          print “This is display block”

          print “Received 1st argument:”,type(a1)

          print “Received 2nd argument:”,type(a2)

# The above code display block contains two arguments

display(“data1”,”data2”)  # valid call
display() # empty argument – invalid call
display(10,20,30) #more than two arguments - invalid call

Keyword  arguments

  •  Keyword arguments are related to the function calls.
  • When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name.
  • This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters.
def  display( name,age) :
          print  “Name:”, name
          print “Age:”,age
 
display(name=”Mr.Xerox”,age=55) 

In python, the function will take the default value if the value is not passed in the function call as an argument.

def display(name=”Mr.Xerox”,dept=”Sales”) :
                   print “Name:”,name
                   print “Dept:”,dept
display()
display(name=”Mr.John”,dept=”Account”)
display(name=”Mr.Paul”)
display(dept=”Production”)
  • A default argument is an argument that assumes a default value if the value is not provided in the function call as argument.

Variable-length arguments

  • You may need to process a function for more arguments than you specify while defining the function.
  • These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments.
def  functionname(*variable) :
                   function definition operation
 
functionname(arg1,arg2,arg3……argN)

Example

def  display(a1,*a2):

          print type(a1)  #  type ‘str’

          print type(a2)  #  type `tuple`

display(“data”,10,20,30,40,50,60)

  • An asterisk (*) is placed before the variable name that holds the values of all non-keyword variable arguments.
  • These collection of non-keyword arguments form a tuple and it remains empty if no additional arguments are specified during the function call.

The *args vs **kwargs

  •  We studied  *args allows you to do is take in more arguments than the number of formal arguments that you previously defined.
  •   With *args, any number of extra arguments can be treated as tuple type in formal parameters 
  •  The special syntax**kwargs in function definitions in python is used to pass a keyword variable-length argument list.
  • We use the name kwargs with the double star.
  •  The reason is because the double star allows us to pass through       keyword arguments (and any number of them).
  •  A keyword argument is where you provide a name to the variable as you pass it into the function.
  •  The kwargs as being a dictionary that maps each keyword to the value that we pass along it.
  • That’s the reason when we iterate over the kwargs there doesn’t seem to be ordered result.
  •  kwargsreturn type will be ‘dict’ type.
>>> def    display(**kwargs):
...             print type(kwargs)

...

>>> display(name="Karthik",place="Bangalore")

 type 'dict'

>>> def    display(**kwargs):

 

...     for v in kwargs.keys():

...             print v,"\t",kwargs[v]

>>> display(name="Karthik",place="Bangalore")

#output
place   Bangalore

name    Karthik

Anonymous function

  •  Anonymous function (or) lambda function i.e., functions unnamed or without name.
  • The general syntax of a lambda function:-

lambda argument_list expression

  • The argument_ list consists of list of arguments separated by comma and the expression is
  • an arithmetic expression using these arguments.
  • You can assign the function to a variable to give it a name.

>>> f = lambda x, y : x + y

>>> f(10,20)

30

Scope of variables

  • All variables within a program may not be accessible at all locations in that program.
  • This depends on where you have declared that variable.
  • The scope of a variable determines the portion of the program where you can access a particular identifier.
  • There are two basic scopes of variables in Python ?
  • Global variables
  • Local variables
  • Variables that are defined inside a function is called local variables
  • Local variables can be accessed only inside the function, we can’t access outside the function

Example:

def    hello():
         Fname=”/var/log/result.log”   # local variable
         print “File name:”,Fname  
hello() # function call
print “Outside function  File name:”, Fname  ## NameError
  • We can use a global variable in other functions by declaring it as global in each function that assigns to it.
  • Global variables are accessible from anywhere in the script  i.e., inside a function and outside a function.

Example :

def  hello():
         global Fname #  variable Fname is a global variable
         Fname=”/var/log/result.log”   
 
def  display():
       print “Result log file name is: “,Fname   # Result log file name is:/var/log/result.log
 
hello()
display()
print  “Outside function  File name:”  # display Outside function File name:/var/log/result.log

File Handling categories

  • Read a data from Keyboard(STDIN) to script write a data to FILE ( Not using Monitor(STDOUT) )
  • Read a data from FILE to Script display to Monitor ( Not using STDIN )
  • Read a data from one FILE to Script write a data to another FILE (Not using STDIN/STDOUT. (like: cp old new))
  • When we want to read from or write to a file we need to open it first.
  • When we are done, it needs to be closed, so that resources that are tied with the file are freed.
  • Hence, in Python, a file operation takes place in the following order.
    • Open a file
    • Read or write (perform operation)
    • Close the file

How to open a file?

  • Python has a built-in function open() to open a file.
  • This function returns a file object, also called a handle, as it is used to read or modify the file accordingly.

Syntax :

Object=open(“Inputfile”)
>>> f = open("test.txt")    # open file in current directory
>>> f = open("/var/log/temp.log")  # specifying full path
  • We can specify the mode while opening a file.
  • In mode, we specify whether we want to read ‘r’, write ‘w’ or append ‘a’ to the file.
  • We also specify if we want to open the file in text mode or binary mode.
  • The default is reading in text mode. In this mode, we get strings when reading from the file.
  • On the other hand, binary mode returns bytes and this is the mode to be used when dealing with non-text files like image or exe files.

Python File Modes

Python File Modes
ModeDescription
‘r’Open a file for reading. (default)
‘w’Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists.
‘x’Open a file for exclusive creation. If the file already exists, the operation fails.
‘a’Open for appending at the end of the file without truncating it. Creates a new file if it does not exist.
‘t’Open in text mode. (default)
‘b’Open in binary mode.
‘+’Open a file for updating (reading and writing)

Example:-

f = open("test.txt")      # equivalent to 'r' or 'rt'
f = open("test.txt",'w')  # write in text mode
f = open("img.bmp",'r+b') # read and write in binary mode

How to close a file Using Python?

  • When we are done with operations to the file, we need to properly close the file.
  • Closing a file will free up the resources that were tied with the file and is done using Python close() method.
  • Python has a garbage collector to clean up unreferenced objects but, we must not rely on it to close the file.
f = open("test.txt)
# perform file operations
f.close()

How to read a file using python ?

Syntax :-

Object=Open(“Inputfile”,”mode”)
Example:-
>>> obj=open(“/var/log/result.log”,”r”)  # r – read mode by default.
>>> type(obj)

Read data from file in python we are using different functions.

1.read() – read the entire file contents and returns them as a single string
Example :-

cat IP1.txt
Data1
Data2
Data3
Data4
obj=open(“IP1.txt”)
obj.read()
‘Data1\nData2\nData3\nData4\n’
type(obj.read())

2. readline() – read the file contents line by line return as a single string

>>> obj=open(“IP1.txt”)
>>> obj.readline()
‘Data1’
>>> obj.readline()
‘Data2’
>>> obj.readline()
‘Data3’
>>> obj.readline()
‘Data4’
>>> obj.readline()
“ ”

3. readlines() – read the entire file contents and return as a single list type of data.

>>>obj=open(“IP1.txt”)
>>>type(obj.readlines())
>>>obj.readlines()
[‘Data1\n’,’Data2\n’,’Data3\n’,’Data4\n’]

4. next() – read line by line like readline() and return the next item from the iterator.

  • If default is given and the iterator is exhausted , control returns instead of raising StopIteration
>>>obj=open(“IP1.txt”)
>>>type(next(obj))
>>> next(obj)
‘Data1’
>>> next(obj)
 ‘Data2’
>>> next(obj)
 ‘Data3’
>>> next(obj)
 ‘Data4’
>>> next(obj)
StopIteration 
  •  Note that above object (obj) is iterable object. So will use for loop will read data from file.
>>> obj=open(“IP.txt”) # open a file , bydefault read mode
>>> for var in obj:  # iterable object
              print var.strip() # strip() function is used to remove \n char
>>> obj.close()  # close the file object
     Data1
     Data2
     Data3
     Data4
     Data5
  • This method is not entirely safe. If an exception occurs when we are performing some operation with the file, the code exits without closing the file.
  •  A safer way is to use exception handling techniques which we will be discussing later. 
try:
       f = open(“test.txt”)
except Exception as e:
     print e
else:
      for var in f:
               print var.strip
finally:
       f.close()

How to write to a File in Python?

  • In order to write into a file in Python, we need to open it in write ‘w’, append ‘a.

Syntax:-

open(“Filename”,” w”)

Example:-

f=open("test.txt",'w’):
f.write("my first file\n")
f.write("This file\n\n")
f.write("contains three lines\n")
f.close()
  • This program will create a new file named ‘test.txt’ if it does not exist. If it does exist, it is overwritten.
  • We must include the newline characters ourselves to distinguish different lines.

Using with keyword

with open("test.txt",'w') as f:
        f.write("my first file\n")
        f.write("This file\n\n")
        f.write("contains three lines\n")
  •   This program will create a new file named ‘test.txt’ if it does not exist.
  •   If it does exist, it is overwritten.
  •   When using with keyword, file handler will be closed automatically.
  •  No need to explicitly use f.close().  

Using seek() method

We can change our current file cursor (position) using the seek() method.

>>> obj.seek(0)   # brings file cursor to initial position
0
>>>obj=open(“IP.txt”)
>>>obj.read()
‘Data1\nData2\nData3\nData4\nData5\n’
>>>obj.read()
“ “ # empty string
>>>obj.seek(0)  # brings file cursor to initial position
>>>obj.read()
‘Data1\nData2\nData3\nData4\nData5\n’

Python Directory Handling

  •  A directory or folder is a collection of files and sub directories.
  •  Using python os module we can handle the directories

Get Current Directory

  •   We can get the present working directory using the getcwd()method.
  •   This method returns the current working directory in the form of a string
>>> import os
>>> os.getcwd()
'C:\\Users\\Krosumlabs\\Desktop'

Changing Directory

  • We can change the current working directory using the chdir() method.
>>> os.chdir('C:\\Python33')
>>> print(os.getcwd())
C:\Python33
  •   The new path that we want to change must be supplied as a string argument to this method.
  •   We can use both forward slash (/) and the backward slash (\) to separate the path elements.

List Directories and Files

All files and sub directories inside a directory can be known using the listdir() method.

>>> os.listdir()
['DLLs',
'Doc',
'include',
'Lib',
'libs',
'LICENSE.txt',
'NEWS.txt',
'python.exe',
'pythonw.exe',
'README.txt',
'Scripts',
'tcl',
'Tools']

Making a New Directory

  •  We can make a new directory using the mkdir() method.
  •  This method takes in the path of the new directory. If the full path is not specified the new directory is created in the current working directory.
>>> os.mkdir('test')
>>> os.listdir()
['test']

Renaming a Directory or a File

  • The rename() method can rename a directory or a file.
  • The first argument is the old name and the new name must be supplied as the second argument.
>>> os.listdir()
['test']
>>> os.rename('test','new_one')
>>> os.listdir()
['new_one']

Removing Directory or File

  • A file can be removed (deleted) using the remove() method.
  • Similarly, the rmdir() method removes an empty directory.
>>> os.listdir()
['new_one', 'old.txt']
 
>>> os.remove('old.txt')
>>> os.listdir()
['new_one']
 
>>> os.rmdir('new_one')
>>> os.listdir()
[]
  •  However, note that rmdir() method can only removes empty directories.
  •  In order to remove a non-empty directory we can use the rmtree() method inside the shutil module.
>>> os.listdir()
['test']
>>> os.rmdir('test')
Traceback (most recent call last):
...
OSError: [WinError 145] The directory is not empty: 'test'
 
>>> import shutil
>>> shutil.rmtree('test')
>>> os.listdir()
[]

Multidimensional data structures

Combination of List,tuple and dictionary structures

List  of List

>>> confs=[["p1.log","p2.log","p3.log"],["host01","host02"],
                          ["/etc",  ["passwd",”gpasswd"] ]  ]
>>> type(confs)
>>> confs[0]  # display 0th index
['p1.log', 'p2.log', 'p3.log']
>>> confs[1]  # display 1st index
['host01', 'host02']
>>> confs[2] # display 2nd index
['/etc', ['passwd', 'gpasswd']]
>>> confs[2][1] # list of list 2nd index of 1st index
['passwd', 'gpasswd']
>>>
>>> confs[1] # 1st index
['host01', 'host02']
>>> confs[2][1]
['passwd', 'gpasswd']
>>> confs[2][1][0] # list of list
'passwd'

List of tuple

# List inside tuples
>>> IPs=[('host01','host02','host03'),('host04',('host05'))]
>>> type(IPs)
>>> IPs[0]
('host01', 'host02', 'host03')
>>> type(IPs[0])
>>> IPs[-1]
('host04', 'host05')
>>> IPs[-1][0]
'host04'
>>> IPs[-1][1]
'host05'

Tuple of Tuple

# Read only mode
>>> files=("/etc/passwd",("p1.log","p2.log"),("p3.log"),("p4.log"))
>>>
>>> type(files)
>>>
>>> type(files[1])
>>> files[1]
('p1.log', 'p2.log')
>>>
>>> files[1][0]
'p1.log'

Tuple of List

>>> IPs=(['10.20.30.40','10.20.30.50','10.20.30.65'],['/etc/passwd','/etc/hosts','/etc/gpasswd'])  # tuple of list
>>> type(IPs)
>>> IPs[0]  # 0th index is List
['10.20.30.40', '10.20.30.50', '10.20.30.65']
>>> type(IPs[0]) # List type
>>> IPs[0][0] # tuple of list
'10.20.30.40'
>>> IPs[0][1]
'10.20.30.50'
>>> IPs[1]
['/etc/passwd', '/etc/hosts', '/etc/gpasswd']
>>> IPs[1][-1]
'/etc/gpasswd'
>>> IPs[-1]
['/etc/passwd', '/etc/hosts', '/etc/gpasswd']

Dictionary of List

# Single key points to multiple values ( list )
 Confs={'hosts':['/etc/hosts','/etc/hostname','/etc/sysconfig/network-scripts’]}
# ‘hosts’ is a key – value is list
>>> type(Confs)
>>> Confs['hosts']
['/etc/hosts', '/etc/hostname', '/etc/sysconfig/network-scripts']
>>> type(Confs['hosts'])
>>> Confs['hosts'][0]  # from dict key is pointing to 0th index list
'/etc/hosts'
>>> Confs['hosts'][-1] # from dict key is pointing to last index
'/etc/sysconfig/network-scripts'

Dictionary of tuple

# Dictionary key  value is tuple
 Confs={'hosts':('/etc/hosts','/etc/hostname','/etc/sysconfig/network-scripts’)}
>>> type(Confs)
 
>>> Confs['hosts'] # dictionary key is  tuple value
('/etc/hosts', '/etc/hostname', '/etc/sysconfig/network-scripts')
 
>>> type(Confs['hosts'])
>>> Confs['hosts'][0]  #  0th index
'/etc/hosts'
>>> Confs['hosts'][1]
'/etc/hostname'
>>> Confs['hosts'][2]
'/etc/sysconfig/network-scripts'

Dictionary of Dictionary

# Dictionary is holding another dictionary
>>> Confs={'host1':{'file1':'/etc/hosts'},'host2':{'file2':'/etc/hostname'},
                      'host3':{'file3':'/etc/sysconfig/network-scripts'}}
>>> type(Confs)
>>> type(Confs['host1'])  
>>> Confs['host1'] # host1 key value is dictionary
{'file1': '/etc/hosts'}
>>> Confs['host1']['file1']  # dictionary of another dictionary
'/etc/hosts'

Exception Handling in Python

Exceptions

  • An exception is a signal that an error or other unusual condition has occurred.
  • When that error occurs, Python generate an exception that can be handled, which avoids your program to crash.
  • Exceptions are convenient in many ways for handling errors
  • Below is some examples explaining some common exceptions errors in Python:

Examples

>>> var=10
>>> print Var  # Invalid variable –python case sensitive
Traceback (most recent call last):
  File "", line 1, in
NameError: name 'Var' is not defined
>>> a=['one','two','three']
>>> a[3] # invalid index
Traceback (most recent call last):
File "", line 1, in
IndexError: list index out of range
 
>>> import Http  # module is not loaded
Traceback (most recent call last):
  File "", line 1, in
ImportError: No module named Http
# Temp.log file is not exists
>>> open("Temp.log")
Traceback (most recent call last):
  File "", line 1, in
IOError: [Errno 2] No such file or directory: 'Temp.log'

Handling an exception

  • In basic terminology we are aware of try/except clause.
  • The code which can cause an exception to occur is put in the try block and the handling of the exception is implemented in the except block.

Syntax

try:

    operation

except Exception :

    Handle the exception

Example


NameError: name 'Var' is not defined
>>> try:
...     Var # Exception is occured here
... except NameError:
...     print "Invalid variable"
...
Invalid variable
>>>try:
…     print 1/0
…except ZeroDivisionError:
       print "You can't divide by zero."
  •  The error handling is done through the use of exceptions that are caught in try blocks and handled in except blocks.
  •  If an error is encountered, a try block code execution is stopped and transferred down to the except block.

Handling multiple exceptions

Syntax:-

try:
          operation
 except Exception1:
           Handle the exception
 except Exception2:
           Handle the exception
 except Exception3:
           Handle the exception
 .......
except Exception'N':
           Handle the exception
 
Example:-
>>> try:
...     open("Temp.log") # File is not available
... except NameError:
...     print "Invalid variable"
... except IOError:
...     print "File is not exists"
... except ZeroDivisonError:
...     print "Divide by zero"
...
File is not exists

Try … except … else clause

  • The else clause in a try/ except statement must follow all except clauses, and is useful for the code that must be executed if the try clause does not raise an exception.
try:
        operation
except Exception:
        handle_the_exception_error
else:
         # follows the code that there is no exception    
Example :-
>>> try :
...     var=10
... except NameError:
...     print "Name error"
... else:
...     print "No Exception"
...     print "var value is:",var
No Exception
var value is: 10

Try … finally clause

  • The finally clause is optional.
  • It is intended to define clean-up actions that must be executed under all circumstances.
  • Whether the exception occurs or not, the finally block will always execute.
  • Make sure that the else clause is run before the finally block.

Example:

File : e1.py

try:
           obj=open("Temp.log")
except IOError:
           print "Invalid file"
else:
           print "Read operation"
            for var in obj:
                     print var
                     obj.close
finally:
            print "-----Thank you----"
  •  Let Temp.log file does not exist. So the exception occurs and the control moves to the except clause.
  •   It displays ‘invalid file’ message and then will go to finally block displaying a ‘—-Thankyou —-‘.

C:\Users\Krosumlabs\Desktop>python e1.py

Invalid file

—–Thank you—-

Now create a Temp.log file and then run the Script discussed above.

Now, there is no exception. So the control goes to else clause, followed by the finally block.

C:\Users\Krosumlabs\Desktop>python e1.py

Read operation

dat1

data2

—–Thank you—-

A finally clause is always executed before leaving the try statement, irrespective of whether an exception has occurred or not.

Raising an Exception

  • In Python programming, exceptions are raised when corresponding errors occur at run time, but we can forcefully raise it using the keyword raise.
  • We can also optionally pass values to the exception to clarify why that exception was raised.
>>> raise KeyboardInterrupt
Traceback (most recent call last):
KeyboardInterrupt
>>> raise MemoryError("This is an argument")
Traceback (most recent call last):
MemoryError: This is an argument
>>> try:
...     a = int(input("Enter a positive integer: "))
...     if a <= 0:
...         raise ValueError("That is not a positive number!")
... except ValueError as ve:
...     print(ve)
...    
Enter a positive integer: -2
That is not a positive number!

Python Built-in Exceptions

  •   Illegal operations can raise exceptions. There are plenty of built-in exceptions in Python that are raised when corresponding errors occur.
  •    We can view all the built-in exceptions using the local() built-in functions as follows.

>>> locals()[‘__builtins__’]

  •   This will return us a dictionary of built-in exceptions, functions and attributes.

Reference

https://www.python.org/

https://www.anaconda.com/

Continue exploring at Teknonauts.com

]]>
https://teknonauts.com/python-programming-05/feed/ 0
#28 Python Programming – Conditional Statements and Dictionary https://teknonauts.com/python-programming-04/ https://teknonauts.com/python-programming-04/#respond Thu, 24 Jun 2021 12:03:20 +0000 https://teknonauts.com/?p=4265

Python Conditional Statements

if statement

  • The if statement contains a logical expression using which data is compared and  a decision is made based  on the result of  the comparison

if( condition-expression ):

Syntax :

if( condition-expression ):

    Operation Block

  • If the Boolean expression evaluates to True, then the block of statement(s) inside the if statement is executed.
  • If Boolean expression evaluates to False, then the first set of code after the end of the if statement(s) is executed.
  • Note: The indentation is important in python. After conditional statement, on the next line followed by indent, write down true block operation

if..else style

  • An else statement can be combined with an if statement
  • If the condition is not True , the control will go to the else block part

Syntax :

if (condition):

True Block operation

else:

False Block operation

  • Note: After the else statement, the next line followed by the indentation is the False block operation

if..elif..elif..else style

  • Based on the outcome, if we need to determine which action to take place and which statements to execute, then the choice will be Multi conditional statements

Syntax:-

if ( condition1) :

         True block -1

elif  ( condition2):

         True Block-2

elif (condition3):

         True Block-3

elif (conditionN):

         True Block-N

else:

         False Block

  • Python will test the condition1 expression, if condition1 is True, the control will go to Trueblock -1, executes the python code then exits from the block
  • If condition1 fails, then the control will test the condition2 block
  • If condition2 is True, execute True Block-2 operation, then exit from control statement so on
  • Only if all the conditions are failed control will go to else block

Example :

if ( “AB” == “AB”) :

       print (“Im True Block1”)

elif (100 >50):

       print (“Im True Block2”)

elif (“SAB” != “sab”) :

       print (“Im True Block3”)

else :

        print (“False Statement”)

  • In the above example, all the given conditions are True
  • As per the flow, the Python will test the 1st condition ( “AB” == “AB”)
  • Here condition1 is True, so the control will go to True block
  • In case if 1st condition is False, the control will go to next condition

Result :   “Im True Block1”

Looping in Python

  • A looping statement allows us to execute the code blocks more than one time
  • Python looping statements are executed in two ways
    • List style – Execution of the block depends on the number of elements in the list
    • Conditional style – – Execution of the block depends on the conditional statement

Python for loop

Syntax

for variable in list-of-elements:

Operation block

# Note:

Just like conditional statements, looping statements also needs proper indentation.

forin are keywords.

  • If a list-of-elements in turn contains a list or a tuple or an unnamed expression list, the loop evaluates them first
  • And then, the first item in the list is assigned to the iterating variable
  • Next, the statements block is executed.
  • Further, each item in the list is assigned to iterating variable, and the statement(s) block is executed until the entire list  is finished

Example 1

for var in "host01","host02","host03" :  
  print "Host name:",var       # Block will run 3 times

Result :-

Host name:host01

Host name:host02

Host name:host03

Example 2

IPs=['10.20.30.40','10.20.30.50','10.20.30.60','10.20.30.66','10.20.40.60']
for var in IPs:
      print "System IP:",var
      print "-------------------"

Result:-

System IP: 10.20.30.40

———————————–

System IP:10.20.30.50

———————————–

System IP:10.20.30.60

———————————–

System IP:10.20.30.66

———————————–

System IP:10.20.40.60


  • The above looping statement will run 5 times
  • List variable IPs is holding 5 elements so block will run 5 times

Example 3

#  Display the CPU Load Balance for 5 times

import os
for v in 1,2,3,4,5:
         os.system("uptime")

Example 4

import os
for v in [1,2,3,4,5]: <======= List contains 5 elements
            os.system("uptime")

Example 5

import os
for v in (1,2,3,4,5):  <======= tuple contains 5 elements
              os.system("uptime")

Example 6

import os
for v in ('data1','data2','data3','data4','data5'):   <======= tuple contains 5 elements
              os.system("uptime")
  • All the above examples have same result.
  • It displays the current CPU load balance result 5 times

range()

By using the range() method, we can iterate over the  looping operations, The range function takes number (any integer),say n as argument and returns a list of values start from 0 to n-1

Example: 

range(5)  ==>  [0,1,2,3,4]
range(n,m)  ==> start from 'n' value to 'm-1' value
range(1,5)  ==> [1,2,3,4]
range(n,m,count)   ==>  start from 'n' value to 'm-1' for every count occurrence
range(1,7)   ==>  start from 1 to 6   ==> [ 1,2,3,4,5,6 ]   ==>  for every occurrence single increment
range(1,7,3)  ==> every 3 increment  ==> [1,4]

How to use range() in for loop statements ?

Example:

for v in range(5) :   # [0,1,2,3,4]  No.of elements in the list is 5 ,so block will run 5 times
           print "Hello..",v

Result:-

Hello..0

Hello..1

Hello..2

Hello..3

Hello..4

for v in range(1,10,3): 
          print "value of v:",v  # Block will run 3 times

Result :-

value of v:1

value of v:4

value of v:7

Using else Statement with Loops

  • Python supports the usage of an else statement with a loop statement
  • In case the else statement is used with a for loop, the else statement is executed when the loop has finished iterating the list
  • Generally else statements are optional in looping statements and are usually used to write a footer message
  • else block can be used with both for and while loops

Example:-

for v in range(5):
         print "Hello-->",v
else:
         print "Thank you"

Result:-

Hello–>0

Hello–>1

Hello–>2

Hello–>3

Hello–>4

Thank you

Python While loop

A while loop in Python continuously executes a statement as long as the given condition is true.

syntax

While (condition ) :

Operation –block

  • The Loop will test the condition. If condition is True, the operation block is executed and again the condition is tested and if condition is True again, it repeat the operation
  • This goes on until the condition fails where the loop terminates
  • Here the operation block execution is determined only by the condition and not by the list, tuple or list of values

Example:-

count=0
while(count<5):
  print "Count value :",count
  count=count+1

Result :

Count value : 0

Count value : 1

Count value : 2

Count value : 3

Count value : 4

While with else statement

Example :-

count=0
while(count<5):
  print "Count value :",count
  count=count+1
else :
   print "Thank you"

Result

Count value : 0

Count value : 1

Count value : 2

Count value : 3

Count value : 4

Thank you

Looping statements

1) break – Terminate from loops

  • The most common use of break is when some external condition is triggered requiring a hasty exit from a loop
  • The break statement can be used in both while and for loops

Example

while True:

Fname=raw_input( “Enter a first name:”):
if( Fname == “Ram” ):
          print “Matched”
          break  # Exit from while loop 
  • The above loop is an un-conditional ( always  true ) infinite loop
  • Once the condition is matched, block will get terminate

2) Continue-continues on the next iteration of the loop

  • It returns the control to the beginning of the while loop
  • The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control  back to the top of the loop
  • The continue statement can be used in both while and for loops

Example :

for  var in [‘Mon’,’Tue’,’Wed’,’Thu’,’Fri’]:
if(var == “Wed”):
      continue # Skip the wed, continue to the next statement
else:
      print var

Result:

Mon

Tue

Thu

Fri

3) Pass statement

  • The pass statement is a null operation; nothing happens when it executes
  • The pass is also useful in places where your code will eventually go, but has not been written yet (e.g., in stubs for example) ?

Example:

for letter in 'Python':
       if letter == 'h':
             pass
             print 'This is pass block'
             print 'Current Letter :', letter
             print "Good bye!"

Result:-

Current Letter : P

Current Letter : y

Current Letter : t

This is pass block

Current Letter : h

Current Letter : o

Current Letter : n

Dictionary

  • Python dictionary is an unordered collection of data items
  • Like list python dictionary is also modifiable
  • A dictionary contains collection of items, which is of (key,value)  pair

Syntax :-

Dictionaryname={‘Key’ : ‘Value’ }

  • Keys are unique string whereas value can duplicate
  •  Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces
  • The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples

How to create a dictionary?

  • Creating a dictionary is as simple as placing items inside curly braces { } separated by comma

Syntax :-

Dictionaryname={‘Key1’ : ‘Value1’, ‘Key2’: ‘Value2’…….’Key N’: ‘Value N’ }

Examples:-

Hosts={‘ip’ : ’10.20.30.40’, ‘file’:’/etc/hosts’ , ‘port’ : 22 }

Hosts is the name of the dictionary

ip is a key & its value is  an IP address (10.20.30.40 )

file  is a key & its value is /etc/hosts

port is a key & its value is 22

Generally, dictionaries have a key and the corresponding value expressed as a pair, key: value

How to access the elements from a dictionary?

  • Similar to list, in order to get the data from a dictionary, we use index [ ] notation

Using index [  ]  : 

dict_name[‘key’]

  • Keys can also be used with the get() method to access the elements from a dictionary.

Using get() :  

dict_name.get(‘key’)

Examples:-

emp={‘name’ : ‘Mr.Kris’ , ‘ID’ : ‘E123’, ‘dept’:’sales’}
print “Emp name is:”, emp[‘name’]
print emp[‘name’],” Working department is:”,emp.get(‘dept’)
Mr.Kris Working department is: sales

Size of a dictionary

  • We use len() function to display the size of a dictionary 
emp={‘name’ : ‘Mr.Vishnu’ , ‘ID’ : ‘E123’, ‘dept’:’sales’}
print len(K) 
3
  • Data inside a dictionary are unordered elements
  • In order to get list of keys from dictionary, we use keys() function

Syntax:-

dictionary_name.keys()

keys() returns a collection of values and its return type will be of list type.

K=emp.keys()

# Determine keys() return type

type(K) 

(or)

type(emp.keys())

Dictionary Manipulation

 Dictionary are mutable, which means that we can add new data (key:value) into an existing dictionary or we can update/modify the value of an existing dictionary using an assignment operator

Adding new data to a dictionary

Whenever adding a new data to an existing dictionary, we should define a new unique key and a value

Syntax :-

dictionary_name[‘Key’]=”Value”

Examples:-

>>>emp={‘name’ : ‘Mr.Vishnu’ , ‘ID’ : ‘E123’, ‘dept’:’sales’}
>>>print  len(emp.keys())
3
>>>emp[‘phone’]=”+91 9901233456”
>>>emp[‘place’]=”Bangalore”
>>>print  len(emp.keys())
5
Modifing an existing data in a dictionary

Syntax:-

dictionary_name[‘Key’]=”Updated Value”

Example:-

>>>emp={‘name’ : ‘Mr.Vishnu’ , ‘ID’ : ‘E123’, ‘dept’:’sales’, ’phone’ : ’+91 9901233456’, ‘place’ : ‘Bangalore’}
>>>print “Before Modification : “, emp[‘dept’]
>>>emp[‘dept’]=”PRODUCTION” # modify existing value
>>>print “After Modification : ”,emp[‘dept’]

Result:-

After Modification : PRODUCTION

Before Modification : sales

Delete a single record from dictionary

Syntax :- del(dictionary_name[‘Key’])

To clear the entire contents of a dictionary
Syntax:-

dictionary_name.clear( )

Example:-

>>>emp={‘name’ : ‘Mr.Vishnu’ , ‘ID’ : ‘E123’, ‘dept’:’sales’}
>>>print “Total no.of records :”,len(emp.keys())  
Total no.of records : 3
>>>del(emp[‘dept’] ) # to delete a single record
>>>print “Total no.of records :”,len(emp.keys())
Total no.of records : 2
>>>emp.clear( ) # remove all entries in  emp dictionary 
>>>print “Total no.of records :”,len(emp.keys())
Total no.of records : 0
To delete an entire dictionary

del(emp)

Dictionary methods and examples

Syntax

dictionary_name.clear()  #removes all elements of dictionary 

>>>emp={‘name’ : ‘Mr.Vishnu’ , ‘ID’ : ‘E123’, ‘dept’:’sales’}
>>>emp.clear()  - Now the size of dictionary is zero

Syntax : dictionary_name.setdefault(key,default=None)

  • The method setdefault() is similar to get(), but the difference is that it sets dictionary_name[key]=default  if the key does not exist in the dictionary
  • Similar to get() method, it returns the value corresponding to the key
  • In case if the given key is not available; it returns the provided default value
emp={‘name’:’Vishnu’,’dept’:’sales’}
emp.setdefault(‘name’)  # displays name (key) value as Vishnu.
#If passed as invalid key as an argument , it will return as None.
emp.setdefault(‘Name’) -> None 
if(emp.setdefault(‘Name’)==None):
             print “Invalid Key”
  • The above program input key (‘Name’) is an invalid key, so the default value (None) will be returned
  • Here the condition is True .So the control goes to True block  and the script say ‘Invalid key
if(emp.setdefault(‘name’) ==None):
                 print “Invalid key”
else:
                 print “value of name is :”,emp[‘name’]

In the above code, the given key is a valid key (‘name’). Hence it returns a  string(“Vishnu”) and not ‘None’.

value of name is: Vishnu

Syntax

dictionary.update(dict2)

  • The method update() adds the dictionary dict2’s key-values pairs in to dict
  • This function does not return anything
  • But all items of dict2 is added into dict1
Items={‘code’:’P-123’,’cost’:1000.54}
Files={‘fname’:’Invoice.txt’, ‘size’:’100M’}
Items.update(Files) # Files dictionary is added into Items dictionary 
>>> Items
{‘code’:’P-123’,’fname’:’Invoice.txt’,’cost’:1000.54,’size’:’100M’}
# Note that dictionary are unordered data type
>>> print “Total no.of records :”,len(Items.keys())
Total no.of records:4

Syntax

dictionary_name.keys()

  • This method returns a list of all keys available in a given dictionary
>>>emp={‘name’ : ‘Mr.Vishnu’ , ‘ID’ : ‘E123’, ‘dept’:’sales’}
>>>emp.keys()
[‘name’, ’ID’, ’dept’ ]
  • The return type of keys() will be always list type of data

Syntax

dictionary_name.items()

  • The method items() returns a list of dictionary’s (key, value) tuple pairs
>>>  emp={‘name’ : ‘Mr.Vinu’ , ‘ID’ : ‘E123’, ‘dept’:’sales’}
>>> emp.items()
[('dept', 'sales'), ('name', 'Mr.Vinu'), ('ID', ‘E123')]

Syntax:

dictionary_name.has_key(Key)

  • This method has_key() returns True if a given key is available in the dictionary, otherwise it returns a False.
>>>  emp={‘name’ : ‘Mr.Vinu’ , ‘ID’ : ‘E123’, ‘dept’:’sales’}
>>> emp.has_key(‘name’)
True
>>> emp.has_key(‘NAME’)  # invalid input key
False
  • Since dictionary_name.has_key(Key) returns a Boolean values (True / False ), it is mostly used in testing or validation
if(emp.has_key(‘name’)):  # input key is valid return will be True
               print “Name is Found:”,emp[‘name’]
else:
                print “Invalid key”
  • Since the condition satisfies, the above code displays ‘Name is Found: Mr.Vinu’
if(emp.has_key(‘NAME’)):  # input key is invalid return will be False
          print “Valid Key”
else:
          print “Invalid Key”   
  • Here the function returns false and hence it displays ‘Invalid Key’.
Other dictionary methods

pop() method

  • The pop() method removes and returns an element from a dictionary having the given key.

syntax :

dictionary.pop(key[, default])

  • Similar to deleting a single key   del(dict[‘key’]) 
emp={‘name’ : ‘Mr.Vinu’ , ‘ID’ : ‘E123’, ‘dept’:’sales’}
>>>  emp.pop(‘dept’)  # same as  del (emp[‘dept’])
sales
>>> emp
{‘ID’:’E123’,’name’:’Mr.Vinu’}

pop( ) Parameters

  • The pop() method takes two parameters:
  • key – key which is to be searched for removal
  • default – value which is to be returned when the key is not in the dictionary
  • Return value from pop()
  • The pop() method returns:
  • If key is found – remove/pop the element from the dictionary
  • If key is not found – value specified as the second argument (default)
  • If key is not found and default argument is not specified – KeyError exception is raised
emp={‘name’ : ‘Mr.Vishnu’ , ‘ID’ : ‘E123’, ‘dept’:’sales’}
>>> emp.pop(‘ID’)
‘E123’
>>>emp.pop(‘post’,’manager’)
‘manager’
>>>emp.pop(‘K1’)  # invalid key
KeyError: ‘K1’
 

popitem() 

The popitem() returns and removes an arbitrary element (key, value) pair from the dictionary.

syntax:-

dict.popitem()

The popitem() doesn’t take any parameters

Return Value from popitem()

  • returns an arbitrary element (key, value) pair from the dictionary.
  • When you run the program, the output will be
>>>emp={‘name’ : ‘Mr.Vishnu’ , ‘ID’ : ‘E123’, ‘dept’:’sales’}
>>>emp.popitem()
(‘ID’,’E123’)  
>>>emp
{‘dept’ : ‘sales’, ‘name’ : ‘Mr.Vishnu’ }
>>>emp.popitem()
(‘dept’:’sales’)
>>>emp
{‘name’ : ‘Mr.Vishnu’}
>>>emp.popitem()
(‘name’ : ‘Mr.vishnu’)
>>> emp
{}  # empty dictionary
>>> emp.popitems()  
KeyError : ‘popitem(): dictionary is empty’

Reference

https://www.python.org/

https://www.anaconda.com/

Continue exploring at Teknonauts.com

]]>
https://teknonauts.com/python-programming-04/feed/ 0
#27 Python Programming – Mathematical Functions & List P03 https://teknonauts.com/python-programming-03/ https://teknonauts.com/python-programming-03/#respond Fri, 18 Jun 2021 02:37:53 +0000 https://teknonauts.com/?p=4197

Mathematical functions

Python supports a wide variety of mathematical functions.

FunctionReturnsExample
abs(x)Returns the absolute value of xx = -35;x = abs(x)
print(x)
cmp(x,y)Returns -1 if x < y>
Returns 0 if x equals to y 
Returns 1 if x > y.
x = 6; y = 4
print( cmp(x,y) )
exp(x)Returns the exponential of ximport math
x = 6; print( math.exp(x) )
log(x)The natural logarithm of ximport math
x = 6; print( math.log(x) )
log10(x)The base-10 logarithm of ximport math
x = 6; print( math.log10(x) )
pow(x,y)The result of x**yimport math
x = 6; print( math.pow(x,2) )
sqrt(x)The square root of ximport math
x = 6; print( math.sqrt(x) )

List

  • Python List is a collection of data like array in Perl, shell script & ruby
  • Here data are not strictly of same type. It’s not like C – array
  • Data in side list are ordered elements (index based)
  • List are mutable  i.e., we can modify the content of the list
  • Lists have methods that allow you to manipulate the values inside them. 
  • Python list elements are separated by comma
  • List elements are enclosed by square brackets  [  ]

How to create a list?

Syntax:- 

listname= [data1, data2, data3, data4,data5….dataN ]

db=[ “oracle” , “sql”,”mysql”,”DB2”,”sqlite”]

|__ list name

[“oracle” , “sql” ,”mysql”,”DB2”,”sqlite” ]

      0            1           2           3             4     index

# List index starts at 0

To determine list type using type function

>>>  db=[ “oracle” , “sql”,”mysql”,”DB2”,”sqlite”]
>>> type(db)

Accessing list values

=> List of elements accessed using the list name

>>>print db   
#output
[ “oracle” , “sql”,”mysql”,”DB2”,”sqlite”]

Access single data from list

Syntax:-

listname [index number ]

Example:-

# print 0th index data

>>>print db[0]
#output
'oracle'
# print 1st index data
>>>print db[1]
'sql'
5-4-3-2-1Index From Right to Left
[‘Oracle’,‘sql’,‘mysql’,DB2’,‘sqlite’]
01234Index from Left to Right

Slice Operator

db=[ “oracle” , “sql”,”mysql”,”DB2”,”sqlite”]
print db[1:3]  #output [ ‘sql’,  ‘ mysql’ ]
print db[2:]    #output  [‘mysql’,’db2’,’sqllite’ ]
print db[:2]   #output   [‘oracle',’sql`]

Create employee list

>>>emp=[ ‘E123’, ‘Mr.Visa’, ‘sales’,’10.20.30.40.50’,’12995.46’ ]
>>>print emp
[ ‘E123’, ‘Mr.Visa’, ‘sales’,’10.20.30.40.50’,’12995.46’ ]
>>>print  “Hello ”,emp [1]
Hello  Mr.Visa
>>>print  emp[1] ,” working department is: ”,emp[2]
 # Mr.Visa working department is sales

Update list values

# Modify sales department in to PRODUCTION

# we can modify list values through index

Syntax :-  

listname[index]= “updated value”

>>>emp[2]=”PRODUCTION”  
>>>print   emp[1] ,”Current working department is:”,emp[2]
Mr.Visa Current working department is PRODUCTION

Find the size of list

  • Use len() function to display the total number of elements in the list.
>>>a1=[ 10,20,’data’,’/etc/passwd’,’10.20.30.40’ ]
>>>print  len(a1)  
5
  • Re-cap len() we used in string to count the number of characters
>>>print  len(“Ab”)
2

Delete List Elements

  •  To remove a list element, you can use the del() function

Syntax:- del(listname)

Example:-

>>>a1=[ 10,20,’data’,’/etc/passwd’,’10.20.30.40’ ]
>>>print  a1
[ 10,20,’data’,’/etc/passwd’,’10.20.30.40’ ]
>>>print len(a1)
 5
>>>del(a1) # delete a list name
>>>a2= [ ‘data1’,’data2’,’data3’ ]
           #    0th         1st         2nd    index
>>>print  “Total no.of elements :”, len(a2)  
Total no.of elements: 3
>>>del(a2[1])  # delete 1st index data
>>>print  “Total no.of elements :”, len(a2)
Total no.of elements: 2

Basic List operations

  • List respond to the + and * operators much like strings; + Operator is used for list concatenation and * is used for list repetition operators .
>>>L1=[‘data1’,’data2’,’data3’]
>>>L2=[10, 20, 30]
>>>L1+ L2
[ ‘data1’, ’data2’, ’data3’ ,10 ,20 ,30 ]
>>>L1*3
[‘data1’,’data2’,’data3’, ‘data1’, ’data2’,’data3’, ‘data1’, ’data2’,’data3’]

Membership operators with list

>>>L1=[‘data1’,’data2’,’data3’]
>>> ‘data1’  in  L1   # test  data1 is placed in the given list (L1) 
True
>>> ‘dataX’  in  L1  # test dataX is placed in the given list( L1) 
False
>>> ‘data1’ not in L1
False
>>> ‘dataX’ not in L1  # test dataX is not placed in the given list
True

List Based Method

Syntax:-   sorted(list)          #  displays sorted order of elements

>>>sh=[”expect”,”csh”,”tcsh”,”bash”]
>>>sorted(sh)  
bash ,csh ,expect,tcsh  

Syntax:- 

cmp(list1,list2)          #compares corresponding elements of two lists.

list1 – This is the first list to be compared.

list2 – This is the second list to be compared.

  • If elements are of the same type, perform the compare and return the result.
  • If elements are different types, check to see if they are numbers.
  • If numbers, perform numeric coercion if necessary and compare.
  • If either element is a number, then the other element is “larger” (numbers are “smallest”).
  • Otherwise, types are sorted alphabetically by name.
l1=[‘a’,’b’]
l2=[‘a’,’b’]
l3=[‘A’,’b’]
cmp(l1,l2)  ==> 0
cmp(l1,l3) ==> 1
cmp(l3,l1)   ==> -1

Syntax:- 

len(list)          #returns the number of items in list

list – list for which number of elements is to be counted.

l1=[‘data1’,’data2’,’data3’]
print  “Total no.of elements:”,len(l1)  ==> Total no.of elements: 3

Syntax:-

 max(list)          #returns the elements from the list with maximum value.

L1=[10,20,330,500,25]
print max(L1) ==> 500

Syntax:- 

min(list)          # returns the elements from the list with minimum value.

L1=[10,20,330,500,25]
print min(L1) ==> 10

List methods

  • To get list of methods type help() function with  argument as a list
>>> help(list)

The method append() appends a passed data into the existing list.

Syntax:-

list.append (data)

>>>sh=[‘/bin/sh’, ‘/bin/bash’,’/usr/bin/tcsh’]
>>>sh.append(‘/usr/bin/perl’)  # adding “/usr/bin/perl”  to  existing list

This method does not return any value but updates existing list.

>>> sh=[‘/bin/sh’, ‘/bin/bash’,’/usr/bin/tcsh’]

>>> sh.append(‘/usr/bin/perl’)  # adding “/usr/bin/perl”  to  existing list
>>> sh
[ ‘/bin/sh’, ‘/bin/bash’,’/usr/bin/tcsh’,’/usr/bin/perl’ ]
  • The method count() returns count of how many times data occurs in list.

Syntax:-

List.count(‘data’)

>>>L1=[‘unix’,’linux’,’unix’,’aix’,’linux’,’winx’]
>>>print L1.count(‘linux’)  
2
>>>print L1.count(‘winx’)
1
  • The method extend() appends the contents of seq to list

Syntax :-

List.extend(seq)  where  Seq is collection of elements 

L1=[‘unix’,’linux’,’aix’]
L2=[‘data1’,’data2’]
L1.extend(L2)
print “Extended List :”, L1
Extended List :[ ‘unix’,’linux’,’aix’,’data1’,’data2’]
L3=[‘unix’,’linux’,’aix’]
print “Extend list:”, L3.extend(“ABC”)
Extend list: [‘unix’,’linux’,’aix’,’A’,’B’,’C’]
  • The method index() returns the lowest index in list where data appears

Syntax:-

List.index(data)
  • This method returns index of the found object otherwise raises an exception indicating that value does not found.
>>>L1=[‘unix’,’linux’,’aix’]
>>>print L1.index(‘linux’)
1
  • The method insert() inserts object data into list at offset index.

Syntax:-

List.insert(index,data)

index – This is the Index where the object obj need to be inserted.

data – This is the data to be inserted into the given list

  • This method does not return any value but it inserts the given element at the given index.
L1=[‘unix’,’linux’,’aix’]
L1.insert(2,”SOLARIS”)
>>> L1
[‘unix’,’linux’,’SOLARIS’,’aix’]
  • The method pop() removes and returns last data  from the list.

Syntax:-

List.pop()
List.pop(data)
=>   This method returns the removed object from the list.
L1=[‘unix’,’linux’,’aix’,’solaris’,’winx’]
>>> L1.pop()
‘winx’
>>> L1.pop(2)
‘aix’
  • This method remove() does not return any value but removes the given object from the list.

Syntax:-

List.remove(data)
L1=[‘unix’,’linux’,’aix’,’solaris’,’winx’]
L1.remove(‘linux’) # remove linux element from L1 list
  • The method reverse() does not return any value but reverse the given object in the list.

Syntax:- List.reverse()


>>> L1=[‘unix’,’linux’,’aix’,’solaris’,’winx’]
>>> L1.reverse()
>>> L1
[‘winx’,’solaris’,’aix’,’linux’,’unix’]
  • The method sort() sorts objects of the list

Syntax:-

List.sort()

  • This method does not return any value but it changes the original list
  • Compare sorted() function returns the list of data in sorted order but keeps the original values unchanged
>>>L1.sort()
>>>L1
[‘aix’,’linux’,’solaris’,’unix’,’winx’]

Tuple

  • Python tuple  is a collection of data like array in Perl, shell script, ruby
  • Here data are not strictly of same type. It’s not like C – array
  • Data in side list are ordered elements (index based) like list
  • Unlike List, Tuple is a sequence of immutable elementsmeans that tuple elements cannot be updated or modified.
  • Like List, tuple have methods that allow you only to perform manipulation on the values inside them. 
  • Python tuple elements are separated by comma
  • Tuple elements are enclosed by parentheses

How to create a tuple?

Syntax:-

tuplename= ( data1, data2, data3, data4,data5….dataN  )
db=(  “oracle” , “sql”,”mysql”,”DB2”,”sqlite” )
|__ tuple name
>>> type(db)

Print elements of tuple

>>> print db
(“oracle” , “sql”, “mysql”, “DB2”,”sqlite”)

Accessing Single data from the Tuple

Syntax:-

Tuplename[index]

>> db=(“oracle” , “sql”, “mysql”, “DB2”,”sqlite”)
#print  1st index data from tuple
print db[1]  => like list 'sql'
print db[2:]  => from 2nd index to list of all  (‘mysql’,’DB2’,’sqlite’)

Basic Tuple operation

Syntax:-

tuplename.count (Value) 

# return integer total number of occurrence of a given value.
db=(‘oracle’,’sql’,’oralce’,’mysql’)
db.count(‘oracle’)  ==>  2

Syntax:-

len(tuplename)

db=(“oracle” , “sql”, “mysql”, “DB2”,”sqlite”)
print “Total no.of DB’s :”,len(db)  
# Total no.of DB’s : 5
  • Removing individual tuple elements is not possible.
  • append () or insert() is not used in tuple.
  • We can’t modify single data from tuple
  • Like List, Tuple supports min() , max() cmp() functions.
  • tuple(seq) –  Converts a list into tuple.
  • list(seq) –Converts a tuple into list 

Advantages of Tuple over List

  1. Since, tuples are quite similar to lists; both of them are used in similar situations as well.
  2. However, there are certain advantages of implementing a tuple over a list.
  3. Below listed are some of the main advantages
    1. Since tuple are immutable, iterating through tuple is faster than with list. So there is a slight performance boost.
    2. Tuples that contain immutable elements can be used as key for a dictionary. With list, this is not possible.
    3. If you have data that doesn’t change, implementing it as tuple will guarantee that it remains write-protected.

Reference

https://www.python.org/

Continue exploring at Teknonauts.com

]]>
https://teknonauts.com/python-programming-03/feed/ 0
#26 Python Programming – Input-Output statements & Operators P02 https://teknonauts.com/python-programming-02/ https://teknonauts.com/python-programming-02/#respond Sat, 05 Jun 2021 16:34:00 +0000 https://teknonauts.com/?p=4136

Till now you know the basics of Python programming and able to make simple program. Now lets go little more deeper and understand Input & Output statements

Input and Output statement

The usage of input statement depends on the Python version being used.

Python 3 . x (Input)

  • The input() function is used to get input from STDIN which usually returns String type of data.
  •  In the case of numerical input, perform an additional step of typecasting it using int() or float() function.

Syntax

var=input(“Prompt”)

Example :-

>>> x = input (“Enter X value : “)
Enter X value : 12
>>>x
‘12’ # Note the quotes enclosing the value referring string type data
>>>type(x)
>>>x = int ( input (“Enter X value : “))
Enter X value : 10
>>>x
10 # Numerical data-displayed without quotes
>>>type(x)

Python 2. x (Input)

  •  An older version of Python where in addition to the input () method, we have raw_input() to get input from STDIN.
  •  The input() in Python 2. x is slightly different from that in Python 3. x.
  • Here the input() returns the numerical type of data. Otherwise, syntax and usage are the same.
  •   raw_input() returns string type of data.

Syntax

var=raw_input(“Prompt”)
Example
>>>y = input ( “Enter y : ”)
Enter y : 12
>>>type(y)
>>>x= raw_input (“Enter x : “)
Enter x : hai
>>x
‘hai’
>>>type(x)

Print statement 

  • The usual way of displaying text to the STDOUT is print method. This is very similar to the printf statement in C language.
  •  The usage of format specifier (%) in print method is similar to C style coding.
>>> print(“s”  %(“Hai”))
Hai  # we tell format specifier that 10 characters are expected.
 # Right formatting with white space prefixed.
>>>  print(“% -10s”  %(“Hai”))
Hai       #Left Formatting with trailing white space & width=10
  • Let us make it clearer with another print statement.
>>>  print(“% -10s”  %(“Hai”)), ; print(“All”)
#output 
Hai       All
  •   Usage of comma(,) after a print() method suppresses the newline character.
  •   Recall semicolon(;) used to concatenate multiple statement on single line.
  •   Note the above way of comma usage works only in Python 2.x versions & not in Python 3.x.

format( ) method

  •  The another style of using print() method along with the usage of format().
>>>  x=3; y=5; print ( “The Total of {} and {} is {}”.format(x,y,x+y))
#output
The Total of 3 and 5 is 8

Using sys module

Other way of displaying text to the STDOUT is by using sys module

In Python 3.x, 

>>>import sys
>>>sys.stdout.write(“Ever Inspiring”)
Ever Inspiring14
>>>sys.stdout.write(“Dr.A.P.J.Abdul Kalam”)
Dr.A.P.J.Abdul Kalam20

Here, the write() method returns the text followed by its total length and a newline character.

In Python 2.x,

>>>import sys
>>>sys.stdout.write(“Ever Inspiring”)
Ever Inspiring
>>>sys.stdout.write(“Dr.A.P.J.Abdul Kalam”)
Dr.A.P.J.Abdul Kalam

Here the write() method in sys module works similar to print() except that it does not allow the trailing newline character.

Python operators

Arithmetic operators

  •   Arithmetic operators
  •  Python supports arithmetic operations like addition (+), multiplication (*), division (/), subtractions (), modulus( %), exponent (**) and floor division  (//).

Example:-

>>>x = 30
>>>y = 80
>>>total = x + y
>>>print(total)
110
>>>2**3
8
>>>20//3
6
>>>-20/3
-7

Relational operators

  •   The following are some relational operators used to perform comparisons.
  •    ==, != (or) <>, <, >, <=, >= . These operators return Boolean values ( True / False ).
>>>a= int( input(“Enter A : ”))
Enter A : 12
>>>b= int( input(“Enter B : ”))
Enter B : 3
>>>a != b
True
>>>a <> b
True
>>>a == b
False

Logical operators

  • Logical operators includes andornot
>>> (a != b) and (a>b )
True
>>>not(a <> b)
False

Bitwise operators

  • Performs bit by bit operation

Consider A=5, B=10

A= 0000 0101 (5)

B= 0000 1010 (10)

A&B   = 0000 0000 (0) # copies bit if bit in both the operands are set.

A|B      = 0000 1111 (15)   # copies bit if bit in any of the operands are set.

~A  = 1111 1010 (10) # one’s complement

A<<2> (20)  # Binary left shift

A>>2   = 0000 0001 (1)   # Binary right shift

Python Identity Operators

Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location:

is –> Returns True if both variables are the same object . Example : x is y

is not–> Returns True if both variables are not the same object. Example : x is not y

Python Membership Operators

Membership operators are used to test if a sequence is presented in an object:

in –> Returns True if a sequence with the specified value is present in the object. Example : x in y

not in –> Returns True if a sequence with the specified value is not present in the object. Example : x not in y

Reference

https://www.python.org/

https://www.anaconda.com/

Continue exploring at Teknonauts.com

]]>
https://teknonauts.com/python-programming-02/feed/ 0
#25 Python Programming – Setting up system P01 https://teknonauts.com/python-programming-01/ https://teknonauts.com/python-programming-01/#respond Fri, 04 Jun 2021 21:34:00 +0000 https://teknonauts.com/?p=4069

If you are just starting your journey as a Programmer, then I highly recommend you to start with Python. Here are some reason-

Why you should Learn Python

  • First of all, Python is an easy-to-learn, interpreted programming language.
  • Furthermore, it has efficient high-level data structures, which allow you to write complex operations in fewer statements than in C, C++, or Java.
  • Object-oriented programming is a lot easier than in languages like Java. 
  • Python has become one of the most popular programming languages among developers and programmers because of its Interactive and Extendable features. They praise it for its clean syntax and code readability.
  • Python is a general-purpose, high-level programming language.
  • Python is both object-oriented and imperative and it can be even used in a functional style as well.
  • Python programs are portable, i.e. they can be ported to other operating systems like  Windows, Linux, Unix, and  Mac OS X, and they can be run on Java and .NET virtual machines. 
  • Emerging technologies like AI, ML, and Data Science are mostly developed using Python

A Brief History of Python

  • Invented in the Netherlands, the early 90s by Guido van Rossum
  • Named after Monty Python
  • Open-sourced from the beginning
  • Considered a scripting language, but is much more
  • Scalable, object-oriented and functional from the beginning
  • Used by Google from the beginning
  • Increasingly popular

Python’s Benevolent Dictator For Life

“Python is an experiment in how  much freedom program-mers need.  Too much freedom and nobody can read another’s code; too little and expressive-ness is endangered.”       – Guido van Rossum

Guido's Personal Home Page
Guido van Rossum

Advantages of Python

  • It’s surprisingly easy to embed Python, or better the Python interpreter into C programs.
  • The Python Standard Library contains an enormous number of useful modules and is part of every standard python installation.
  • We can write python program in object-oriented and procedure style
  • Python is a dynamic type language
  • Provides interface to all major databases
  • Automatic Garbage collection
  • We can execute python in different ways

Get Started with Python

Download and install python from – https://www.python.org/

Python IDEs

 Komodo  Windows/Linux/Mac   OS X Multi-language IDE with support for Python 2.x and Python 3. Available as Komodo IDE (commercial).
 PyDev EclipseFree, open-source plugin for Eclipse — Allows Python, Jython, and IronPython editing, code-completion, debugger, refactoring, quick navigation, templates, code analysis, unittest integration, Django integration, etc.

Other popularly used IDEs are Notepad++, Spyder, Jupyter Notebook, Pycharm and Atom

Using the Python Interpreter

  • With the Python interactive interpreter, it is easy to check Python commands
  • The Python interpreter can be invoked by typing the command “python” without any parameter followed by the “return”  key at the shell prompt.
Python Prompt

Python Basic

We use the Python interpreter as a simple calculator by typing an arithmetic expression

<p>root@krosumlabs~]#  python {Enter-key}</p>
>>> 12+2
37
>>> 2.40+0.25</p>
2.65
>>> “AB”  + “SAB”    # string concatenation
ABSAB
>>> 5*3    # multiplication
15
>>>”AB”*3   # string repetition   
ABABAB
>>> 12.0 / 7 # floating point division
1.7142857142857142
>>>”AB” + 12 #Error- mixed types

  • Python follows the usual order of operation in the expression
  • The standard order of operations is expressed in the following enumeration
    • Exponents and roots
    • Multiplication and division
    • Addition and subtraction

This means that we don’t need parenthesis in the expression :3 + (2 * 4)

>>> 3 + 2 * 4
11
  • Python provides numerous built-in functions (BIFs). Of which help () provides us with the help document on the related object.
>>>help (3)
# Help on int object……
>>>help (int)
# Help on int object……
>>>help (str)
# Help on string object……
  •  Some other commonly used BIFs are  type (), max () and dir ().
>>>type (12)
>>>type(‘12’) #data within quotes are considered to be string .
>>>max(12, 3.145678, 0.2344)
12
>>>dir (10)       #returns a list of data & functions associated with the object passed, here an integer (10).
  • Usage of the semicolon as a statement terminator is optional in python. However, it can be used to concatenate multiple statements in a single line
>>> 12+3; ‘Learning Well’; 33+7.222
15
‘Learning Well’
40.222

Python Comment Lines

Single Line Comments

  • Typically, you just use the # (pound) sign to comment out everything that follows it on that line.
>>> print("Not a comment")
       Not a comment
>>> # print("Am a comment")  # one line comment
>>>  import  os  #  loaded os module
>>>  os.system("uptime")  #  using system function display cpu load balance

Multiple Line Comments

  • Multiple line comments are slightly different
  • Simply use triple quotes before and after the part that we want to comment
  • It can be either triple single quotes (”’…….”’) or triple double quotes (“““…..”””)
'''  print("We are in a comment line")
     print ("We are still in a comment line")
'''
print("We are out of the comment")

Execute a Python script

  • Now Let us save our program in a source file
  • To save and edit programs in a file, we need an editor
  • There are lots of editors, but you should choose one, which supports syntax highlighting and indentation
  • Under Linux, you can use vi, vim, emacs, geany, gedit and umpteen others. So, after you have chosen your editor, you can input your mini script and save it as filename.py
  • The suffix .py is not really necessary under Linux but it’s good style to use it
  • But it is essential, if you want to write modules
root@krosumlabs~]#   vi  ab.py  
print  “Hello this 1st python code”
print   “There are many data structures used in python”
# this line single line comment
# python won’t read this line
‘‘‘
This is multiline comment
’’’
print  “End of the script”
( Save the program, exit from editor  ESC  :wq )
root@krosumlabs~]#   python ab.py # execute python file
Hello this 1st python code
There are many data structures used in python
End of the script

Structuring with Indentation

  • Python uses a different principle
  • Programs get structured through indentation; this means that code blocks are defined by their indentation
  • All statements with the same distance to the right belong to the same block of code,i.e. the statements within a block line up vertically
  • The block ends at a line less indented or the end of the file
  • If a block has to be more deeply nested, it is simply indented further to the right

Reference

https://www.python.org/

https://www.anaconda.com/

Continue exploring at Teknonauts.com

]]>
https://teknonauts.com/python-programming-01/feed/ 0