Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
62 views

Python Part2 New

The document provides an introduction to object-oriented programming (OOP) concepts in Python. It discusses the differences between procedural programming and OOP. The key features of OOP - classes, objects, encapsulation, inheritance, polymorphism - are explained. Various Python programs are presented to demonstrate class creation, inheritance, polymorphism, and other OOP concepts.

Uploaded by

Apurva
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views

Python Part2 New

The document provides an introduction to object-oriented programming (OOP) concepts in Python. It discusses the differences between procedural programming and OOP. The key features of OOP - classes, objects, encapsulation, inheritance, polymorphism - are explained. Various Python programs are presented to demonstrate class creation, inheritance, polymorphism, and other OOP concepts.

Uploaded by

Apurva
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 90

Adv Python Nageswarao Datatechs

INTRODUCTION TO OOPS
Procedure oriented approach

The main and sub tasks are represented by functions and procedures.
Ex: C, Pascal, FORTRAN.

Object oriented approach

The main and sub tasks are represented by classes.


Ex: C++, Java, Python.

Differences between POA and OOA

POA OOA
1. There is no code reusability. For every new task, We can create sub classes to existing classes and
the programmer needs to develop a new function. reuse them.

2. One function may call on another function. Every class is independent and hence it can be
Hence debugging becomes difficult as we have to debugged without disturbing other classes.
check every function.

3. This approach is not developed from human Developed from human being’s life and hence easy
being’s life and hence learning and using it is very to understand and handle.
difficult.
4. Programmers lose control at a particular point Suitable to handle bigger and complex projects.
when the code size is between 10,000 to 1,00,000
lines. Hence not suitable for bigger and complex
projects.

Features of OOPS
1. classes and objects
2. encapsulation
3. abstraction
4. inheritance
5. polymorphism

Classes and objects

An object is anything that really exists in the world. Object contains behavior -> attributes and actions ->
variables and methods.

A group of objects having same behavior belong to same class or category.

A class is a model for creating objects. An object exists physically but a class does not exist physically. Class also
contains variables and methods.

Def: A class is a specification of behavior of a group of objects.


Def: An object is an instance (physical form) of a class.

80
Adv Python Nageswarao Datatechs

PROGRAMS
1. Create Person class and object to it.

Self variable

‘self’ is a default variable that contains the memory address of the instance of the current class. So, we can use
‘self’ to refer to all the instance variables and instance methods.

Constructor

A constructor is a special method that is used to initialize the instance variables of a class. In the constructor, we
create the instance variables and initialize them with some starting values. The first parameter of the
constructor will be ‘self’ variable that contains the memory address of the instance.
A constructor may or may not have parameters.

Ex:
def __init__(self): # default constructor
self.name = ‘Vishnu’
self.marks = 900

Ex:
def __init__(self, n = ‘’, m=0): # parameterized constructor with 2 parameters
self.name = n
self.marks = m

PROGRAMS
2. Create Student class with parameterized constructor.

Types of variables

The variables which are written inside a class are of 2 types:

□ Instance variables
□ Class variables or Static variables

81
Adv Python Nageswarao Datatechs

Instance variables are the variables whose separate copy is created in every instance (or object). Instance
variables are defined and initialized using a constructor with ‘self’ parameter. Also, to access instance variables,
we need instance methods with ‘self’ as first parameter. Instance variables can be accessed as: obj.var

Unlike instance variables, class variables are the variables whose single copy is available to all the instances of
the class. If we modify the copy of class variable in an instance, it will modify all the copies in the other
instances. A class method contains first parameter by default as ‘cls’ with which we can access the class
variables. For example, to refer to the class variable ‘x’, we can use ‘cls.x’.

NOTE: class variables are also called ‘static variables’. class methods are marked with the decorator
@classmethod .
NOTE: instance variables can be accessed as: obj.var or classname.var

PROGRAMS
3. Demonstrate class variables and class methods.

Namespaces

A namespace represents a memory block where names are mapped (or linked) to objects. A class maintains its
own namespace, called ‘class namespace’. In the class namespace, the names are mapped to class variables.
Similarly, every instance (object) will have its own name space, called ‘instance namespace’. In the instance
namespace, the names are mapped to instance variables.

When we modify a class variable in the class namespace, its modified value is available to all instances. When
we modify a class variable in the instance namespace, then it is confined to only that instance. Its modified value
will not be available to other instances.

Types of methods

By this time, we got some knowledge about the methods written in a class. The purpose of a method is to
process the variables provided in the class or in the method. We already know that the variables declared in the
class are called class variables (or static variables) and the variables declared in the constructor are called
instance variables. We can classify the methods in the following 3 types:

□ Instance methods
(a) Accessor methods
(b) Mutator methods
□ Class methods
□ Static methods

An instance method acts on instance variables. There are two types of methods.
1. Accessor methods: They read the instance vars. They do not modify them. They are also called getter()
methods.
2. Mutator methods: They not only read but also modify the instance vars. They are also called setter() methods.

PROGRAMS
4. Create getter and setter methods for a Manager with name and salary instance variables.

Static methods

We need static methods when the processing is at class level but we need not involve the class or instances.
Static methods are used when some processing is related to the class but does not need the class or its
82
Adv Python Nageswarao Datatechs

instances to perform any work. For example, setting environmental variables, counting the number of instances
of the class or changing an attribute in another class etc. are the tasks related to a class. Such tasks are handled
by static methods. Static methods are written with a decorator @staticmethod above them. Static methods are
called in the form of classname.method().

PROGRAMS
5. Create a static method that counts the number of instances of a class.

Inner classes

Writing a class within another class is called inner class or nested class. For example, if we write class B inside
class A, then B is called inner class or nested class. Inner classes are useful when we want to sub group the data
of a class.

PROGRAMS
6. Create Dob inner class in Student outer class.

Encapsulation

Bundling up of data and methods as a single unit is called ‘encapsulation’. A class is an example for
encapsulation.

Abstraction

Hiding unnecessary data from the user is called ‘abstraction’. By default all the members of a class are ‘public’ in
Python. So they are available outside the class. To make a variable private, we use double underscore before the
variable. Then it cannot be accessed from outside of the class. To access it from outside the class, we should
use: obj._Classname__var. This is called name mangling.

PROGRAMS
7. Using name mangling, access the private variable from outside of Bank class.

Inheritance

Creating new classes from existing classes in such a way that all the features of the existing classes are available
to the newly created classes – is called ‘inheritance’. The existing class is called ‘base class’ or ‘super class’. The
newly created class is called ‘sub class’ or ‘derived class’.

Sub class object contains a copy of the super class object. The advantage of inheritance is ‘reusability’ of code.
This increases the overall performance of the organization.

Syntax: class Subclass(Baseclass):

PROGRAMS
8. Create Teacher class and use it.
9. Create Student class and use it. Use inheritance to create Student class.

Constructors in inheritance

In the previous programs, we have inherited the Student class from the Teacher class. All the methods and the
variables in those methods of the Teacher class (base class) are accessible to the Student class (sub class). The
constructors of the base class are also accessible to the sub class.

83
Adv Python Nageswarao Datatechs

When the programmer writes a constructor in the sub class, then only the sub class constructor will get
executed. In this case, super class constructor is not executed. That means, the sub class constructor is replacing
the super class constructor. This is called constructor overriding.
PROGRAMS
10. Override the constructor and method of Father class in Son’s class.

super() method

super() is a built-in method which is useful to call the super class constructor or methods from the sub class.

super().__init__() # call super class constructor


super().__init__(arguments) # call super class constructor and pass arguments
super().method() # call super class method

PROGRAMS
11. Derive Rectangle class from Square class. Access the constructor and method of super class in the sub class
using super().

Types of inheritance

There are two types:


1. Single inheritance: deriving sub class from a single super class.
Syntax: class Subclass(Baseclass):

2. Multiple inheritance: deriving sub class from more than one super class.
Syntax: class Subclass(Baseclass1, Baseclass2, … ):

NOTE: ‘object’ is the super class for all classes in Python.

PROGRAMS
12. Derive Child class from both Father and Mother class.

Polymorphism

poly + morphos = many + forms


If something exists in various forms, it is called ‘Polymorphism’. If an operator or method performs various tasks,
it is called polymorphism.

Ex:
Duck typing: Calling a method on any object without knowing the type (class) of the object.
Operator overloading: same operator performing more than one task.
Method overloading: same method performing more than one task.
Method overriding: executing only sub class method in the place of super class method.

PROGRAMS
13. Example of how to call a method on various objects.
14. Show how + operator can be overloaded.
15. Write a method to perform sum of two or three numbers.
16. Override base class method in sub class.

84
Adv Python Nageswarao Datatechs

ABSTRACT CLASSES AND INTERFACES


An abstract method is a method whose action is redefined in the sub classes as per the requirement of the
objects. Generally abstract methods are written without body since their body will be defined in the sub classes

anyhow. But it is possible to write an abstract method with body also. To mark a method as abstract, we should
use the decorator @abstractmethod. On the other hand, a concrete method is a method with body.

An abstract class is a class that generally contains some abstract methods. PVM cannot create objects to an
abstract class.
Once an abstract class is written, we should create sub classes and all the abstract methods should be
implemented (body should be written) in the sub classes. Then, it is possible to create objects to the sub classes.

A meta class is a class that defines the behavior of other classes. Any abstract class should be derived from the
meta class ABC that belongs to ‘abc’ module. So import this module, as:

from abc import ABC, abstractmethod


(or) from abc import *

PROGRAMS
17. A program to create abstract class and sub classes which implement the abstract method of the abstract
class.

Interfaces in Python

We learned that an abstract class is a class which contains some abstract methods as well as concrete methods
also. Imagine there is a class that contains only abstract methods and there are no concrete methods. It
becomes an interface. This means an interface is an abstract class but it contains only abstract methods. None
of the methods in the interface will have body. Only method headers will be written in the interface. So an
interface can be defined as a specification of method headers. Since, we write only abstract methods in the
interface, there is possibility for providing different implementations (body) for those abstract methods
depending on the requirements of objects. In Python, we have to use abstract classes as interfaces.

Since an interface contains methods without body, it is not possible to create objects to an interface. In this
case, we can create sub classes where we can implement all the methods of the interface. Since the sub classes
will have all the methods with body, it is possible to create objects to the sub classes. The flexibility lies in the
fact that every sub class can provide its own implementation for the abstract methods of the interface.

PROGRAMS
18. Create an interface that connects to any database.

EXCEPTIONS
An exception is a runtime error which can be handled by the programmer. That means if the programmer can
guess an error in the program and he can do something to eliminate the harm caused by that error, then it is
called an ‘exception’. If the programmer cannot do anything in case of an error, then it is called an ‘error’ and
not an exception.

All exceptions are represented as classes in Python. The exceptions which are already available in Python are
called ‘built-in’ exceptions. The base class for all built-in exceptions is ‘BaseException’ class. From BaseException

85
Adv Python Nageswarao Datatechs
class, the sub class ‘Exception’ is derived. From Exception class, the sub classes ‘StandardError’ and ‘Warning’
are derived.

All errors (or exceptions) are defined as sub classes of StandardError. An error should be compulsorily handled
otherwise the program will not execute. Similarly, all warnings are derived as sub classes from ‘Warning’ class. A

warning represents a caution and even though it is not handled, the program will execute. So, warnings can be
neglected but errors cannot be neglected.

Just like the exceptions which are already available in Python language, a programmer can also create his own
exceptions, called ‘user-defined’ exceptions. When the programmer wants to create his own exception class, he
should derive his class from ‘Exception’ class and not from ‘BaseException’ class. In the Figure, we are showing
important classes available in Exception hierarchy.

Exception handling

The purpose of handling the errors is to make the program robust. The word ‘robust’ means ‘strong’. A robust
program does not terminate in the middle. Also, when there is an error in the program, it will display an
appropriate message to the user and continue execution. Designing the programs in this way is needed in any
software development. To handle exceptions, the programmer should perform the following 3 tasks:

Step 1: The programmer should observe the statements in his program where there may be a possibility of
exceptions. Such statements should be written inside a ‘try’ block. A try block looks like as follows:

try:
statements

The greatness of try block is that even if some exception arises inside it, the program will not be terminated.
When PVM understands that there is an exception, it jumps into an ‘except’ block.
86
Adv Python Nageswarao Datatechs

Step 2: The programmer should write the ‘except’ block where he should display the exception details to the
user. This helps the user to understand that there is some error in the program. The programmer should also
display a message regarding what can be done to avoid this error. Except block looks like as follows:

except exceptionname:
statements # these statements form handler

The statements written inside an except block are called ‘handlers’ since they handle the situation when the
exception occurs.

Step 3: Lastly, the programmer should perform clean up actions like closing the files and terminating any other
processes which are running. The programmer should write this code in the finally block. Finally block looks like
as follows:

finally:
statements

The specialty of finally block is that the statements inside the finally block are executed irrespective of whether
there is an exception or not. This ensures that all the opened files are properly closed and all the running
processes are properly terminated. So, the data in the files will not be corrupted and the user is at the safe-side.

PROGRAMS
19. A program to handle ZeroDivisionError exception.

However, the complete exception handling syntax will be in the following format:

try:
statements
except Exception1:
handler1
except Exception2:
handler2
else:
statements
finally:
statements

‘try’ block contains the statements where there may be one or more exceptions. The subsequent ‘except’ blocks
handle these exceptions. When ‘Exception1’ occurs, ‘handler1’ statements are executed. When ‘Exception2’
occurs, ‘hanlder2’ statements are executed and so forth. If no exception is raised, the statements inside the
‘else’ block are executed. Even if the exception occurs or does not occur, the code inside ‘finally’ block is always
executed. The following points are noteworthy:

□ A single try block can be followed by several except blocks.


□ Multiple except blocks can be used to handle multiple exceptions.
□ We cannot write except blocks without a try block.
□ We can write a try block without any except blocks.
□ else block and finally blocks are not compulsory.
□ When there is no exception, else block is executed after try block.
□ finally block is always executed.

87
Adv Python Nageswarao Datatechs
Types of exceptions

There are several exceptions available as part of Python language that are called built-in exceptions. In the same
way, the programmer can also create his own exceptions called user-defined exceptions. The following table
summarizes some important built-in exceptions in Python. Most of the exception class names end with the word
‘Error’.

Exception class name Description


Exception This represents any type of exception. All exceptions are sub classes of this
class.
ArithmeticError The base class for arithmetic errors like OverflowError, ZeroDivisionError,
FloatingPointError.
AssertionError Raised when an assert statement gives error.
AttributeError Raised when an attribute reference or assignment fails.
EOFError Raised when input() function reaches end of file condition without reading
any data.
FloatingPointError Raised when a floating point operation fails.
GeneratorExit Raised when generator’s close() method is called.
IOError Raised when an input or output operation failed. It raises when the file
opened is not found or when writing data disk is full.
ImportError Raised when an import statement fails to find the module being imported.
IndexError Raised when a sequence index or subscript is out of range.
KeyError Raised when a mapping (dictionary) key is not found in the set of existing
keys.
KeyboardInterrupt Raised when the user hits the interrupt key (normally Control-C or Delete).
NameError Raised when an identifier is not found locally or globally.
NotImplementedError This exception is derived from ‘RuntimeError’. In user defined base classes,
abstract methods should raise this exception when they require derived
classes to override the method.
OverflowError Raised when the result of an arithmetic operation is too large to be
represented. This cannot occur for long integers (which would rather raise
‘MemoryError’)
RuntimeError Raised when an error is detected that doesn’t fall in any of the other
categories.
StopIteration Raised by an iterator’s next() method to signal that there are no more
elements.
SyntaxError Raised when the compiler encounters a syntax error. Import or exec
statements and input() and eval() functions may raise this exception.
IndentationError Raised when indentation is not specified properly.
SystemExit This exception is raised by the sys.exit() function. When it is not handled,
the Python interpreter exits.
TypeError Raised when an operation or function is applied to an object of
inappropriate datatype.
UnboundLocalError Raised when a reference is made to a local variable in a function or
method, but no value has been bound to that variable.
ValueError Raised when a built-in operation or function receives an argument that has
right datatype but wrong value.
ZeroDivisionError Raised when the denominator is zero in a division or modulus operation.

PROGRAMS
20. To handle syntax error given by eval() function.

88
Adv Python Nageswarao Datatechs
assert statement

assert statement is useful to ensure that a given condition is True, otherwise to raise AssertionError. The syntax
is as follows:

assert condition, message

If the condition is False, then the exception by the name AssertionError is raised along with the ‘message’
written in the assert statement. If ‘message’ is not given in the assert statement, and the condition is False, then
also AssertionError is raised without message.

PROGRAMS
21. To raise AssertionError if the user input is not in between 5 and 10.

User- defined exceptions

Like the built-in exceptions of Python, the programmer can also create his own exceptions which are called
‘User- defined exceptions’ or ‘Custom exceptions’. The programmer should follow the steps:

1. Since all exceptions are classes, the programmer is supposed to create his own exception as a class. Also, he
should make his class as a sub class to the in-built ‘Exception’ class.

class MyException(Exception):

def __init__(self, arg):


self.msg = arg

Here, ‘MyException’ class is the sub class for ‘Exception’ class. This class has a constructor where a variable
‘msg’ is defined. This ‘msg’ receives a message passed from outside through ‘arg’.

2. The programmer can write his code; maybe it represents a group of statements or a function etc. When the
programmer suspects the possibility of exception, he should raise his own exception using ‘raise’ statement as:

raise MyException(‘message')

Here, raise statement is raising MyException class object that contains the given ‘message’.

3. The programmer can insert the code inside a ‘try’ block and catch the exception using ‘except’ block as:

try:
code
except MyException as me:
print(me)

Here, the object ‘me’ contains the message given in the raise statement.

PROGRAMS
22. To raise AssertionError if the user input is not in between 5 and 10.

Logging the exceptions

89
Adv Python Nageswarao Datatechs
It is a good idea to store all the error messages raised by a program into a file. The file which stores the
messages, especially of errors or exceptions is called a ‘log’ file and this technique is called ‘logging’. Logging
helps in debugging the programs. Python provides a module ‘logging’ that is useful to create a log file.

There may be different levels of error messages which are shown in the table below:

Level Numeric value Description


CRITICAL 50 Represents a very serious error that needs high attention.
ERROR 40 Represents a serious error.
WARNING 30 A warning message, some caution is needed.
INFO 20 A message with some important information.
DEBUG 10 A message with debugging information.
NOTSET 0 The level is not set.

Some important steps in logging are discussed now. First we have to create a file for logging (storing) the
messages. This is done using basicConfig() method of logging module, as:

logging.basicConfig(filename=’mylog.txt’, level=logging.ERROR)

Here, the log file name is given as ‘mylog.txt’. The level is set to ERROR. Hence the messages whose level will be
at ERROR or above, (i.e. ERROR or CRITICAL) will only be stored into the log file. Once, this is done, we can add
the messages to the ‘mylog.txt’ file, as:

logging.methodname(‘message’)

The methodnames can be critical(), error(), warning(), info() and debug(). For example, we want to add a critical
message, we should use critical() method, as:

logging.critical(‘System crash - Immediate attention required’)

Now, this error message is stored into the log file, i.e. ‘mylog.txt’.

PROGRAMS
23. A program that creates a log file with errors and critical messages.
24. To store the messages released by any exception into a log file.

FILES IN PYTHON
A file represents storage of data. A file stores data permanently so that it is available to all the programs.

Types of files in Python

In Python, there are 2 types of files. They are:

□ Text files
□ Binary files

Text files store the data in the form of characters. For example, if we store employee name “Ganesh”, it will be
stored as 6 characters and the employee salary 8900.75 is stored as 7 characters. Normally, text files are used to
store characters or strings.

90
Adv Python Nageswarao Datatechs
Binary files store entire data in the form of bytes, i.e. a group of 8 bits each. For example, a character is stored
as a byte and an integer is stored in the form of 8 bytes (on a 64 bit machine). When the data is retrieved from
the binary file, the programmer can retrieve the data as bytes. Binary files can be used to store text, images,
audio and video.

Opening a file

We should use open() function to open a file. This function accepts ‘filename’ and ‘open mode’ in which to open
the file.

file handler = open(“file name”, “open mode”, “buffering”)


Ex: f = open(“myfile.txt”, “w”)

Here, the ‘file name’ represents a name on which the data is stored. We can use any name to reflect the actual
data. For example, we can use ‘empdata’ as file name to represent the employee data. The file ‘open mode’
represents the purpose of opening the file. The following table specifies the file open modes and their
meanings.

File open mode Description


w To write data into file. If any data is already present in the file, it
would be deleted and the present data will be stored.
r To read data from the file. The file pointer is positioned at the
beginning of the file.
a To append data to the file. Appending means adding at the end of
existing data. The file pointer is placed at the end of the file. If the
file does not exist, it will create a new file for writing data.
w+ To write and read data of a file. The previous data in the file will be
deleted.
r+ To read and write data into a file. The previous data in the file will
not be deleted. The file pointer is placed at the beginning of the
file.
a+ To append and read data of a file. The file pointer will be at the end
of the file if the file exists. If the file does not exist, it creates a new
file for reading and writing.
x Open the file in exclusive creation mode. The file creation fails if
the file already exists.

The above Table represents file open modes for text files. If we attach ‘b’ for them, they represent modes for
binary files. For example, wb, rb, ab, w+b, r+b, a+b are the modes for binary files.

A buffer represents a temporary block of memory. ‘buffering’ is an optional integer used to set the size of the
buffer for the file. If we do not mention any buffering integer, then the default buffer size used is 4096 or 8192
bytes.

Closing a file

A file which is opened should be closed using close() method as:


f.close()

91
Adv Python Nageswarao Datatechs
Files with characters

To write a group of characters (string), we use: f.write(str)


To read a group of characters (string), we use: str = f.read()

PROGRAMS
25. Create a file and store a group of chars.
26. Read the chars from the file.

Files with strings

To write a group of strings into a file, we need a loop that repeats: f.write(str+”\n”)
To read all strings from a file, we can use: str = f.read()

PROGRAMS
27. Create a file and store a group of strings.
28. Read the strings from the file.

Knowing whether a file exists or not

The operating system (os) module has a sub module by the name ‘path’ that contains a method isfile(). This
method can be used to know whether a file that we are opening really exists or not. For example,
os.path.isfile(fname) gives True if the file exists otherwise False. We can use it as:

if os.path.isfile(fname): # if file exists,


f = open(fname, 'r') # open it
else:
print(fname+' does not exist')
sys.exit() # terminate the program

PROGRAMS
29. Check if the file exists or not and then read the strings from the file.

with statement

‘with’ statement can be used while opening a file. The advantage of with statement is that it will take care of
closing a file which is opened by it. Hence, we need not close the file explicitly. In case of an exception also,
‘with’ statement will close the file before the exception is handled. The format of using ‘with’ is:

with open(“filename”, “openmode”) as fileobject:

Ex: writing into a flie


# with statement to open a file
with open('sample.txt', 'w') as f:
f.write('Iam a learner\n')
f.write('Python is attractive\n')

Ex: reading from a file


# using with statement to open a file
with open('sample.txt', 'r') as f:
for line in f:
print(line)

92
Adv Python Nageswarao Datatechs
Pickle in Python

Pickle is a process of converting a class object into a byte stream so that it can be stored into a file. This is also
called object serialization. Pickling is done using dump() method of ‘pickle’ module as:

pickle.dump(object, file)

The preceding statement stores the ‘object’ into the binary ‘file’. Once the objects are stored into a file, we can
read them from the file at any time. Unpickle is a process whereby a byte stream is converted back into a class

object. It means, unpickling represents reading the class objects from the file. Unpickling is also called de-
searialization. Unpickling is done using load() method of ‘pickle’ module as:

object = pickle.load(file)

Here, load() method reads an object from a binary ‘file’ and returns it into ‘object’. Let us remember that
pickling and unpickling should be done using binary files since they support byte streams. The word stream
represents data flow. So, byte stream represents flow of bytes.

PROGRAMS
30. Store Emp class objects into emp.dat file using pickle.
31. Read Emp class objects from emp.dat file and display the contents.

seek() and tell() methods

We know that data in the binary files is stored in the form of bytes. When we conduct reading or writing
operations on a binary file, a file pointer moves inside the file depending on how many bytes are written or read
from the file. For example, if we read 10 bytes of data from a file, the file pointer will be positioned at the 10 th
byte so that it is possible to continue reading from the 11th byte onwards. To know the position of the file
pointer, we can use tell() method. It returns the current position of the file pointer from the beginning of the
file. It is used in the form:

n = f.tell()

Here, ‘f’ represents file handler or file object. ‘n’ is an integer that represents the byte position where the file
pointer is positioned.

In case, we want to move the file pointer to another position, we can use seek() method. This method takes two
arguments:

f.seek(offset, fromwhere)

Here, ‘offset’ represents how many bytes to move. ‘fromwhere’ represents from which position to move. For
example, ‘fromwhere’ can be 0, 1 or 2. Here, 0 represents from the beginning of the file, 1 represents from the
current position and 2 represents from the ending of the file. The default value of ‘fromwhere’ is 0, i.e.
beginning of the file.

f.seek(10) # same as f.seek(10, 0)

This will move the file pointer to the 11th byte (i.e. 10+1) from the beginning of the file (0 represents beginning
of the file). So, any reading operation will read data from 11th byte onwards.

93
Adv Python Nageswarao Datatechs
f.seek(-10, 2)

This will move the file pointer to the 9th byte (-10+1) from the ending of the file (2 represents ending of the file).
The negative sign before 10 represents moving back in the file.

We will take an example to understand how these methods work in case of a binary file. Observe the following
code snippet where we open a binary file ‘line.txt’ in ‘r+b’ mode so that it is possible to write data into the file
and read data from the file.

with open('line.txt', 'r+b') as f:

f.write(b'Amazing Python')

The file object is ‘f’. The write() method is storing a string 'Amazing Python' into the file. Observe ‘b’ prefixed
with this string to consider it as a binary string. Now, the string is stored in the file as shown in the following
Figure.

First, we will move the file pointer to the 4th byte using seek() as:

f.seek(3)

The preceding method will put the file pointer at 3+1 = 4th position. So, file pointer will be at ‘z’. If we print 2
bytes using read() method as:

print(f.read(2))

This will display ‘zi’. Now, to know the position of the file pointer we can use tell() method as:

print(f.tell())

This will display 5. Now, to move the file pointer to 5th position from the ending of the file, we can use seek()
method as:

f.seek(-6, 2)

This will move the file pointer to -6+1 = 5th position. It means it will be positioned at the character ‘y’. We can
display this character using read() method as:

print(f.read(1))

This will display ‘y’. Now, we can find the position of the file pointer using tell() method, as:

print(f.tell())

This will display 10 as the character ‘y’ is at 10th position from the beginning of the file. Please remember the
tell() method always gives the positions from the beginning of the file.

94
Adv Python Nageswarao Datatechs

Random accessing of binary files

Data in the binary files is stored in the form of continuous bytes. Let us take a binary file having 1000 bytes of
data. If we want to access the last 10 bytes of data, it is not needed to search the file byte by byte from the
beginning. It is possible to directly go to 991st byte using seek() method as:

f.seek(900)

Then read the last 10 bytes using read() method as:

f.read(10)

In this way, directly going to any byte in the binary file is called random accessing. This is possible by moving the
file pointer to any location in the file and then performing reading or writing operations on the file as required.

A problem with binary files is that they accept data in the form of bytes or in binary format. For example, if we
store a string into a binary file, as shown in the following statement, we will end up with an error.

str = 'Dear'
with open('data.bin', 'wb') as f:
f.write(str) # store str
f.write('Hello') # store ‘Hello’

TypeError: ‘str’ does not support the buffer interface.

The reason behind this error is that we are trying to store strings into a binary file without converting them into
binary format. So, the solution is to convert the ordinary strings into binary format before they are stored into
the binary file. Now observe the code:

str = 'Dear'
with open('data.bin', 'wb') as f:
f.write(str.encode())
f.write(b'Hello')

Converting a string literal into binary format can be done by prefixing the character ‘b’ before the string, as:
b'Hello'. On the other hand, to convert a string variable into binary format, we have to use encode() method, as:
str.encode().

The encode() method represents the string in byte format so that it can be stored into the binary file. Similarly,
when we read a string from a binary file, it is advisable to convert it into ordinary text format using decode()
method, as: str.decode().

PROGRAMS
32. Store a group of strings into a binary file.
33. Read first 10 bytes and then another 10 bytes and last 10 bytes in binary file.

Zipping and Unzipping files

In Python, the module zipfile contains ZipFile class that helps us to zip or unzip a file contents. For example, to
zip the files, we should first pass the zip file name in write mode with an attribute ZIP_DEFLATED to the ZipFile
class object, as:

95
Adv Python Nageswarao Datatechs
f = ZipFile('test.zip', 'w', ZIP_DEFLATED)

Here, ‘f’ is the ZipFile class object to which test.zip file name is passed. This is the zip file that is created finally.
The next step is to add the filenames that are to be zipped, using write() method, as:

f.write('file1.txt')
f.write('file2.txt')

Here, we are writing two files: file1.txt and file2.txt into the object ‘f’. Hence, these two files are compressed
and stored into test.zip file.

To unzip the contents of the compressed files and get back their original contents, we can use ZipFile class
object in read mode, as:

z = ZipFile('test.zip', 'r')

Here, test.zip is the filename that contains the compressed files. To extract all the files in original format, we
should use extractall() method as:
z.extractall()
z.extractall(directory-path) # extract to this directory

PROGRAMS
34. Zip the contents of 3 files.
35. Unzip the contents of zipped files and display them.

Running other programs from Python program

‘os’ module has system() method that is useful to run an executable program from our Python program. This
method is similar to system() function of C language. It is used as system(‘string’) where ‘string’ represents any
command or executable file name. See the following examples:

os.system('dir') # display directory contents on DOS operating system


os.system('demo.py') # run demo.py program

PROGRAMS
36. Display all the files having .py extension in the present directory.

REGULAR EXPRESSIONS
A regular expression is a string that contains special symbols and characters to find and extract the information
needed by us from the given data. A regular expression helps us to search information, match, find and split
information as per our requirements. A regular expression is also called simply regex.

Regular expressions are used to perform the following important operations:

□ Matching strings
□ Searching for strings
□ Finding all strings
□ Splitting a string into pieces
□ Replacing strings

The following methods belong to ‘re’ module that are used in the regular expressions:

96
Adv Python Nageswarao Datatechs

□ match() method searches in the beginning of the string and if the matching string is found, it returns an
object that contains the resultant string, otherwise it returns None. We can access the string from the
returned object using group() method.

□ search() method searches the string from beginning till the end and returns the first occurrence of the
matching string, otherwise it returns None. We can use group() method to retrieve the string from the
object returned by this method.

□ findall() method searches the string from beginning till the end and returns all occurrences of the
matching string in the form of a list object. If the matching strings are not found, then it returns an
empty list. We can retrieve the resultant strings from the list using a for loop.

□ split() method splits the string according to the regular expression and the resultant pieces are returned
as a list. If there are no string pieces, then it returns an empty list. We can retrieve the resultant string
pieces from the list using a for loop.

□ sub() method substitutes (or replaces) new strings in the place of existing strings. After substitution, the
main string is returned by this method.

Sequence characters in regular expressions

Sequence characters match only one character in the string. Let us list out the sequence characters which are
used in regular expressions along with their meanings in Table 1.

Character Its description


\d Any digit ( 0 to 9)
\D Any non-digit
\s White space. Ex: \t\n\r\f\v
\S Non-white space character
\w Any alphanumeric (A to Z, a to z, 0 to 9)
\W Non-alphanumeric
\b A space around words
\A Matches only at start of the string
\Z Matches only at end of the string

Each of these sequence characters represents a single character matched in the string. For example ‘\w’
indicates any one alphanumeric character. Suppose we write it as [\w+*. Here ‘*’ represents 0 or more
repetitions. Hence [\w]* represents 0 or more alphanumeric characters.

Example 1. A regular expression to search for strings starting with m and having total 3 characters using search()
method.

import re
str = 'man sun mop run'
result = re.search(r'm\w\w', str)
if result: # if result is not None
print(result.group())

Output:
97
Adv Python Nageswarao Datatechs
man

Example 2. A regular expression to search for strings starting with m and having total 3 characters using findall()
method.

import re
str = 'man sun mop run'
result = re.findall(r'm\w\w', str)
print(result)

Output:
['man', 'mop']

Example 3. A regular expression using match() method to search for strings starting with m and having total 3
characters.

import re
str = 'man sun mop run'
result = re.match(r'm\w\w', str)
print(result.group())
Output:
man

Example 4. A regular expression using match() method to search for strings starting with m and having total 3
characters.

import re
str = 'sun man mop run'
result = re.match(r'm\w\w', str)
print(result)

Output:
None

Example 5. A regular expression to split a string into pieces where one or more numeric characters are found.

impor re
str = 'gopi 2222 vinay 9988 subba rao 89898'
res = re.split(r'\d+\b', str)
print(res)
Output:
['gopi ', ' vinay ', ' subba rao ', '']

Example 6. A regular expression to replace a string with a new string.

import re
str = 'Kumbhmela will be conducted at Ahmedabad in India.'
res = re.sub(r'Ahmedabad', 'Allahabad', str)
print(res)
Output:
Kumbhmela will be conducted at Allahabad in India.

Quantifiers in regular expressions

98
Adv Python Nageswarao Datatechs
In regular expressions, some characters represent more than one character to be matched in the string. Such
characters are called ‘quantifiers’

Character Its description


+ 1 or more repetitions of the preceding regexp
* 0 or more repetitions of the preceding regexp
? 0 or 1 repetitions of the preceding regexp
{m} Exactly m occurrences
{m, n} From m to n. m defaults to 0. n to infinity.

Example7. A regular expression to find all words starting with ‘an’ or ‘ak’.

import re
str = 'anil akhil anant arun arati arundhati abhijit ankur'
res = re.findall(r'a[nk][\w]*', str)
print(res)
Output:
['anil', 'akhil', 'anant', 'ankur']
Example 8. A regular expression to retrieve date of births from a string.

import re
str = 'Vijay 20 1-5-2001, Rohit 21 22-10-1990, Sita 22 15-09-2000'
res = re.findall(r'\d{2}-\d{2}-\d{4}', str)
print(res)
Output:
['22-10-1990', '15-09-2000']

NOTE: Try the following regex in the above example:


res = re.findall(r'\d{1,2}-\d{1,2}-\d{4}', str)

Special characters in regular expressions

Characters with special significance shown in the following Table can be used in regular expressions.

Character Its description


\ Escape special character nature
. Matches any character except new line
^ Matches beginning of a string
$ Matches ending of a string
[...] Denotes a set of possible characters. Ex: [6b-d+ matches any characters ‘6’,
‘b’, ’c’ or ‘d’
[^...] Matches every character except the ones inside brackets. Ex: [^a-c6] matches
any character except ‘a’, ‘b’, ‘c’ or ‘6’
(... ) Matches the regular expression inside the parentheses and the result can be
captured.
R|S Matches either regex R or regex S

Example 9. A regular expression to search whether a given string is starting with ‘He’ or not.

import re
str = "Hello World"
res = re.search(r"^He", str)

99
Adv Python Nageswarao Datatechs
if res:
print ("String starts with 'He'")
else:
print("String does not start with 'He'")

Output:
String starts with 'He'

Retrieving information from a HTML file

Let us see how to apply regular expressions on a HTML file and retrieve the necessary information. As an
example, let us take a HTML file that contains some items for breakfast and their prices in the form of a table, as
shown here:
<! breakfast.html>
<html>
<table border=2>
<tr align="center"><td>1</td> <td>Roti</td> <td>50.00</td></tr>
<tr align="center"><td>2</td> <td>Chapatti</td> <td>55.75</td></tr>
<tr align="center"><td>3</td> <td>Dosa</td> <td>48.00</td></tr>
<tr align="center"><td>4</td> <td>Idly</td> <td>25.00</td></tr>
<tr align="center"><td>5</td> <td>Vada</td> <td>38.90</td></tr>
<tr align="center"><td>6</td> <td>Coffee</td> <td>20.00</td></tr>
<tr align="center"><td>7</td> <td>Tea</td> <td>15.00</td></tr>
</table>
</html>

When we open this file, we can see the table in the browser as shown below:

Let us assume that this file is available in our computer in the directory as: F:\py\breakfast.html. To open this
file, we have to use urlopen() method of urllib.request module in Python. So, we have to use the following code:

import urllib.request
f = urllib.request.urlopen(r'file:///f|py\breakfast.html')

Observe the raw string passed to urlopen() method. It contains the path of the .html file, as:

100
Adv Python Nageswarao Datatechs

file:///f|py\breakfast.html

The first word ‘file:///’ indicates file URL scheme that is used to refer to files in the local computer system. The
next word ‘f|py’ indicates the drive name ‘f’ and the sub directory ‘py’. In this, we have the file breakfast.html.
Once this file is open, we can read the data using read() method, as:

text = f.read()

But the data in the HTML files would be stored in the form of byte strings. Hence, we have to decode them into
normal strings using decode() method, as:

str = text.decode()

Now, we have the string ‘str’. We have to retrieve the required information from this string using a regular
expression. Suppose we want to retrieve only item name and price, we can write:

r'<td>\w+</td>\s<td>(\w+)</td>\s<td>(\d\d.\d\d)</td>'
Please observe that the preceding expression contains three special characters: the first one is a \w+, the
second one is (\w+) and the third one is (\d\d.\d\d). They are embedded in the tags <td> and </td>. So, the
information which is in between the tags is searched.

The first \w+ indicates that we are searching for a word (item number). The next \w+ is written inside
parentheses (). The parentheses represents that the result of the regular expression written inside these
parentheses will be captured. So, (\w+) stores the words (item names) into a variable and the next (\d\d.\d\d)
stores the words (item prices) into another variable. If we use findall() method to retrieve the information, it
returns a list that contains these two variables as a tuple in every row. For example, the first two values are
‘Roti’ and ’50.00’ which are stored in the list as a tuple as: [('Roti', '50.00')] .

Retrieving required data from a HTML file using regular expressions and JSON concepts is called ‘webscraping’.

PROGRAMS
37. To retrieve item name and its price from a HTML file using a regular expression.

DATE AND TIME


The epoch

‘epoch’ is the point where the time starts. This point is taken as the 0.0 hours of January 1st of the current year.
For Unix, the epoch is 0.0 hours of January 1st of 1970. It is possible to measure the time in seconds since the
epoch using time() function of ‘time’ module.

Epoch time can be converted into date and time with the help of ctime() function.

PROGRAMS
38. To know the time since the epoch.

Date and time now

The current date and time as shown in our computer system can be known using the following:

101
Adv Python Nageswarao Datatechs

□ ctime() function of ‘time’ module. Just call ctime() without passing anything.
Ex: dt = time.ctime()
□ today() method of ‘datetime’ class of ‘datetime’ module.
Ex: dt = datetime.today()
□ now() method of ‘datetime’ class of ‘datetime’ module.
Ex: dt = datetime.now()
We can retrieve individual values as: dt.day, dt.month, dt.year, dt.hour, dt.minute, dt.second.

PROGRAMS
39. To know the current date and time.

Combining date and time

We can create ‘datetime’ class object by combining date class object and time class objects using combine()
method. Please remember that the date and time classes belong to ‘datetime’ module. For example, we can
create a date class object with some date, as:

d = date(2016, 4, 29)

Similarly, we can create time class object and store some time, as:

t = datetime.time(15, 30)

Now, the combine() method is a class method in the class ‘datetime’ that can combine the previously created
objects, as:

dt = datetime.combine(d, t)

PROGRAMS
40. Enter date and time from keyboard and combine them.

Formatting dates and times

The contents of the ‘datetime’,’ date’ and ‘time’ classes objects can be formatted using strftime() method.
‘strftime’ represents ‘string format of time’. This method converts the objects into a specified format and
returns the formatted string.
dt = strftime(‘Formatted string’)

Format Meaning Example


code
%a Weekday as an abbreviated name. Sun, Mon, … Sat
%A Weekday as full name. Sunday, Monday, … Saturday
%w Weekday as a decimal number, where 0 is Sunday 0, 1, … 6
and 6 is Saturday.
%d Day of the month as a zero-padded decimal 01, 02, … 31
number.
%b Month as an abbreviated name. Jan, Feb, … Dec
%B Month as full name. January, February, … December
%m Month as zero-padded decimal number. 01, 02, … 12

102
Adv Python Nageswarao Datatechs
%y Year without century as a zero-padded decimal 00, 01, … 99
number.
%Y Year with century as decimal number. 0001, 0002, … 2016, … 9999
%H Hour (24-hour clock) as zero-padded decimal 00, 01, … 23
number.
%I Hour (12-hour clock) as a zero-padded decimal 01, 02, … 12
number.
%p Either AM or PM. AM, PM
%M Minute as a zero-padded decimal number. 00, 01, … 59
%S Second as a zero-padded decimal number. 00, 01, … 59
%f Microsecond as a decimal number, zero-padded 000000, 000001, ... 999999
on the left.
%Z Time zone name. (empty), UTC, EST, CST
%j Day of the year as a zero-padded decimal number. 001, 002, … 366
%U Week number of the year (Sunday as the first day 00, 01, … 53
of the week) as a zero padded decimal number. All
days in a new year preceding the first Sunday are
considered to be in week 0.
%W Week number of the year (Monday as the first day 00, 01, … 53
of the week) as a decimal number. All days in a
new year preceding the first Monday are
considered to be in week 0.
%c Appropriate date and time representation. Tue Aug 16 21:30:00 1988
%x Appropriate date representation. 08/16/88 (None);
08/16/1988 (en_US)

%X Appropriate time representation. 21:30:00 (en_US)


%% A single % character. %

Example 1: To display date, month name and year.

from datetime import *


dt = date.today()
str = dt.strftime('Date = %d, %B, %Y')
print(str)
Output
Date = 05, September, 2017

Example 2: To find current year’s day number and week day name.

from datetime import *


dt = date.today()
str = dt.strftime('Today is the %j th day of current year')
print(str)
str = dt.strftime('And it is %A')
print(str)
Output
Today is the 248 th day of current year
And it is Tuesday

Example 3: To format the current time and show it as HH: MM: SS.

from datetime import *


dt = datetime.now()
103
Adv Python Nageswarao Datatechs
str = dt.strftime('Current time= %H:%M:%S')
print(str)
Output
Current time= 18:49:03

Finding durations using timedelta

The ‘timedelta’ class of ‘datetime’ module is useful to find the durations like difference between two dates or
finding the date after adding a period to an existing date. It is possible to know the future dates or previous
dates using ‘timedelta’. The ‘timedelta’ class object is available in the following format:

timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

All arguments passed to the ‘timedelta’ object are optional and default to 0. Arguments may be integers or
floats, and may be positive or negative.

Example 4: Find the future date if we add 10 days, 12 hours, 30 minutes, 10 seconds to the existing date.

from datetime import *


d1 = datetime(2017, 9, 5, 6, 50, 30)
period = timedelta(days=10, hours=12, minutes=30, seconds=10)
print('New date and time = ', d1+period)
Output
New date and time = 2017-09-15 19:20:40

Comparing two dates

It is possible to compare two ‘date’ class objects or ‘datetime’ class objects just like comparing two numbers.
For example, d1 and d2 are to be compared, we can write:

d1 == d2
d1> d2
d1<d2

These expressions return either True or False.


Ex:
b1 = date(y1, m1, d1)
b2 = date(y2, m2, d2)
if b1==b2: print(‘Both persons are of same age’)

Sorting dates

One of the best ways to sort a group of dates is to store them into a list and then apply list’s sort() method.
Dates can be stored in date class object as: date(y,m,d).

PROGRAMS
41. Sort a given group of dates.

Stopping execution temporarily

To stop execution of a program temporarily for a given amount of time, we can use sleep() function of ‘time’
module. This function is used in the format:

time.sleep(2) # sleep for 2 seconds

104
Adv Python Nageswarao Datatechs
time.sleep(2.5) # sleep for 2.5 seconds

Knowing the time taken by a program

Python provides two functions: perf_counter() and process_time() of ‘time’ module to measure the time
difference between two points in a program. perf_counter() is useful to know the time taken by a program.
process_time() is useful to know the time taken by a program + CPU’s time in executing the program.

PROGRAMS
42. A Python program to find the execution time of a program.

Working with calendar module

The ‘calendar’ module is useful to create calendar for any month or year and to test whether year is leap or not.
Ex:
calendar.isleap(y) # returns True if y is leap year

str = calendar.month(2017, 9)
print(str) # displays calendar for Sep 2017
str = calendar.calendar(2017)
print(str) # displays calendar for the year 2017

THREADS
A thread represents a separate path of execution of a group of statements. In every Python program, there is a
main thread that always runs the program statements.

PROGRAMS
43. To know the thread running the Python program.

Single tasking and multi tasking

A thread represents execution of statements. The way the statements are executed is of two types: 1) Single
tasking 2) Multi tasking. In single tasking, the processor (or PVM) executes only 1 task at a time. In multi tasking,
it executes several tasks at a time. Hence we are using the processor time in a better way in multitasking.

Multitasking is of 2 types: 1) Process based multitasking and 2) Thread based multitasking. In Process-based
multi tasking, several programs are executed at a time, by the microprocessor. In Thread-based multi tasking,
several parts of the same program is executed at a time, by the microprocessor.

Concurrent programming and GIL

In Python, it is possible to create multiple processes and set them to work simultaneously. In the same way, it is
possible to create multiple threads and set them to execute different parts of the program simultaneously.
Executing the tasks or parts of a program simultaneously is called ‘concurrent programming’.

When more than one thread is running at a time, since the data of one thread is available to another thread,
there is possibility that the data may undergo unwanted manipulations. This happens especially when more
than one thread is acting on the data simultaneously. This will lead to wrong results. It means the PVM is not
thread safe. Hence, PVM uses an internal global interpreter lock (GIL) that allows only a single thread to execute
at any given moment. GIL does not allow more than one thread to run at a time. This becomes an obstacle to
write concurrent programs in Python. Even when there are many processors available in a Computer system,

105
Adv Python Nageswarao Datatechs
the programmer can use the capability of only one processor at a time due to the restriction imposed by GIL.
However GIL will not impose this restriction of using only one thread at a time, in case of normal Python
programs that take some input and provide output. GIL will impose this restriction on applications that involve
heavy amounts of CPU processing or those involving multiple processors.

Creating threads in Python

Python provides ‘Thread’ class of threading module that is useful to create threads. To create our own thread,
we are supposed to create an object of Thread class. The following are the different ways of creating our own
threads in Python:

□ Creating a thread without using a class.


t = Thread(target=functionname, *args=(arg1, arg2, …)+)
t.start()

□ Creating a thread by creating a sub class to Thread class.


class MyThread(Thread):
then override run() method of Thread class
t.start()

□ Creating a thread without creating sub class to Thread class.


Create MyThread class with display() method.
t = Thread(target=obj.display, args=(1, 2))

PROGRAMS
44. To create a thread without using a class.
45. To create a thread by making our class as sub class to Thread class.
46. To create a thread without creating sub class to Thread class.

Single tasking and multi tasking

PROGRAMS
47. Single tasking example – preparing tea.
48. Multi tasking example - theatre context.

Thread synchronization

When more than one thread acts on same object simultaneously then they may not act in the expected
sequence leading to race condition. When race condition occurs, the output will not be reliable. Race condition
can be eliminated using ‘thread synchronization’.

PROGRAMS
49. Allot the only available berth in Railway reservation to two competing passengers using 2 threads.

When a thread is already acting on an object, preventing any other thread from acting on the same object is
called ‘thread synchronization’ or ‘thread safe’. The object on which the threads are synchronized is called
‘synchronized object’ or ‘mutex’(mutually exclusive lock). Thread synchronization is recommended when
multiple threads are acting on the same object simultaneously. Thread synchronization is done using the
following techniques:

□ Using locks
□ Using semaphores

106
Adv Python Nageswarao Datatechs

Locks can be used to lock the object on which the thread is acting. When a thread enters the object, it locks the
object and after the execution is completed, it will unlock the object and comes out of it.

We can create a lock by creating an object of Lock class, as:


l = Lock()

To lock the current object, we should use acquire() method, as:


l.acquire()

To unlock or release the object, we can use release() method, as:


l.release()

PROGRAMS
50. Thread synchronization using locks.

A semaphore is an object that provides synchronization based on a counter. A semaphore is created as an object
of Semaphore class, as:

l = Semaphore(countervalue) # here the counter value by default is 1

If the ‘counter value’ is not given, the default value of the counter will be 1. When the acquire() method is
called, the counter gets decremented by 1 and when release() method is called, it is incremented by 1. These
methods are used in the following format:

l.acquire() # make counter 0 and then lock


code that is locked by semaphore
l.release() # counter is 0 so unlock and make counter 1

PROGRAMS
Rewrite Program 50 using Semaphore for Thread synchronization.
NOTE: replace self.l = Lock() by self.l = Semaphore()

Daemon threads

Sometimes, we need threads to run continuously in memory. For example, let us take an Internet server that
runs continuously and caters the needs of the clients. Another example is garbage collector that runs
continuously and deletes the unused variables and objects while a Python program is being executed. Such
threads which run continuously are called ‘daemon’ threads. Generally daemon threads are used to perform
some background tasks. We can make a thread as daemon thread by setting its property ‘daemon’ as True or by
using setDaemon() method, as:

t.daemon = True # set the property as True to make t as daemon thread


t. setDaemon(True) # make t as daemon thread

GRAPHICAL USER INTERFACE


Python offers tkinter module to create graphics programs. tkinter represents ‘toolkit interface’ for GUI.
The following are the general steps involved in basic GUI programs:

107
Adv Python Nageswarao Datatechs
1. First of all, we should create the root window. The root window is the top level window that provides
rectangular space on the screen where we can display text, colors, images, components etc.

2. In the root window, we have to allocate space for our use. This is done by creating a canvas or frame. So,
canvas and frame are child windows in the root window.

3. Generally, we use canvas for displaying drawings like lines, arcs, circles, shapes, etc. We use frame for the
purpose of displaying components like push buttons, check buttons, menus, etc. These components are also
called ‘widgets’.

4. When the user clicks on a widget like push button, we have to handle that event. It means we have to
respond to the events by performing the desired tasks.

The root window

To display the graphical output, we need space on the screen. This space that is initially allocated to every GUI
program is called ‘top level window’ or ‘root window’. We can say that the root window is the highest level GUI
component. We can reach this root window by creating an object to Tk class.

PROGRAMS
51. Create root window with a title and size.

Frame

A frame is similar to canvas that represents a rectangular area where some text or widgets can be displayed.
Our root window is in fact a frame. To create a frame, we can create an object of Frame class, as:
f= Frame(root, height=400, width=500, bg="yellow")

Once the frame is created, it should be added to the root window using pack() method, as:

f.pack()

PROGRAMS
52. Create frame with some background color and title.

Widgets

A widget is a GUI component that is displayed in the frame and can perform a task as desired by the user. All
widgets are objects. For example, a push button is a widget that is nothing but an object of Button class.
Similarly, label is a widget that is an object of Label class. Once a widget is created, it should be added to frame.
The following are important widgets in Python:

□ Button
□ Label
□ Message
□ Text
□ Scrollbar
□ Checkbutton
□ Radiobutton
□ Entry
□ Spinbox

108
Adv Python Nageswarao Datatechs
□ Listbox
□ Menu

In general, working with widgets takes the following 4 steps:

1. Create the widgets that are needed in the program. As an example, suppose we want to create a push button,
we can create an object to Button class, as:

b = Button(f, text='My Button')

Here, ‘f’ is Frame object to which the button is added. ‘My Button’ is the text that is displayed on the button.

2. When the user interacts with a widget, he will generate an event. For example, clicking on a push button is an
event. Such events should be handled by writing functions or routines. These functions are called in response to
the events. Hence they are called ‘callback handlers’ or ‘event handlers’. Other examples for events are pressing
the Enter button, right clicking the mouse button etc. As an example, let us write a function that may be called
in response to button click.

def buttonClick(self):
print('You have clicked me')

3. When the user clicks on the push button, that ‘clicking’ event should be linked with the ‘callback handler’
function. Then only the button widget will appear as if it is performing some task. As an example, let us bind the
button click with the function, as:

b.bind('<Button-1>', buttonClick)
Here, ‘b’ represents the push button. <Button-1> indicates the left mouse button. When the user presses the
left mouse button, the ‘buttonClick’ function is called as these are linked by bind() method in the preceding
code.

4. The preceding 3 steps make the widgets ready for the user. Now, the user has to interact with the widgets.
This is done by entering text from the keyboard or pressing mouse button. These are called events. These events
are continuously monitored by our program with the help of a loop, called ‘event loop’. In our programs, the
mainloop().

Button

A push button is a component that performs some action when clicked. Push buttons are created as objects of
Button class, as:

b = Button(f, text='My Button', width=15, height=2, bg='yellow', fg='blue', activebackground='green',


activeforeground='red')

We can also display an image on the button as shown in the following two steps:

# first load the image into file1


file1 = PhotoImage(file="cat.gif")

# create a push button with image


b = Button(f, image=file1, width=150, height=100, bg='yellow', fg='blue', activebackground='green',
activeforeground='red')

109
Adv Python Nageswarao Datatechs
PROGRAMS
53. To create a push button and bind it with an event handler function.

NOTE: We can eliminate bind() method and we will use ‘command’ option to link the push button with even
handler function, as:

b = Button(f, text='My Button', width=15, height=2, bg='yellow', fg='blue', activebackground='green',


activeforeground='red', command=buttonClick)

PROGRAMS
54. Rewrite the previous program to create a push button using command option and class concept.

Label widget

A label represents constant text that is displayed in the frame or container. A label can display one or more lines
of text that cannot be modified. A label is created as an object of Label class, as:

lbl = Label(f, text="Welcome to Python", width=20, height=2, font=('Courier', -30, 'bold underline '), fg='blue',
bg='yellow')

PROGRAMS
55. Create and display a label when a push button is clicked.

Message widget

A message is similar to label. But messages are generally used to display multiple lines of text where as a label is
used to display a single line of text. All the text in the message will be displayed using the same font. To create a
message, we need to create an object of Message class, as:
m = Message(f, text='This is a message that has more than one line of text.', width=200, font=('Roman', 20, 'bold
italic'), fg='dark goldenrod')

Here, ‘text’ represents the text to be displayed in the message. The ‘width’ option specifies the message width
in pixels. ‘font’ represents the font for the message. We can use options ‘fg’ for specifying foreground color and
‘bg’ for specifying background color for the message text.

Text widget

Text widget is same as a Label or Message. But Text widget has several options and can display multiple lines of
text in different colors and fonts. It is possible to insert text into a Text widget, modify it or delete it. One can
create a Text widget by creating an object to Text class, as:

t = Text(root, width=20, height=10, font=('Verdana', 14, 'bold'), fg='blue', bg='yellow',


wrap=CHAR/WORD/NONE)

Once the Text widget is created, we can insert any text using insert() method, as:

t.insert(END, 'Text widget\nThis text is inserted into the Text widget.\n This is second line\n and this is third
line\n')

Here, the first argument END represents that the text is added at the end of the previous text. We can also use
CURRENT to represent that the text is added at the current cursor position. The second argument is the text
that is added to the Text widget.

110
Adv Python Nageswarao Datatechs

PROGRAMS
56. Create a Text widget along with a vertical scrollbar.

Scrollbar widget

A scroll bar is a widget that is useful to scroll the text in another widget. For example, the text in the Text, Frame
or Listbox can be scrolled from top to bottom or left to right using scroll bars. There are two types of scroll bars.
They are horizontal and vertical. The horizontal scroll bar is useful to view the text from left to right. The vertical
scroll bar is useful to scroll the text from top to bottom. To create a scroll bar, we have to create Scrollbar class
object, as:

h = Scrollbar(root, orient=HORIZONTAL, command=t.xview)

Here, ‘h’ represents the Scrollbar object which is created as a child to ‘root’ window. The option ‘orient’
indicates HORIZONTAL for horizontal scroll bars and VERTICAL indicates vertical scroll bars. The option
‘command’ represents the method that is to be executed. The method ‘xview’ is executed on the object ‘t’.
Here, ‘t’ may represent a widget like Text widget or Listbox.

Similarly, to create a vertical scroll bar ‘v’, we can write:

v = Scrollbar(root, orient=VERTICAL, command=t.yview)

After creating the scroll bar, it should be attached to the widget like Text widget or Listbox, as:
t.configure(xscrollcommand=h.set)

Here, ‘t’ indicates Text widget. ‘xscrollcommand’ calls the set() method of horizontal scroll bar. In the same way,
we can attach vertical scroll bar, as:

t.configure(yscrollcommand=v.set)

Finally, the scroll bar should be attached to the root window using pack() or grid() methods as:

h.pack(side=BOTTOM, fill=X)

Here, we are attaching the horizontal scroll bar at the bottom of the widget and it spreads across X - axis.
Similarly, to attach vertical scroll bar, we can use:

v.pack(side=RIGHT, fill=Y)

Checkbutton widget

Check buttons, also known as check boxes are useful for the user to select one or more options from available
group of options. Check buttons are displayed in the form of square shaped boxes. When a check button is
selected, a tick mark is displayed on the button. We can create check buttons using Checkbutton class as:

c1 = Checkbutton(f, bg='yellow', fg= 'green', font=('Georgia', 20, 'underline'), text='Java', variable= var1,
command=display)

Here, the option ‘variable’ represents an object of IntVar() class. ‘command’ represents the method to be called
when the user clicks the check button.

111
Adv Python Nageswarao Datatechs
The class ‘IntVar’ is useful to know the state of the check button, whether it is clicked or not. IntVar class object
can be created as:

var1 = IntVar()

When the check button is clicked or selected, the value of ‘var1’ will be 1, otherwise its value will be 0. To
retrieve the value from ‘var1’, we should use get() method, as:

x = var1.get() # x value can be 1 or 0

PROGRAMS
57. Create 3 check buttons and know which options are selected by the user.

Radiobutton widget

A radio button is similar to a check button, but it is useful to select only one option from a group of available
options. A radio button is displayed in the form of round shaped button. The user can not select more than one
option in case of radio buttons. When a radio button is selected, there appears a dot in the radio button. We
can create a radio button as an object of Radiobutton class, as:

r1 = Radiobutton(f, bg='yellow', fg= 'green', font=('Georgia', 20, 'underline'), text='Male', variable= var, value=1,
command=display)

The option ‘text’ represents the string to be displayed after the radio button. ‘variable’ represents the object of
IntVar class. ‘value’ represents a value that is set to this object when the radio button is clicked. The object of
IntVar class can be created as:

var = IntVar()

When the user clicks the radio button, the value of this ‘var’ is set to the value given in ‘value’ option, i.e. 1. It
means ‘var’ will become 1 if the radio button ‘r1’ is clicked by the user. In this way, it is possible to know which
button is clicked by the user.

PROGRAMS
58. Create 2 radio buttons and know which option is selected by the user.

Entry widget

Entry widget is useful to create a rectangular box that can be used to enter or display one line of text. For
example, we can display names, passwords or credit card numbers using Entry widgets. An Entry widget can be
created as an object of Entry class, as:

e1 = Entry(f, width=25, fg='blue', bg='yellow', font=('Arial', 14), show=’*’)

Here, ‘show’ represents a character that replaces the originally typed characters in the Entry widget. For
example, show=’*’ is useful when the user wants to hide his password by displaying stars in the place of
characters.

After typing text in the Entry widget, the user presses Enter button. Such an event should be linked with the
Entry widget using bind() method as:

e1.bind("<Return>", self.display)

112
Adv Python Nageswarao Datatechs

When the user presses Enter (or Return) button, the event is passed to display() method. Hence, we are
supposed to catch the event in the display method, as:

def display(self, event):

As seen in the preceding code, we are catching the event though an argument ‘event’ in the display() method.
This argument is never used inside the method. The method consists of the code that is to be executed when
the user pressed Enter button.

PROGRAMS
59. Create 2 Entry boxes and enter user-name and password.

Spinbox widget

A Spinbox widget allows the user to select values from a given set of values. The values may be a range of
numbers or a fixed set of strings.

The spin box appears as a long rectangle attached with arrowheads pointing towards up and down. The user can
click on the arrowheads to see the next value or previous value. The user can also edit the value being displayed
in the spin box just like he can do in case of an Entry widget.

A spin box is created as an object of Spinbox class. To create a spin box with numbers ranging from 5 to 15, we
can write:
s1 = Spinbox(f, from_= 5, to=15, textvariable=val1, width=15, fg='blue', bg='yellow', font=('Arial', 14, 'bold'))

Here, ‘f’ represents the parent widget. ‘from_’ indicates the starting value and ‘to’ indicates the ending value in
the spin box. ‘textvariable’ shows the control variable, i.e. val1 that is created as an object of IntVar class, as:

val1 = IntVar()
‘ val1’ is control variable that receives the displayed value in the spin box. Similarly, we can create a spin box
with strings by specifying the strings as a tuple, as:

s2 = Spinbox(f, values=('Hyderabad', 'Delhi', 'Kolkata', 'Bangalore'), textvariable=val2, width=15, fg='black',


bg='green', font=('Arial', 14, 'bold italic'))

Here, the fixed strings that are displayed in the spin box are mentioned in the ‘values’ option as a tuple, as:

values=('Hyderabad', 'Delhi', 'Kolkata', 'Bangalore')

The ‘textvariable’ option indicates the control variable value ‘val2’ that is created as an object of StringVar class,
as:

val2 = StringVar()

‘val2’ contains the displayed string in the spin box. To retrieve the values from the control variables, we can use
get() method, as:

a = val1.get() # get the number from val1


s = val2.get() # get the string from val2

113
Adv Python Nageswarao Datatechs
PROGRAMS
60. Create a spin box with city names.

Listbox widget

A list box is useful to display a list of items in a box so that the user can select 1 or more items. To create a list
box, we have to create an object of Listbox class, as:

lb = Listbox(f, font="Arial 12 bold", fg='blue', bg='yellow', height=8, width=24, activestyle='underline',


selectmode=MULTIPLE)

Here, ‘lb’ is the list box object. The option ‘height’ represents number of lines shown in the list box. ‘width’
represents the width of the list box in terms of number of characters and the default is 20 characters. The
option ‘activestyle’ indicates the appearance of the selected item. It may be ‘underline’, ‘dotbox’ or ‘none’. The
default value is ‘underline’. The option ‘selectmode’ may take any of the following values:

□ BROWSE: Normally, we can select one item (or line) out of a list box. If we click on an item and then
drag to a different item, the selection will follow the mouse. This is the default value of ‘selectmode’
option.

□ SINGLE: This represents that we can select only one item( or line) from all available list of items.

□ MULTIPLE: We can select 1 or more number of items at once by clicking on the items. If an item is
already selected, clicking second time on the item will un-select it.

□ EXTENDED: We can select any adjacent group of items at once by clicking on the first item and dragging
to the last item.
Once the list box is created, we should insert items into the list box using insert() method, as:

lb.insert(0, 'Standford University')


lb.insert(1, ' Oxford University')

To bind the ListboxSelect event with a method, we can using bind() method as:

lb.bind('<<ListboxSelect>>', on_select)

The meaning of the previous statement is that when the user selects any items in the list box, the method
on_select() will be called. This method can be written something like this:

def on_select(event):
# create an empty list box
lst = []

# know the indexes of the selected items


indexes = lb.curselection()

# retrieve the items names depending on indexes


# append the items names to the list box
for i in indexes:
lst.append(lb.get(i))

114
Adv Python Nageswarao Datatechs
Observe the on_select() method. It has a parameter ‘event’ that is useful to catch the ListboxSelect event. We
need not do anything with this event inside the method. To retrieve the indexes or position numbers of the
selected items, we can use curselection() method of Listbox class. Suppose, we want to know the names of the
items based on the indexes, we can use get() method of the Listbox class. In the on_select() method, we are
appending the names of the selected items to a list box. Later the contents of this list box can be displayed in a
Text box.

PROGRAMS
61. To create a list box with Universities names and display the selected Universities names in a text box.

Menu widget

A menu represents a group of items or options for the user to select from. For example, when we click on ‘File’
menu, it may display options like ‘New’, ‘Open’, ‘Save’, etc. We can select any option depending on our
requirements. ‘New’, ‘Open’, ‘Save’ – these options are called menu items. Thus, a menu is composed of several
menu items. Similarly, ‘Edit’ is a menu with menu items like ‘Cut’, ‘Copy’, ‘Paste’, etc. Generally, we see menus
displayed in a bar, called menu bar. Please see the following figure to understand the terms menu bar, menu
and menu item.

To create a menu, we should use the following steps:

1. First of all, we should create a menu bar as a child to root window. This is done using Menu class, as:

menubar = Menu(root)

2. This menu bar should be attached to the root window using config() method as:

root.config(menu=menubar)

3. The next step is to create a menu with a group of menu items. For this purpose, first of all we should create
Menu class object as:

filemenu = Menu(root, tearoff=0)

115
Adv Python Nageswarao Datatechs
Here, ‘filemenu’ is the Menu class object. The option ‘tearoff’ can be 0 or 1. When this option is 1, the menu can
be torn off. In this case, the first position (position 0) in the menu items is occupied by the tear-off element
which is a dashed line. If this option value is 0, then this dashed line will not appear and the menu items are
displayed starting from 0th position onwards.

The next step is to add menu items to the filemenu object using add_command() method, as:

filemenu.add_command(label="New", command=donothing)

Here, the menu item name is ‘New’ and when it is clicked by the user, the method donothing() will be called. In
this way, we can add any number of menu items to filemenu object. When we want to display a horizontal line
that separates a group of menu items from another group of menu items, we can use add_separator() method,
as:

filemenu.add_separator()

After adding all menu items to filemenu object, we should give it a name and add it to menu bar using
add_cascade() method, as:

menubar.add_cascade(label="File", menu=filemenu)
The ‘menu’ option tells that the ‘File’ menu is composed of all menu items that are added already to filemenu
object.

PROGRAMS
62. To create a simple menu.

NETWORKING IN PYTHON

Interconnection of computers is called a network. A simple network can be formed by connecting two
computers using a cable. Thus a network can have two computers or two thousand computers. For example,
Internet is the largest network on the earth where millions of computers are connected.

Downloading a web page from Internet

It is possible to download the entire web page from Internet and save it into our computer system. Of course,
the images of the web page may not be downloaded.

First we should open the web page using urlopen() function. This function returns the content of the web page
into a file like object. Now, we can read from this object using read() method, as:

file = urllib.request.urlopen("https://www.python.org/")
content = file.read()

urlopen() function can raise ‘urllib.error.HTTPError’ if the web page is not found. The next step is to open a file
and write the ‘content’ data into that file. Since web pages contain binary data, to store the web pages, we have
to open the file in binary write mode, as:

f = open('myfile.html', 'wb') # we want to write data into myfile.html


f.write(content) # write it

PROGRAMS

116
Adv Python Nageswarao Datatechs
63. A program to download a web page from Internet and save it into our computer.

Downloading an image from Internet

We can connect our computer to Internet and download images like .jpg, .gif or .png files from Internet into our
computer system by writing a simple Python program. For this purpose, we can use urlretrieve() function of
urllib.request module. This function takes the URL of the image file and our own image file name as arguments.

download = urllib.request.urlretrieve(url, "myimage.jpg")

Here, ‘download’ is a tuple object. ‘url’ represents the URL string of the image location on Internet.
“myimage.jpg” is the name of the file on which the image will be downloaded.

PROGRAMS
64. A program to download an image from Internet into our computer system.

A TCP/IP Server

A server is a program that provides services to other computers on the network or Internet. Similarly a client is a
program that receives services from the servers. When a server wants to communicate with a client, there is a
need of a socket. A socket is a point of connection between the server and client. The following are the general
steps to be used at server side:

1. Create a TCP/IP socket at server side using socket() function.

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

Here, socket.AF_INET represents IP Address version 4 and socket.SOCK_STREAM indicates that we are using
TCP/IP protocol for communication with client. Anyhow, a socket uses IP address version 4 and TCP/IP protocol
by default. Hence, we can create a socket without giving protocol version and type of the protocol, as:

s = socket.socket() # this uses TCP/IP protocol by default

2. Bind the socket with host name and port number using bind() method. Here, host name can be an IP Address
or a web site name. If we want to run this program in an individual computer that is not connected in any
network, then we can take hose name as ‘localhost’. This represents that the server is running in the local
system and not on any network. The IP Address of the ‘localhost’ is 127.0.0.1. As an alternative to ‘localhost’, we
can also mention this IP Address. bind() method is used in the following format:

s.bind((host, port)) # here, (host, port) is a tuple.

3. We can specify maximum number of connections using listen() method as:

s.listen(5); # maximum connections allowed are 5

4. The server should wait till a client accepts connection. This is done using accept() method as:

c, addr = s.accept() # this method returns c and addr

Here, ‘c’ is connection object that can be used to send messages to the client. ‘addr’ is the address of the client
that has accepted the connection.

117
Adv Python Nageswarao Datatechs
5. Finally, using send() method, we can send message strings to client. The message strings should be sent in the
form of byte streams as they are used by the TCP/IP protocol.

c.send(b"message string")

Observe the ‘b’ prefixed before the message string. This indicates that the string is a binary string. The other
way to convert a string into binary format is using encode() method, as:

string.encode()

6. After sending the messages to the client, the server can be disconnected by closing the connection object as:

c.close()

A TCP/IP Client

A client is a program that receives the data or services from the server. We use the following general steps in
the client program:

1. At the client side, we should first create the socket object that uses TCP/IP protocol to receive data. This is
done as:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

2. Connect the socket to the server and port number using connect() method.

s.connect((host, port))

3. To receive the messages from the server, we can use recv() method, as:

msg = s.recv(1024)

Here, 1024 indicates the buffer size. This is the memory used while receiving the data. It means, at a time, 1024
bytes of data can be received from the server. We can change this limit in multiples of 1024. For example, we
can use 2048 or 3072 etc. The received strings will be in binary format. Hence they can be converted into
normal strings using decode() method.

4. Finally, we should disconnect the client by calling close() method on the socket object, as:
s.close()

PROGRAMS
65. A TCP/IP server program that sends messages to a client.
66. A TCP/IP client program that receives messages from the server.

A UDP Server

If we want to create a server that uses UDP protocol to send messages, we have to specify socket.SOCK_DGRAM
while creating the socket object, as:

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

It means the server will send data in the form of packets called ‘datagrams’. Now, using sendto() function, the
server can send data to the client. Since UDP is a connection-less protocol, server does not know to where the
data should be sent. Hence we have to specify the client address in sendto() function, as:

118
Adv Python Nageswarao Datatechs

s.sendto(“message string”, (host, port))

Here, the "message string" is the binary string to be sent. The tuple (host, port) represents the host name and
port number of the client.

A UDP Client

At the client side, the socket should be created to use UDP protocol as:

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

The socket should be bound to the server using bind() method as:

s.bind((host, port))

Now, the client can receive messages with the help of recvfrom() method, as:

msg, addr = s.recvfrom(1024)

This method receives 1024 bytes at a time from the server which is called buffer size. This method returns the
received message into ‘msg’ and the address of the server into ‘addr’. Since the client does not know how many
messages (i.e. strings) the server sends, we can use recvfrom() method inside a while loop and receive all the
messages as:

while msg:
print('Received: '+ msg.decode())
msg, addr = s.recvfrom(1024)

But the problem here is that the client will hang when the server disconnects. To rectify this problem, we have
to set some time for the socket so that the client will automatically disconnect after that time elapses. This is
done using settimeout() method.

s.settimeout(5)

This method instructs the socket to block when 5 seconds time is elapsed. Hence if the server disconnects, the
client will wait for another 5 seconds time and disconnects. The settimeout() method can raise socket.timeout
exception.

PROGRAMS
67. A UDP server program that sends messages to a client.
68. A UDP client program that receives messages from the server.

File server

A file server is a server program that accepts a file name from a client, searches for the file on the hard disk and
sends the content of the file to the client. When the requested file is not found at server side, the server sends a
message to the client saying ‘File does not exist’. We can create a file server using TCP/IP type of socket
connection.

File client

119
Adv Python Nageswarao Datatechs
A file client is a client side program that sends a request to the server to search for a file and send the file
contents. We have to type the file name from the key board at the file client. This file name is sent to the file
server and the file contents are received by the client in turn. We can create a file client program using TCP/IP
type of socket connection.

PROGRAMS
69. A file server that receives a file name from a client and sends the contents of the file.
70. A file client program that sends a file name to the server and receives the file contents.

Sending a simple mail

It is possible to develop a Python program that can send a mail to any email address from any email address. For
this purpose, we need SMTP class of smtplib module. When we create an object of SMTP class, we actually
connect to smtp (simple mail transfer protocol) server that is useful to send the mail. For example to connect to
gmail.com server we can write:

server = smtplib.SMTP('smtp.gmail.com', 587)

Here, we want to connect to gmail.com website using its port number 587. If we want to connect to any other
mail server, we are supposed to provide that server name along with its port number. Once we connect to mail
server, we can send the mail using send_message() method, as:
server.send_message(msg)

Here, ‘msg’ represents the total message string including the address to which the mail should be sent, address
from where the mail is sent, subject of the mail and body of the mail. This ‘msg’ is represented as an object of
MIMEText class which belongs to email.mime.text module. The word ‘MIME’ (Multi-Purpose Internet Mail
Extensions) indicates an extension of the original Internet e-mail protocol that lets people use the protocol to
exchange different kinds of data on the Internet. Now, let us see how to create the ‘msg’ object:

msg = MIMEText(body) # here, body indicates mail body text

Once the ‘msg’ is created, we can fill in the details like from address, to address and subject as:

msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "SUBJECT LINE OF OUR MESSAGE"

Of course, before sending the email, we have to log into the server with a valid password. This is done in two
steps as shown below:

1. First put the smtp connection into TLS (Transport Layer Security) mode. This will start the process of verifying
authenticity of the sender.

server.starttls()

2. Next, we have to login to the server with our mail address and pass word. This is done using login() method
as:

server.login(fromaddr, "password")

All these steps are shown in Program 77 in a proper sequence. Just follow each step one by one and you will be
able to send the mail easily.

120
Adv Python Nageswarao Datatechs
PROGRAMS
71. A Python program to send email to any mail address.

NOTE:
While running this program, our computer should have been connected in Internet. This program is sending the
mail through gmail.com server. Now-a-days, the gmail.com server people are using more security levels and
hence this program may show an error like ‘SMTPAuthenticationError’ which means that the gmai.com server
does not allow this program to communicate. In that case, we have to inform the gmail.com server to allow
“less secure apps” also. You can do this by logging into your Gmail account and then visiting the following page:

https://www.google.com/settings/security/lesssecureapps

In this page, we should click on ‘Turn on’ option against ‘Access for less secure apps’. Then the less secure
applications like our Program are allowed by gmail.com server. Then we can run this program successfully. A
caution is to ‘Turn off’ the ‘Access for less secure apps’ option after execution of this program is over. You can
verify in the rediffmail.com’s inbox that the mail sent by our program reached nageswara.r@rediffmail.com.

Note: If the above does not work, try the below way.

Turning on 'less secure apps' settings as mailbox user

1. Go to your (Google Account) by typing: https://myaccount.google.com/


2. On the left navigation panel, click Security.
3. On the bottom of the page, in the Less secure app access panel, click Turn on access.
If you don't see this setting, your administrator might have turned off less secure app account
access (check the instruction above).
4. Click the Save button.

PYTHON’S DATABASE CONNECTIVITY


A database represents collection of data. Just like a file, we can store data into a database. Once the data is
stored in a database, we need to perform some operations on data. For example modifying the existing data or
deleting the unwanted data or retrieving the data from the database, etc. operations are needed on data. To
perform such operations, a database comes with a software. This is called a database management system
(DBMS). Hence, we can say:

DBMS = database + software to manage the data.

Examples for DBMS are MySQL, Oracle, Sybase, SQL Server etc.

Advantages of a DBMS over files

□ If we go for files, we have to write a lot of programming. For example, to store data into a file, we have
to write a program, to retrieve data, we need another program and to modify data, we should write yet
another program. A lot of programmers’ time is consumed in developing these programs. If we use
DBMS, we can achieve all these tasks without writing any programs. We can store data, retrieve it,
modify or delete it by giving simple commands. These commands are written in a language called SQL
(Structured Query Language). Thus programmers’ duty is simplified.

□ Generally each file contains data that is not related to another file’s data. When there is no relationship
between the files, it would be difficult to fulfil the information needs of the user. The user may wish to

121
Adv Python Nageswarao Datatechs
see the information that has some relationship and that is stored in various files. Accessing such data is
difficult for the programmers. In DBMS, various pieces of data can be related and retrieved easily using
keys concept.

□ Files are not so efficient in handling large volumes of data. It would be difficult task to enter large data
into a file or retrieving it from the file. But DBMS can handle large volumes of data efficiently and easily.

□ When multiple users are accessing the data concurrently from the same file, there are chances of wrong
results or inconsistent changes to the existing data. DBMS will take care of such problems.

□ Once changes are made to the file, we cannot roll them back. In case of DBMS, we can restore the
previous state of data by rolling back the changes.

□ Files offer very weak security for data whereas DBMS offers very good protection for data.

Using MySQL from Python

To work with MySQL in a Python program, we have to use connector sub module of mysql module. We can
import this module as:

import pymysql

To establish connection with MySQL database, we use connect() method of mysql.connector module, as:

conn = pymysql.connect(host='localhost', database='world', user='root', password='nag123')

The connect() method returns MySQLConnection class object ‘conn’. This method takes the following
parameters:
host= In the network, server’ ip address should be given as host. If we use individual computer, then the string
‘localhost’ can be supplied.
database= This is the database name to connect to.
user= this represents the user name. Generally this is ‘root’.
password= This indicates the root password.

The next step is to create cursor class object by calling cursor() method on ‘conn’ object as:

cursor = conn.cursor()

The ‘cursor’ object is useful to execute SQL commands on the database. For this purpose, we can use execute()
method of ‘cursor’ object, as:

cursor.execute("select * from emptab")

The resultant rows retrieved from the table are stored in the ‘cursor’ object. We can get them from the ‘cursor’
object using fetchone() or fetchall() methods.

row = cursor.fetchone() # get 1 row


rows = cursor.fetchall() # get all rows

Finally, we can close the connection with MySQL by closing the cursor and connection objects as:

cursor.close()
conn.close()
122
Adv Python Nageswarao Datatechs

Retrieving all rows from a table

After establishing connection with MySQL database using connect() method, we have to create ‘cursor’ object.
Then we have to call the execute() method which executes our SQL command, as:

cursor.execute("select * from emptab")

Our assumption in this case is that we have ‘emptab’ table already available in the ‘world’ database in MySQL.
The rows of the ‘emptab’ will be available in the ‘cursor’ object. We can retrieve them using fetchone() method
as:

row = cursor.fetchone() # retrieve the first row

while row is not None: # if that row exists then


print(row) # display it
row = cursor.fetchone() # get the next row

PROGRAMS
72. To retrieve and display all rows from employee table.

We can also use fetchall() method that retrieves all rows from the ‘emptab’ table and stores them in an iterator,
as:

rows = cursor.fetchall()

Now, we can retrieve the rows one by one from ‘rows’ iterator using a for loop as:

for row in rows:


print(row) # display each row

PROGRAMS
73. To retrieve and display all rows from employee table.

Inserting rows into a table

To insert a row into a table, we can use SQL insert command, as:

str = "insert into emptab(eno, ename, sal) values(9999, 'Srinivas', 9999.99)"

Here, we are inserting values for eno, ename and sal columns into ‘emptab’ table. The total command is taken
as a string ‘str’. Now we can execute this command by passing it to execute() method, as:

cursor.execute(str) # SQL insert statement in the str is executed

After inserting a row into the table, we can save it by calling commit() method as:

conn.commit()

In case, there is an error, we can un-save the row by calling rollback() method as:

conn.rollback()

123
Adv Python Nageswarao Datatechs

PROGRAMS
74. A Python program to insert a row into a table in MySQL.

Deleting rows from a table

We can accept the employee number from the keyboard and delete the corresponding row in the employee
table. For this purpose, we can use the SQL command as:

delete from emptab where eno = '%d'

Here, ‘%d’ represents the integer number supplied to the command as argument. This is nothing but the
employee number, i.e. eno.

PROGRAMS
75. Let us delete a row from emptab by accepting the employee number.

Updating rows in a table

Suppose, we want to modify the values in a row, we can use update command. For example, to increase the
salary of an employee by 1000, we can write:

update emptab set sal = sal+1000 where eno = '%d'

Here, ‘%d’ represents the argument value, i.e. the employee number. This can be passed from the keyboard.

PROGRAMS
76. A program to increase the salary of an employee by accepting the employee number from keyboard.

Using Oracle database from Python

To work with Oracle database in a Python program, we have to use cx_Oracle module. This module can be
imported as:

import cx_Oracle

To establish connection with Oracle database, we use connect() method of cx_Oracle module, as:

conn = cx_Oracle.connect('SYSTEM/Nagesh123@localhost')

The connect() method returns cx_Oracle.Connection class object ‘conn’. This method takes the following
parameters:

SYSTEM: this is the user name for Oracle database.


Nagesh123: this is the pass word given at the time of Oracle database installation.
localhost: this indicates the IP Address of the Oracle server machine. When we are not in the network and we
are running this program in an individual computer, we can mention ‘localhost’ to represent that the server is
also found in the local system.

The next step is to create cursor class object by calling cursor() method on ‘conn’ object as:

cursor = conn.cursor()

124
Adv Python Nageswarao Datatechs
The ‘cursor’ object is useful to execute SQL commands on the database. For this purpose, we can use execute()
method of ‘cursor’ object, as:

cursor.execute("select * from emptab")

The resultant rows retrieved from the table are stored in the ‘cursor’ object. We can get them from the ‘cursor’
object using fetchone() or fetchall() methods.

row = cursor.fetchone() # get 1 row


rows = cursor.fetchall() # get all rows

Finally, we can close the connection with MySQL by closing the cursor and connection objects as:

cursor.close()
conn.close()

PROGRAMS
77. A Python program to connect to Oracle database and retrieve rows from emptab table.

DATA ANALYSIS USING PANDAS


Data Science

To work with datascience, we need the following packages to be installed:

C:\> pip install pandas


C:\> pip install xlrd //to extract data from Excel sheets
C:\> pip install matplotlib

Data plays important role in our lives. For example, a chain of hospitals contain data related to medical reports
and prescriptions of their patients. A bank contains thousands of customers’ transaction details. Share market
data represents minute to minute changes in the share values. In this way, the entire world is roaming around
huge data.

Every piece of data is precious as it may affect the business organization which is using that data. So, we need
some mechanism to store that data. Moreover, data may come from various sources. For example in a business
organization, we may get data from Sales department, Purchase department, Production department, etc. Such
data is stored in a system called ‘data warehouse’. We can imagine data warehouse as a central repository of
integrated data from different sources.

Once the data is stored, we should be able to retrieve it based on some pre-requisites. A business company
wants to know about how much amount they spent in the last 6 months on purchasing the raw material or how
many items found defective in their production unit. Such data cannot be easily retrieved from the huge data
available in the data warehouse. We have to retrieve the data as per the needs of the business organization.
This is called data analysis or data analytics where the data that is retrieved will be analyzed to answer the
questions raised by the management of the organization. A person who does data analysis is called ‘data
analyst’.

125
Adv Python Nageswarao Datatechs

Once the data is analyzed, it is the duty of the IT professional to present the results in the form of pictures or
graphs so that the management will be able to understand it easily. Such graphs will also help them to forecast
the future of their company. This is called data visualization. The primary goal of data visualization is to
communicate information clearly and efficiently using statistical graphs, plots and diagrams.

Data science is a term used for techniques to extract information from the data warehouse, analyze them and
present the necessary data to the business organization in order to arrive at important conclusions and
decisions. A person who is involved in this work is called ‘data scientist’. We can find important differences
between the roles of data scientist and data analyst in following table:

Data Scientist Data Analyst


Data scientist formulates the questions that will Data analyst receives questions from the
help a business organization and then proceed in business team and provides answers to them.
solving them.
Data scientist will have strong data visualization Data analyst simply analyzes the data and
skills and the ability to convert data into a provides information requested by the team.
business story.
Perfection in mathematics, statistics and Perfection in data warehousing, big data
programming languages like Python and R are concepts, SQL and business intelligence is
needed for a Data scientist. needed for a Data analyst.
A Data scientist estimates the unknown A Data analyst looks at the known data from a
information from the known data. new perspective.

Please see the following sample data in the excel file: empdata.xlsx.

126
Adv Python Nageswarao Datatechs

CREATING DATA FRAMES

is possible from csv files, excel files, python dictionaries, tuples list, json data etc.

Creating data frame from .csv file


>>> import pandas as pd
>>> df = pd.read_csv("f:\\python\PANDAS\empdata.csv")
>>> df
empid ename sal doj
0 1001 Ganesh Rao 10000.00 10-10-00
1 1002 Anil Kumar 23000.50 3-20-2002
2 1003 Gaurav Gupta 18000.33 03-03-02
3 1004 Hema Chandra 16500.50 10-09-00
4 1005 Laxmi Prasanna 12000.75 08-10-00
5 1006 Anant Nag 9999.99 09-09-99

Creating data frame from .xlsx file


>>> df1 = pd.read_excel("f:\\python\PANDAS\empdata.xlsx", "Sheet1")
>>> df1
empid ename sal doj
0 1001 Ganesh Rao 10000.00 2000-10-10
1 1002 Anil Kumar 23000.50 2002-03-20
2 1003 Gaurav Gupta 18000.33 2002-03-03
3 1004 Hema Chandra 16500.50 2000-09-10
4 1005 Laxmi Prasanna 12000.75 2000-10-08
5 1006 Anant Nag 9999.99 1999-09-09

Creating data frame from a dictionary


>>> empdata = {"empid": [1001, 1002, 1003, 1004, 1005, 1006],
"ename": ["Ganesh Rao", "Anil Kumar", "Gaurav Gupta", "Hema Chandra",
"Laxmi Prasanna", "Anant Nag"],
"sal": [10000, 23000.50, 18000.33, 16500.50, 12000.75, 9999.99],
"doj": ["10-10-2000", "3-20-2002", "3-3-2002", "9-10-2000", "10-8-2000",
"9-9-1999"]}

127
Adv Python Nageswarao Datatechs
>>> df2 = pd.DataFrame(empdata)
>>> df2
doj empid ename sal
0 10-10-2000 1001 Ganesh Rao 10000.00
1 3-20-2002 1002 Anil Kumar 23000.50
2 3-3-2002 1003 Gaurav Gupta 18000.33
3 9-10-2000 1004 Hema Chandra 16500.50
4 10-8-2000 1005 Laxmi Prasanna 12000.75
5 9-9-1999 1006 Anant Nag 9999.99

Creating data frame from a list of tuples

>>> empdata = [(1001, 'Ganesh Rao', 10000.00, '10-10-2000'),


(1002, 'Anil Kumar', 23000.50, '3-20-2002'),
(1003, 'Gaurav Gupta', 18000.33, '03-03-2002'),
(1004, 'Hema Chandra', 16500.50, '10-09-2000'),
(1005, 'Laxmi Prasanna', 12000.75, '08-10-2000'),
(1006, 'Anant Nag', 9999.99, '09-09-1999')]
>>> df3 = pd.DataFrame(empdata, columns=["eno", "ename", "sal", "doj"])
>>> df3
eno ename sal doj
0 1001 Ganesh Rao 10000.00 10-10-2000
1 1002 Anil Kumar 23000.50 3-20-2002
2 1003 Gaurav Gupta 18000.33 03-03-2002
3 1004 Hema Chandra 16500.50 10-09-2000
4 1005 Laxmi Prasanna 12000.75 08-10-2000
5 1006 Anant Nag 9999.99 09-09-1999

BASIC OPERATIONS ON DATAFRAMES


(Data analysis)

For all operations please refer to:

https://pandas.pydata.org/pandas-docs/stable/ generated/pandas.Series.html

df = pd.read_csv("f:\\python\PANDAS\empdata.csv")
>>> df
empid ename sal doj
0 1001 Ganesh Rao 10000.00 10-10-00
1 1002 Anil Kumar 23000.50 3-20-2002
2 1003 Gaurav Gupta 18000.33 03-03-02
3 1004 Hema Chandra 16500.50 10-09-00
4 1005 Laxmi Prasanna 12000.75 08-10-00
5 1006 Anant Nag 9999.99 09-09-99

1. To know the no. of rows and cols – shape


>>> df.shape
(6, 4)

>>> r, c = df.shape
>>> r
6

2. To display the first or last 5 rows – head(), tail()


>>> df.head()
>>> df.tail()

128
Adv Python Nageswarao Datatechs
To display the first 2 or last 2 rows

>>> df.head(2)
>>> df.tail(2)

3. Displaying range of rows – df[2:5]


To display 2nd row to 4th row:
>>> df[2:5]
To display all rows:
>>> df[:]
>>> df

4. To display column names – df.columns


>>> df.columns
Index(['empid', 'ename', 'sal', 'doj'], dtype='object')

5. To display column data – df.columname


>>> df.empid (or)
>>> df['empid']
>>> df.sal (or)
>>> df['sal']

6. To display multiple column data – df[[list of colnames]]


>>> df[['empid', 'ename']]
empid ename
0 1001 Ganesh Rao
1 1002 Anil Kumar
2 1003 Gaurav Gupta
3 1004 Hema Chandra
4 1005 Laxmi Prasanna
5 1006 Anant Nag

7. Finding maximum and minimum – max() and min()


>>> df['sal'].max()
23000.5
>>> df['sal'].min()
9999.9899999999998

8. To display statistical information on numerical cols – describe()


>>> df.describe()
empid sal
count 6.000000 6.000000
mean 1003.500000 14917.011667
std 1.870829 5181.037711
min 1001.000000 9999.990000
25% 1002.250000 10500.187500
50% 1003.500000 14250.625000
75% 1004.750000 17625.372500
max 1006.000000 23000.500000

9. Show all rows with a condition


To display all rows where sal>10000

129
Adv Python Nageswarao Datatechs

>>> df[df.sal>10000]
empid ename sal doj
1 1002 Anil Kumar 23000.50 3-20-2002
2 1003 Gaurav Gupta 18000.33 03-03-02
3 1004 Hema Chandra 16500.50 10-09-00
4 1005 Laxmi Prasanna 12000.75 08-10-00

To retrieve the row where salary is maximum


>>> df[df.sal == df.sal.max()]
empid ename sal doj
1 1002 Anil Kumar 23000.5 3-20-2002

10. To show only cols of rows based on condition


>>> df[['empid', 'ename']][df.sal>10000]
empid ename
1 1002 Anil Kumar
2 1003 Gaurav Gupta
3 1004 Hema Chandra
4 1005 Laxmi Prasanna

11. To know the index range - index


>>> df.index
RangeIndex(start=0, stop=6, step=1)

12. To change the index to a column – set_index()


>>> df1 = df.set_index('empid')

(or) to modify the same Data Frame:


>>> df.set_index('empid', inplace=True)

>>> df
ename sal doj
empid
1001 Ganesh Rao 10000.00 10-10-00
1002 Anil Kumar 23000.50 3-20-2002
1003 Gaurav Gupta 18000.33 03-03-02
1004 Hema Chandra 16500.50 10-09-00
1005 Laxmi Prasanna 12000.75 08-10-00
1006 Anant Nag 9999.99 09-09-99
NOTE: Now it is possible to search on empid value using loc[].

>>> df.loc[1004]
ename Hema Chandra
sal 16500.5
doj 10-09-00
Name: 1004, dtype: object

13. To reset the index back – reset_index()


>>> df.reset_index(inplace=True)
>>> df
empid ename sal doj
0 1001 Ganesh Rao 10000.00 10-10-00
1 1002 Anil Kumar 23000.50 3-20-2002
2 1003 Gaurav Gupta 18000.33 03-03-02
3 1004 Hema Chandra 16500.50 10-09-00

130
Adv Python Nageswarao Datatechs
4 1005 Laxmi Prasanna 12000.75 08-10-00
5 1006 Anant Nag 9999.99 09-09-99

HANDLING MISSING DATA

Read .csv file data into Data Frame


>>> df = pd.read_csv("f:\\python\PANDAS\empdata1.csv")
>>> df
empid ename sal doj
0 1001 Ganesh Rao 10000.00 10-10-00
1 1002 Anil Kumar 23000.50 03-03-02
2 1003 NaN 18000.33 03-03-02
3 1004 Hema Chandra NaN NaN
4 1005 Laxmi Prasanna 12000.75 10-08-00
5 1006 Anant Nag 9999.99 09-09-99

To set the empid as index – set_index()


>>> df.set_index('empid', inplace=True)
>>> df
ename sal doj
empid
1001 Ganesh Rao 10000.00 10-10-00
1002 Anil Kumar 23000.50 03-03-02
1003 NaN 18000.33 03-03-02
1004 Hema Chandra NaN NaN
1005 Laxmi Prasanna 12000.75 10-08-00
1006 Anant Nag 9999.99 09-09-99

To fill the NaN values by 0 – fillna(0)


>>> df1 = df.fillna(0)
>>> df1
ename sal doj
empid
1001 Ganesh Rao 10000.00 10-10-00
1002 Anil Kumar 23000.50 03-03-02
1003 0 18000.33 03-03-02
1004 Hema Chandra 0.00 0
1005 Laxmi Prasanna 12000.75 10-08-00
1006 Anant Nag 9999.99 09-09-99

To fill columns with different data – fillna(dictionary)


>>> df1 = df.fillna({'ename': 'Name missing', 'sal': 0.0, 'doj':'00-00-
00'})
>>> df1
ename sal doj
empid
1001 Ganesh Rao 10000.00 10-10-00
1002 Anil Kumar 23000.50 03-03-02
1003 Name missing 18000.33 03-03-02
1004 Hema Chandra 0.00 00-00-00
1005 Laxmi Prasanna 12000.75 10-08-00
1006 Anant Nag 9999.99 09-09-99

131
Adv Python Nageswarao Datatechs

To delete all rows with NaN values – dropna()

>>> df1 = df.dropna()


>>> df1
ename sal doj
empid
1001 Ganesh Rao 10000.00 10-10-00
1002 Anil Kumar 23000.50 03-03-02
1005 Laxmi Prasanna 12000.75 10-08-00
1006 Anant Nag 9999.99 09-09-99

SORTING THE DATA

Read .csv file data into Data Frame and indicate to consider ‘doj’ as date type field
>>> df = pd.read_csv("f:\\python\PANDAS\empdata2.csv", parse_dates=['doj'])
>>> df
empid ename sal doj
0 1001 Ganesh Rao 10000.00 2000-10-10
1 1002 Anil Kumar 23000.50 2002-03-03
2 1003 Gaurav Gupta 18000.33 2002-03-03
3 1004 Hema Chandra 16500.50 2002-03-03
4 1005 Laxmi Prasanna 12000.75 2000-08-10
5 1006 Anant Nag 9999.99 1999-09-09

To sort on a column – sort_values(colname)


>>> df1 = df.sort_values('doj')
>>> df1
>>> df1
empid ename sal doj
5 1006 Anant Nag 9999.99 1999-09-09
4 1005 Laxmi Prasanna 12000.75 2000-08-10
0 1001 Ganesh Rao 10000.00 2000-10-10
1 1002 Anil Kumar 23000.50 2002-03-03
2 1003 Gaurav Gupta 18000.33 2002-03-03
3 1004 Hema Chandra 16500.50 2002-03-03
NOTE: To sort in descending order:
>>> df1 = df.sort_values('doj', ascending=False)

To sort multiple columns differently – sort_values(by =[], ascending = [])


To sort on ‘doj’ in descending order and in that on ‘sal’ in ascending
order:
>>> df1 = df.sort_values(by=['doj', 'sal'], ascending=[False, True])
>>> df1
empid ename sal doj
3 1004 Hema Chandra 16500.50 2002-03-03
2 1003 Gaurav Gupta 18000.33 2002-03-03
1 1002 Anil Kumar 23000.50 2002-03-03
0 1001 Ganesh Rao 10000.00 2000-10-10
4 1005 Laxmi Prasanna 12000.75 2000-08-10
5 1006 Anant Nag 9999.99 1999-09-09

132
Adv Python Nageswarao Datatechs

DATA VISUALIZATION USING MATPLOTLIB


Complete reference is available at:
https://matplotlib.org/api/pyplot_summary.html

CREATE DATAFRAME FROM DICTIONARY


>>> empdata = {"empid": [1001, 1002, 1003, 1004, 1005, 1006],
"ename": ["Ganesh Rao", "Anil Kumar", "Gaurav Gupta", "Hema Chandra",
"Laxmi Prasanna", "Anant Nag"],
"sal": [10000, 23000.50, 18000.33, 16500.50, 12000.75, 9999.99],
"doj": ["10-10-2000", "3-20-2002", "3-3-2002", "9-10-2000", "10-8-2000",
"9-9-1999"]}
>>> import pandas as pd
>>> df = pd.DataFrame(empdata)

TAKE ONLY THE COLUMNS TO PLOT


>>> x = df['empid']
>>> y = df['sal']

DRAW THE BAR GRAPH

Bar chart shows data in the form of bars. It is useful for comparing values.
>>> import matplotlib.pyplot as plt
>>> plt.bar(x,y)
<Container object of 6 artists>
>>> plt.xlabel('employee id nos')
Text(0.5,0,'employee id nos')
>>> plt.ylabel('employee salaries')
Text(0,0.5,'employee salaries')
>>> plt.title('XYZ COMPANY')
Text(0.5,1,'XYZ COMPANY')
>>> plt.legend()
>>> plt.show()

133
Adv Python Nageswarao Datatechs

CREATING BAR GRAPHS FROM MORE THAN 1 DATA FRAMES

For example, we can plot the empid and salaries from 2 departments: Sales team and Production
team.
import matplotlib.pyplot as plt

x = [1001, 1002, 1003, 1004, 1005, 1006]


y = [10000, 23000.50, 18000.33, 16500.50, 12000.75, 9999.99]
x1 = [1010, 1011, 1012, 1013, 1014, 1015]
y1 = [5000, 6000, 4500.00, 12000, 9000, 10000]
plt.bar(x,y, label='Sales dept', color='red')
plt.bar(x1,y1, label='Production dept', color='green')
plt.xlabel('emp id')
plt.ylabel('salaries')
plt.title('XYZ COMPANY')
plt.legend()

plt.show()

134
Adv Python Nageswarao Datatechs

CREATING HISTOGRAM

Histogram shows distributions of values. Histogram is similar to bar graph but it is useful to show
values grouped in bins or intervals.

NOTE: histtype : ,‘bar’, ‘barstacked’, ‘step’, ‘stepfilled’-,

import matplotlib.pyplot as plt


emp_ages = [22,45,30,60,60,56,60,45,43,43,50,40,34,33,25,19]
bins = [0,10,20,30,40,50,60]
plt.hist(emp_ages, bins, histtype='bar', rwidth=0.8, color='cyan')
plt.xlabel('employee ages')
plt.ylabel('No. of employees')
plt.title('XYZ COMPANY')
plt.legend()

plt.show()

135
Adv Python Nageswarao Datatechs

CREATING A PIE CHART

A pie chart shows a circle that is divided into sectors that each represents a proportion of the whole.

To display no. of employees of different departments in a company.


import matplotlib.pyplot as plt
slices = [50, 20, 15, 15]
depts = ['Sales', 'Production', 'HR', 'Finance']
cols = ['cyan', 'magenta', 'blue', 'red']
plt.pie(slices, labels=depts, colors=cols, startangle=90, shadow=True,
explode= (0, 0.2, 0, 0), autopct='%.1f%%')
plt.title('XYZ COMPANY')
plt.show()

136
Adv Python Nageswarao Datatechs

137
Adv Python Nageswarao Datatechs

LIST OF PROGRAMS (ADVANCED PYTHON)

# 1.a class and object


class Person(object):
# special method to initialize the vars
# this is called constructor
def __init__(self):
self.name = 'Vishnu'
self.age = 20
self.sex = 'M'
# instance method
def talk(self):
print('Hi, iam ', self.name)
print('My age is ', self.age)
# create an instance
p1 = Person()
# call the method
p1.talk()
# to display instance variables through object
print(p1.name)
print(p1.age)
print(p1.sex)
__________________________________________________________________
# 2.student class example
class Student(object):
# parameterized constructor
def __init__(self, n='', m=[]):
self.name = n
self.marks = m
# instance method
def total(self):
print('Name: ', self.name)
tot = sum(self.marks)
print('Total marks: ', tot)
# create two instances
s1 = Student('Lakshmi', [10, 20, 30])
s1.total()
s2 = Student()
s2.total()
__________________________________________________________________

# 3.class vars and class methods


class Sample:
x = 10
@classmethod
def modify(cls):
cls.x+=1

# create two instances

138
Adv Python Nageswarao Datatechs
s1 = Sample()
s2 = Sample()
print(s1.x, s2.x)
# modify s1 in the class namespace
s1.modify()
print(s1.x, s2.x)

# modify s1 in the instance namespace


s1.x+=1
print(s1.x, s2.x)
__________________________________________________________________
# 4.accessor and mutator methods
class Manager:
def setName(self, name):
self.name = name
def getName(self):
return self.name
def setSal(self, sal):
self.sal = sal
def getSal(self):
return self.sal
# create object to Manager class
m = Manager()
m.setName('Raju')
print('Manager name= %s'%m.getName())

m.setSal(12000.50)
print('His salary= %.2f'% m.getSal())

__________________________________________________________________
# 5.understanding static methods
class Myclass:
# this is class var or static var
n=0
# constructor that increments n when an instance is created
def __init__(self):
Myclass.n +=1
# this is a static method to display the no. of instances
@staticmethod
def noObjects():
print('No. of instances created: ', Myclass.n)
# create 3 instances
obj1 = Myclass()
obj2 = Myclass()
obj3 = Myclass()
Myclass.noObjects()
__________________________________________________________________

# 6.this is outer class


class Student:
def __init__(self):
self.name = 'Srinu'

139
Adv Python Nageswarao Datatechs

def display(self):
print('Name= ', self.name)
# inner class
class Dob:
def __init__(self):
self.dd = 10
self.mm = 5
self.yy = 1990
def display(self):
print('Dob= {}/{}/{}'.format(self.dd, self.mm, self.yy))
# create outer class instance
s = Student()
s.display()

# create inner class instance


x = Student().Dob()
x.display()
__________________________________________________________________

# 7.Bank class with a private variable 'loan'.


class Bank:
def __init__(self):
self.accno=1001
self.name='Ganesh'
self.bal = 5000.0
self.__loan = 1500000.00
def display_to_clerk(self):
print('Accno= ', self.accno)
print('Name= ', self.name)
print('Balance= ', self.bal)

# create instance to the class


b = Bank()
b.display_to_clerk()

print(b.accno)
print(b.name)
print(b.bal)
print(b._Bank__loan) # name mangling
__________________________________________________________________
# 8. save this as teacher.py
class Teacher:
def setId(self, id):
self.id = id
def getId(self):
return self.id
def setName(self, name):
self.name = name
def getName(self):
return self.name
def setAddress(self, addr):

140
Adv Python Nageswarao Datatechs
self.addr = addr

def getAddress(self):
return self.addr
def setSal(self, sal):
self.sal = sal
def getSal(self):
return self.sal
# use the Teacher class
from teacher import Teacher
t = Teacher()

t.setId(10)
print(t.getId())

t.setName('Ramu')
print(t.getName())

t.setAddress('HNO-15, Arandal pet, Guntur')


print(t.getAddress())

t.setSal(5000.55)
print(t.getSal())
__________________________________________________________________
# 9.save this as student.py
class Student:
def setId(self, id):
self.id = id

def getId(self):
return self.id

def setName(self, name):


self.name = name

def getName(self):
return self.name

def setAddress(self, addr):


self.addr = addr

def getAddress(self):
return self.addr

def setMarks(self, marks):


self.marks = marks
def getMarks(self):
return self.marks
# use the Student class
from student import Student
s = Student()
s.setId(10)
print(s.getId())
s.setName('Ramu')
print(s.getName())

141
Adv Python Nageswarao Datatechs
s.setAddress('HNO-15, Arandal pet, Guntur')
print(s.getAddress())
s.setMarks(988)
print(s.getMarks())
# derive Student class from Teacher class - v2.0
from teacher import Teacher
class Student(Teacher):
def setMarks(self, marks):
self.marks = marks
def getMarks(self):
return self.marks
__________________________________________________________________

# 10.overring the base class constructor and method in sub class


# cut the contructor in Son class and re-execute this program
class Father:
def __init__(self):
self.property = 800000.00

def display_property(self):
print('Father\'s property= ', self.property)

class Son(Father):
def __init__(self):
self.property = 200000.00
def display_property(self):
print('Child\'s property= ', self.property)
# create sub class instance and display father's property
s = Son()
s.display_property()
__________________________________________________________________
# 11.Accessing base class constructor and method in the sub class
class Square:
def __init__(self, x):
self.x = x

def area(self):
print('Area of square= ', self.x*self.x)

class Rectangle(Square):
def __init__(self, x, y):
super().__init__(x)
self.y = y
def area(self):
super().area()
print('Area of rectange= ', self.x*self.y)
# find areas of square and rectanlge
a, b = [float(x) for x in input("Enter two measurements: ").split()]
r = Rectangle(a,b)
r. area()
__________________________________________________________________

142
Adv Python Nageswarao Datatechs
# 12.multiple inheritance
class Father:
def height(self):
print('Height is 6.0 foot')

class Mother:
def color(self):
print('Color is brown')
class Child(Father, Mother):
pass
c = Child()
print('Child\'s inherited qualities: ')
c.height()
c.color()

__________________________________________________________________
# 13.duck typing example
class Duck:
def talk(self):
print('Quack, quack!')
class Human:
def talk(self):
print('Hello, hai!')
# this method accepts an object and calls talk() method
def call_talk(obj):
obj.talk()

# call call_talk() method and pass an object


# depending on type of object, talk() method is executed
x = Duck()
call_talk(x)
x = Human()
call_talk(x)
__________________________________________________________________

# 14.+ operator is already overloaded on numbers, strings and lists


a = 10
b = 20
print(a+b) # addition
a = "Hello"
b = "Student"
print(a+b) # concatenation
a = [10, 20, 30]
b = [ -5, 10, 3]
print(a+b) # making a single list
__________________________________________________________________
# 15.method overloading
class Myclass:
def sum(self, a=0, b=0, c=0):
print('Sum= ', a+b+c)
# overload the sum() method
m = Myclass()
m.sum(10, 15)
m.sum(10, 15, 22.5)

143
Adv Python Nageswarao Datatechs
__________________________________________________________________

# 16.method overriding
class A:
def display(self):
print('Iam from base class')
class B(A):
# override the display() method of A
def display(self):
print('Iam from sub class')
b = B()
b.display()
__________________________________________________________________
# 17.abstract class example
from abc import ABC, abstractmethod
class Myclass(ABC):
@abstractmethod
def calculate(self, x):
pass # empty body, no code
# this is sub class of Myclass
class Sub1(Myclass):
def calculate(self, x):
print('Square value= ', x*x)
# this is another sub class for Myclass
import math
class Sub2(Myclass):
def calculate(self, x):
print('Square root= ', math.sqrt(x))
# third sub class for Myclass
class Sub3(Myclass):
def calculate(self, x):
print('Cube value= ', x**3)
# create Sub1 class object and call calculate() method
obj1 = Sub1()
obj1.calculate(16)
# create Sub2 class object and call calculate() method
obj2 = Sub2()
obj2.calculate(16)

# create Sub3 class object and call calculate() method


obj3 = Sub3()
obj3.calculate(16)
__________________________________________________________________
# 18.abstract class works like an interface
from abc import *
class Myclass(ABC):
def connect(self):
pass

# this is a sub class


class Oracle(Myclass):
def connect(self):
print('Connecting to Oracle database...')

144
Adv Python Nageswarao Datatechs
# this is another sub class
class Sybase(Myclass):
def connect(self):
print('Connecting to Sybase database...')

class Database:
# accept database name as a string
str = input('Enter database name: ')
# convert the string into classname
classname = globals()[str]
# create an object to that class
x = classname()
# call the connect() method
x.connect()
__________________________________________________________________
# 19.ZeroDivisionError exception handling example
try:
f = open("myfile", "w")
a, b = [int(x) for x in input("Enter two numbers: ").split()]
c = a/b
f.write("writing %d into myfile" %c)

except ZeroDivisionError:
print('Division by zero happened')
print('Please do not enter 0 in input')
finally:
f.close()
print('File closed')
__________________________________________________________________
# 20.example for syntax error
try:
date = eval(input("Enter date (yyyy,mm,dd): "))
except SyntaxError:
print('Invalid date entered')
else:
print('You entered: ', date)
__________________________________________________________________

# 21.handling AssertionError
try:
x = int(input('Enter a number between 5 and 10: '))
assert x>5 and x<10, "Your input is not correct"
print('The number entered: ', x)
except AssertionError as obj:
print(obj)
__________________________________________________________________
# 22.create our own class as sub class to Exception class
class MyException(Exception):
def __init__(self, arg):
self.msg = arg

# write code where exception may raise


# to raise the exception, use raise statement
def check(dict):
for k,v in dict.items():
print('Name= {} Balance= {}'.format(k,v))

145
Adv Python Nageswarao Datatechs
if(v<2000.00):
raise MyException('Balance amount is less in the account of
'+k)
# our own exception is handled using try and except blocks
bank = {'Raj':5000.00, 'Vani':8900.50, 'Ajay':1990.00, 'Naresh':3000.00}
try:
check(bank)
except MyException as me:
print(me)

__________________________________________________________________
# 23.understanding logging of error messages.
import logging
# store messages into mylog.txt file.
# store only the messages with level equal to or more than that of ERROR
logging.basicConfig(filename='mylog.txt', level=logging.ERROR)
# these messages are stored into the file.
logging.error("There is an error in the program.")
logging.critical("There is a problem in the design.")
# but these are not stored.
logging.warning("The project is going slow.")
logging.info("You are a junior programmer.")
logging.debug("Line no. 10 contains syntax error.")
__________________________________________________________________
# 24.logging all messages from a program
import logging
# store logging messages into log.txt file
logging.basicConfig(filename='log.txt', level=logging.ERROR)
try:
a = int(input('Enter a number: '))
b = int(input('Enter another number: '))
c = a/b

except Exception as e:
logging.exception(e)

else:
print('The result of division: ', c)
__________________________________________________________________
# 25.creating a file to store characters
# open the file for writing data
f = open('myfile.txt', 'w')
# enter characters from keyboard
str = input('Enter text: ')
# write the string into file
f.write(str)
# closing the file
f.close()
__________________________________________________________________
# 26.reading characters from file
# open the file for reading data

146
Adv Python Nageswarao Datatechs
f = open('myfile.txt', 'r')

# read all characters from file


str = f.read()

# display them on the screen


print(str)

# closing the file


f.close()
__________________________________________________________________
# 27.creating a file with strings
# open the file for writing data
f = open('myfile.txt', 'w')
# enter strings from keyboard
print('Enter text (@ at end): ')
while str != '@':
str = input() # accept string into str
# write the string into file
if(str != '@'):
f.write(str+"\n")
# closing the file
f.close()
__________________________________________________________________
# 28.reading strings from a file
# open the file for reading data
f = open('myfile.txt', 'r')
# read strings from the file
print('The file contents are: ')
str = f.read()
print(str)

# closing the file


f.close()
__________________________________________________________________
# 29.checking if file exists and then reading data
import os, sys
# open the file for reading data
fname = input('Enter filename: ')
if os.path.isfile(fname):
f = open(fname, 'r')
else:
print(fname+' does not exist')
sys.exit()
# read strings from the file
print('The file contents are: ')
str = f.read()
print(str)

# closing the file


f.close()
__________________________________________________________________
# 30.Emp class - Save this as Emp.py

147
Adv Python Nageswarao Datatechs
class Emp:
def __init__(self, id, name, sal):
self.id = id
self.name = name
self.sal = sal
def display(self):
print("{:5d} {:20s} {:10.2f}".format(self.id, self.name, self.sal))

# pickle - store Emp class objects into emp.dat file


import Emp, pickle
# open emp.dat file as a binary file for writing
f = open('emp.dat', 'wb')
n = int(input('How many employees? '))
for i in range(n):
id = int(input('Enter id: '))
name = input('Enter name: ')
sal = float(input('Enter salary: '))

# create Emp class object


e = Emp.Emp(id, name, sal)

# store the object e into the file f


pickle.dump(e, f)
# close the file
f.close()
__________________________________________________________________
# 31.unpickle or object de-serialization
import Emp, pickle
# open the file to read objects
f = open('emp.dat', 'rb')
print('Employees details: ')
while True:
try:
# read object from file f
obj = pickle.load(f)
# display the contents of employee obj
obj.display()

except EOFError:
print('End of file reached...')
break
# close the file
f.close()
__________________________________________________________________
# 32.store a group of strings into a binary file
with open('data.bin', 'wb') as f:
response='Y'
while response=='Y' or response=='y':
str = input('Enter a string: ')
f.write(str.encode())
response = input('Continue (Y/N): ')
__________________________________________________________________

148
Adv Python Nageswarao Datatechs
# 33.to read randomly in binary file
with open('data.bin', 'rb') as f:
# initially fp will be at 0th pos
print(f.tell())

# to read first 10 bytes


str = f.read(10)
print(str.decode())
# after this, fp will be at 10th pos
print(f.tell())
# to read another 10 bytes from present pos
str = f.read(10)
print(str.decode())
# after this, fp will be at 20th pos
print(f.tell())
# to read the last 10 bytes
f.seek(-10, 2)
# after this, fp will be at 10th pos from end
print(f.tell())
str = f.read(10) # now fp will be at end
print(str.decode())
__________________________________________________________________
# 34.zipping the contents of files
from zipfile import *

# create zip file


f = ZipFile('test.zip', 'w', ZIP_DEFLATED)

# add some files. these are zipped


f.write('file1.txt')
f.write('file2.txt')
f.write('file3.txt')
# close the zip file
print('test.zip file created...')
f.close()
__________________________________________________________________
# 35.to view contents of zipped files
from zipfile import *
# Open the zip file
z = ZipFile('test.zip', 'r')
# extract all the file names which are in the zip file
z.extractall()
# close the file
z.close()
__________________________________________________________________
# 36. to display all files having .py extension
import os
# execute dir command of DOS operating system
os.system('dir *.py')
__________________________________________________________________

149
Adv Python Nageswarao Datatechs
# 37. webscraping using regular expression.
import re
import urllib.request
# open the html file using urlopen() method
f = urllib.request.urlopen(r'file:///f|py\breakfast.html')
# read data from the file object into text string
text = f.read()
# convert the byte string into normal string
str = text.decode()
# apply regular expression on the string
result = re.findall(r'<td>\w+</td>\s<td>(\w+)</td>\s<td>(\d\d.\d\d)</td>',
str)

# display result
print(result)
# display the items of the result
for item, price in result:
print('Item= %-15s Price= %-10s' %(item, price))
# close the file
f.close()
__________________________________________________________________
# 38.knowing the time since the epoch
import time
epoch = time.time() # call time() function of time module
print('epoch seconds= ', epoch)
# convert epoch time into date and time
t = time.ctime(epoch)
print('date and time as per epoch= ', t)
__________________________________________________________________
# 39.knowing the current date and time
import time, datetime
dt = time.ctime()
print('Current date and time= ', dt)
dt = datetime.datetime.today()
print('Current date and time= ', dt)
dt = datetime.datetime.now()
print('Current date: {}/{}/{}'.format(dt.day, dt.month, dt.year))
print('Current time: {}:{}:{}'.format(dt.hour, dt.minute, dt.second))
__________________________________________________________________
# 40.combining date and time
from datetime import *
d,m,y = [int(x) for x in input('Enter date, month, year: ').split(',')]
hr,min = [int(x) for x in input('Enter hour, minute: ').split(',')]
d = date(y,m,d)
t = time(hr, min)
dt = datetime.combine(d, t)
print('Created object= ', dt)
__________________________________________________________________
# 41.sorting dates
from datetime import *

150
Adv Python Nageswarao Datatechs

# take an empty list


lst = []
# create date class objects with year, month and date
n = int(input('How many dates? '))
for i in range(n):
d,m,y = [int(x) for x in input('Enter date, month, year: ').split()]
dt = date(y,m,d)
# append it to lst
lst.append(dt)

# sort the list


lst.sort()
# display sorted dates
for i in lst:
print(i)
__________________________________________________________________
# 42.to measure the time taken by the program
from time import *
# note the starting time of the program
t1 = perf_counter()
# do some processing
i, sum = 0, 0
while(i<1000000):
sum+=i
i+=1
# make the PVM sleep for 3 seconds
# this is also measured by the perf_counter()
sleep(3)

# note the ending time of the program


t2 = perf_counter()

# find time for the program in seconds


print('Execution time = %f seconds' %(t2- t1))
__________________________________________________________________
# 43.every Python program is run by main thread
import threading
print('Let us find the current thread')
# find the name of the present thread
print('Currently running thread: ', threading.current_thread().getName())
# check if it is main thread or not
if threading.current_thread() == threading.main_thread():
print('The current thread is the main thread')
else:
print('The current thread is not main thread')
__________________________________________________________________

# 44.creating a thread without using a class


from threading import *
# create a function
def display():

151
Adv Python Nageswarao Datatechs
print('Hello Iam running')

# create a thread and call the function


t = Thread(target=display)

# run the thread


t.start()
__________________________________________________________________
# 45.creating our own thread
from threading import Thread
# create a class as sub class to Thread class
class MyThread(Thread):
# override the run() method of Thread class
def run(self):
print('Hello Iam running')

# create an instance of MyThread class


t = MyThread()
# start running the thread t1
t.start()
__________________________________________________________________

# 46.creating a thread without making sub class to Thread class


from threading import *
# create our own class
class MyThread:

# a method
def display(self):
print('Hello Iam running')
# create an instance to our class
obj = MyThread()
# create a thread to run display method of obj
t = Thread(target=obj.display)
# run the thread
t.start()
__________________________________________________________________
# 47.single tasking using a single thread
from threading import *
from time import *
# create our own class
class MyThread:
# a method that performs 3 tasks one by one
def prepareTea(self):
self.task1()
self.task2()
self.task3()
def task1(self):
print('Boil milk and tea powder for 5 minutes...')
sleep(5)
def task2(self):
print('Add sugar and boil for 3 minutes...')

152
Adv Python Nageswarao Datatechs
sleep(3)

def task3(self):
print('Filter it and serve...')

# create an instance to our class


obj = MyThread()

# create a thread and run prepareTea method of obj


t = Thread(target=obj.prepareTea)
t.start()
__________________________________________________________________
# 48.multi tasking using two threads
from threading import *
from time import *

class Theatre:
# constructor that accepts a string
def __init__(self, str):
self.str = str

# a method that repeats for 10 tickets


def movieshow(self):
for i in range(1, 11):
print(self.str," : ", i)
sleep(1)
# create two instances to Theatre class
obj1 = Theatre('Cut ticket')
obj2 = Theatre('Show chair')
# create two threads to run movieshow()
t1 = Thread(target=obj1.movieshow)
t2 = Thread(target=obj2.movieshow)
# run the threads
t1.start()
t2.start()
__________________________________________________________________
# 49.multi tasking using two threads – observe the wrong output
from threading import *
from time import *
class Railway:
# constructor that accepts no. of available berths
def __init__(self, available):
self.available = available
# a method that reserves berth
def reserve(self, wanted):
# display no. of available berths
print('Available no. of berths= ', self.available)
# if available >= wanted, allot the berth
if(self.available>= wanted):
# find the thread name
name = current_thread().getName()
# display berth is allotted for the person
print('%d berths allotted for %s' %(wanted, name))
# make time delay so that the ticket is printed
sleep(1.5)

153
Adv Python Nageswarao Datatechs
# decrease the no. of available berths
self.available-= wanted
else:
# if available < wanted, then say sorry
print('Sorry, no berths to allot')
# create instance to Railway class
# specify only one berth is available
obj = Railway(1)
# create two threads and specify 1 berth is needed
t1 = Thread(target=obj.reserve, args=(1,))
t2 = Thread(target=obj.reserve, args=(1,))

# give names to the threads


t1.setName('First Person')
t2.setName('Second Person')

# run the threads


t1.start()
t2.start()
__________________________________________________________________
# 50.multi tasking using two threads – synchronize threads
from threading import *
from time import *
class Railway:
# constructor that accepts no. of available berths
def __init__(self, available):
self.available = available
#self.l = Lock() # or, self.l = Semaphore()
# a method that reserves berth
def reserve(self, wanted):
# lock the current object
self.l.acquire()
# display no. of available berths
print('Available no. of berths= ', self.available)

# if available >= wanted, allot the berth


if(self.available>= wanted):
# find the thread name
name = current_thread().getName()
# display berth is allotted for the person
print('%d berths allotted for %s' %(wanted, name))
# make time delay so that the ticket is printed
sleep(1.5)
# decrease the no. of available berths
self.available-= wanted
else:
# if available < wanted, then say sorry
print('Sorry, no berths to allot')
# release the lock since task is completed
self.l.release()
# create instance to Railway class
# specify only one berth is available
obj = Railway(1)
# create two threads and specify 1 berth is needed
t1 = Thread(target=obj.reserve, args=(1,))
t2 = Thread(target=obj.reserve, args=(1,))

154
Adv Python Nageswarao Datatechs

# give names to the threads


t1.setName('First Person')
t2.setName('Second Person')

# run the threads


t1.start()
t2.start()
__________________________________________________________________

# 51.creating root window


from tkinter import *
# create top level window
root = Tk()
# set window title
root.title("My window")
# set window size
root.geometry("400x300")
# display window and wait for any events
root.mainloop()
__________________________________________________________________
# 52.creating a frame in the root window
from tkinter import *
# create top level window
root = Tk()
# set window title
root.title("My frame")
# create a frame as child to root window
f= Frame(root, height=400, width=500, bg="yellow")
# attach the frame to root window
f.pack()
# let the root window wait for any events
root.mainloop()
__________________________________________________________________

# 53.push button
from tkinter import *
# function to be called when the button is clicked
def buttonClick(event):
print('You have clicked me')
# create root window
root = Tk()
# create frame as child to root window
f = Frame(root, height=200, width=300)

# let the frame will not shrink


f.propagate(0)
# attach the frame to root window
f.pack()

155
Adv Python Nageswarao Datatechs

# create a push button as child to frame


b = Button(f, text='My Button', width=15, height=2, bg='yellow', fg='blue',
activebackground='green', activeforeground='red')

# attach button to the frame


b.pack()
# bind the left mouse button with the method to be called
b.bind("<Button-1>", buttonClick)
# the root window handles the mouse click event
root.mainloop()
__________________________________________________________________
# 54.push button creation in the class.
from tkinter import *
class MyButton:
# constructor
def __init__(self, root):
# create frame as child to root window
self.f = Frame(root, height=200, width=300)
# let the frame will not shrink
self.f.propagate(0)
# attach the frame to root window
self.f.pack()
# create a push button as child to frame
self.b = Button(self.f, text='My Button', width=15, height=2,
bg='yellow', fg='blue', activebackground='green', activeforeground='red',
command=self.buttonClick)

# attach button to frame


self.b.pack()

# method
# method to be called when the button is clicked
def buttonClick(event):
print('You have clicked me')
# create root window
root = Tk()
# create MyButton object
mb = MyButton(root)
# display the root window
root.mainloop()
__________________________________________________________________
# 55. push button with a label
from tkinter import *
# this is event handler function
def buttonClick():
# create label as child widget in the frame
lbl = Label(f, text="Welcome to Python", width=20, height=2,
font=('Courier', -30, 'bold underline italic'), fg='blue')
# add label to the frame
lbl.grid(row=2, column=0)

156
Adv Python Nageswarao Datatechs

# create root window


root = Tk()
root.title("My push buttons")
root.geometry('600x500')

# create a frame in the root window


f = Frame(root)
# let the frame does not shrink
f.propagate(0)
# add frame in the root window
f.pack()
# create a push button and bind it to buttonClick function
b1 = Button(f, text='Click Me', width=15, height=2, command=buttonClick)
# create another button that closes the root window upon clicking
b2 = Button(f, text='Close', width=15, height=2, command=quit)
# attach buttons to the frame side by side
b1.grid(row=0, column=1)
b2.grid(row=0, column=2)

# display the root window with widgets


root.mainloop()
__________________________________________________________________
# 56. text widget with scroll bar
from tkinter import *
# create root window
root = Tk()
# create Text widget
t = Text(root, width=25, height=10, font=('Verdana', 14, 'bold'),
fg='blue', bg='yellow', wrap=WORD)
# create a multiline string
str = '''Text widget\nThis text is inserted into the Text widget.\n This is
second line\n and this is third line\nThis is fourth line\n and this is
fifth line\nThis is 6th line\n and this is 7th line\n'''
# insert the string into Text widget
t.insert(END, str)
# add Text widget at left side in the root window
t.pack(side=LEFT)
# create a vertical scroll bar
s = Scrollbar(root, orient=VERTICAL, command= t.yview)
# set the scroll bar to the Text widget
t.configure(yscrollcommand=s.set)
# add the scroll bar at the right side in the root window
s.pack(side=RIGHT, fill=Y)
# display the root window
root.mainloop()
_________________________________________________________________

157
Adv Python Nageswarao Datatechs
# 57. check boxes
from tkinter import *
# create root window
root = Tk()
# create frame and add to root window
f = Frame(root, height=550, width=600)
f.propagate(0)
f.pack()

# function to display user choice


def display():

# retrieve the control variable values


x = var1.get()
y = var2.get()
z = var3.get()
# string is empty initially
str = ''
# catch user choice
if x==1: str+= ' Python '
if y==1: str+= ' Django '
if z==1: str+= ' Data Science '

# display the user selection as a label


lbl = Label(f, text=str, fg='blue').place(x=50, y=150, width=200,
height=20)
# create IntVar class variables
var1 = IntVar()
var2 = IntVar()
var3 = IntVar()

# create check boxes and bind them to display function


c1 = Checkbutton(f, bg='yellow', fg= 'green', font=('Georgia', 20,
'underline'), text='Python', variable= var1, command=display)
c2 = Checkbutton(f, text='Django', variable= var2, command=display)
c3 = Checkbutton(f, text='Data Science', variable= var3, command=display)

# attach check boxes to the frame


c1.place(x=50, y=100)
c2.place(x=200, y=100)
c3.place(x=350, y=100)
# display the root window
root.mainloop()
__________________________________________________________________
# 58. radio buttons
from tkinter import *
# create root window
root = Tk()
# create frame and add it to root window
f = Frame(root, height=550, width=600)
f.propagate(0)
f.pack()
# function to display user choice
def display():

158
Adv Python Nageswarao Datatechs
# retrieve the control variable value
x = var.get()
# string is empty initially
str = ''
# catch user choice
if x==1: str+= ' Your gender is: Male '
if x==2: str+= ' Your gender is: Female '
# display the user selection as a label
lbl = Label(f, text=str, fg='blue').place(x=50, y=150, width=200,
height=20)

# create IntVar class variable


var = IntVar()

# create radio buttons and bind them to display function


r1 = Radiobutton(f, bg='yellow', fg= 'green', font=('Georgia', 20,
'underline'), text='Male', variable= var, value=1, command=display)
r2 = Radiobutton(f, text='Female', variable= var, value=2, command=display)
# attach radio buttons to the frame
r1.place(x=50, y=100)
r2.place(x=160, y=100)

# display the root window


root.mainloop()
__________________________________________________________________
# 59. Entry box
from tkinter import *
# create root window
root = Tk()
root.title("Entry widgets demo")
# function to display the contents of entry boxes
def display(event):
# retrieve the values from the entry widgets
str1 = e1.get()
str2 = e2.get()
# display the values using labels
lbl1 = Label(f, text='Your name is: '+str1).place(x=50, y=200)
lbl2 = Label(f, text='Your password is: '+str2).place(x=50, y=220)

# create a frame as child to root window


f = Frame(root, height=450, width=600)
# let the frame will not shrink
f.propagate(0)
# attach the frame to root window
f.pack()
# labels to be placed before the entry boxes
l1 = Label(text='Enter User name: ')
l2 = Label(text='Enter Password: ')
# create Entry widget for user name
e1 = Entry(f, width=25, fg='blue', bg='yellow', font=('Arial', 14))

159
Adv Python Nageswarao Datatechs
# create Entry widget for pass word. the text in the widget is replaced by
stars (*)
e2 = Entry(f, width=25, fg='blue', bg='yellow', show='*')
# when user presses Enter, bind that event to display method
e2.bind("<Return>", display)
# place labels and entry widgets in the frame
l1.place(x=50, y=100)
e1.place(x=200, y=100)
l2.place(x=50, y=150)
e2.place(x=200, y=150)
# display the root window with all widgets
root.mainloop()
__________________________________________________________________

# 60.spin box demo


from tkinter import *

# create root window


root = Tk()

# create a frame as child to root window


f = Frame(root, height=450, width=600)

# let the frame will not shrink


f.propagate(0)
# attach the frame to root window
f.pack()

# function to display the user selection


def display():
# retrieve the values from the Spinbox widgets
s = val1.get()
# display the values using labels
lbl1 = Label(f, text='Selected city is: '+s).place(x=50, y=220)

# this is control variable for Spinbox


val1 = StringVar()

# create Spinbox with a tuple of strings


s1 = Spinbox(f, values=('Hyderabad', 'Delhi', 'Kolkata', 'Bangalore'),
textvariable=val1, width=15, fg='black', bg='LightGreen', font=('Arial',
14, 'bold italic'))
# create a Button and bind it with display() function
b = Button(f, text='Get values from spinbox', command=display)
# place Spinboxes and button widgets in the frame
s1.place(x=50, y=50)
b.place(x=50, y=150)
# display the root window
root.mainloop()
__________________________________________________________________
# 61.Listbox demo
from tkinter import *
# create root window

160
Adv Python Nageswarao Datatechs
root = Tk()

# title for the root window


root.title("List box demonstration.")

# create frame
f = Frame(root, width=700, height=400)

# let the frame will not shrink


f.propagate(0)

# attach the frame to root window


f.pack()

# function to display selected items from the Listbox into a Text box
def on_select(event):
# create text box to display selected items
t = Text(f, width=40, height=6, wrap=WORD)
t.place(x=300, y=100)

# create an empty list box


lst = []

# know the indexes of the selected items


indexes = lb.curselection()

# retrieve the items names depending on indexes


# append the items names to the list box
for i in indexes:
lst.append(lb.get(i))
# delete the previous content of the text box
t.delete(0.0, END)
# insert the new contents into the text box
t.insert(0.0, lst)
# create a label
lbl = Label(f, text="Click one or more of the Universities below:",
font="Calibri 14")
lbl.place(x=50, y=50)
# create list box with Universities names for multiple selection
lb = Listbox(f, font="Arial 12 bold", fg='blue', bg='yellow', height=8,
selectmode=MULTIPLE)
lb.place(x=50, y=100)

# take a list of items


lst_items = ["Stanford University", "Oxford University", "Texas A&M
University", "Cambridge University", "University of California"]
# using for loop, insert items into list box
for i in lst_items:
lb.insert(END, i)
# bind the ListboxSelect event to on_select() method
lb.bind('<<ListboxSelect>>', on_select)
# display the root window
root.mainloop()
__________________________________________________________________
# 62.to display a menubar with File and Edit menus
from tkinter import *

161
Adv Python Nageswarao Datatechs
root = Tk()
root.title("My Menu")
root.geometry('600x400')

# function to be called when a menu item is clicked


def display():
pass
# create a menubar
mb = Menu(root)
# attach menubar in the root window
root.config(menu=mb)
# create file menu
file = Menu(root, tearoff=1)
# create menu items in the file menu
file.add_command(label='New', command='display')
file.add_command(label='Open', command='display')
file.add_command(label='Save', command='display')
file.add_separator()
file.add_command(label='Exit', command=root.destroy)
# add file menu in the menubar
mb.add_cascade(label='File', menu=file)
# create edit menu
edit = Menu(root, tearoff = 0)
# create menu items in the edit menu
edit.add_command(label='Cut', command = 'display')
edit.add_command(label='Copy', command = 'display')
edit.add_command(label='Paste', command = 'display')
# add edit menu in the menubar
mb.add_cascade(label='Edit', menu=edit)
# display the root window
root.mainloop()
__________________________________________________________________
# 63.reading a website page from Internet and saving it in our
# system
import urllib.request

try:
# store the url of the page into file object
file = urllib.request.urlopen("https://www.python.org/")
# read data from file and store into content object
content = file.read()
except urllib.error.HTTPError:
print('The web page does not exist')
exit()
# open a file for writing
f = open('myfile.html', 'wb')
# write content into the file
f.write(content)

162
Adv Python Nageswarao Datatechs
# close the file
f.close()
__________________________________________________________________

# 64.downloading an image from Internet


import urllib.request

# copy the image url


url = "http://stuffpoint.com/nature/image/43322-nature-sandy-wallpaper.jpg"

# download the image as myimage.jpg in current directory


download = urllib.request.urlretrieve(url, "myimage.jpg")
__________________________________________________________________
# 65.a TCP/IP server that sends messages to client
import socket
# take the server name and port number
host = 'localhost'
port = 5000
# create a socket at server side using TCP/IP protocol
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# bind the socket with server and port number
s.bind((host, port))
# allow maximum 1 connection to the socket
s.listen(1)
# wait till a client accepts connection
c, addr = s.accept()
# display client address
print("Connection from: ", str(addr))
# send messages to the client after encoding into binary string
c.send(b"Hello client, how are U")
msg = "Bye!"
c.send(msg.encode())
# disconnect the server
c.close()
__________________________________________________________________
# 66.a TCP/IP client that receives messages from server
import socket
# take the server name and port number
host = 'localhost'
port = 5000
# create a client side socket using TCP/IP protocol
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# connect it to server and port number
s.connect((host, port))

# receive message string from server, at a time 1024 B


msg = s.recv(1024)
# repeat as long as message strings are not empty
while msg:

163
Adv Python Nageswarao Datatechs
print('Received: '+ msg.decode())
msg = s.recv(1024)

# disconnect the client


s.close()
__________________________________________________________________
# 67.a UDP server that sends messages to client
import socket
import time
# take the server name and port number
host = 'localhost'
port = 5000

# create a socket at server side to use UDP protocol


s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# let the server waits for 5 seconds


time.sleep(5)

# send messages to the client after encoding into binary string


s.sendto(b"Hello client, how are U", (host, port))
msg = "Bye!"
s.sendto(msg.encode(), (host,port))
# disconnect the server
s.close()
__________________________________________________________________

# 68.a UDP client that receives messages from server


import socket

# take the server name and port number


host = 'localhost'
port = 5000
# create a client side socket that uses UDP protocol
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# connect it to server with host name and port number
s.bind((host, port))
# receive message string from server, at a time 1024 B
msg, addr = s.recvfrom(1024)
try:
# let the socket blocks after 5 seconds if the server disconnects
s.settimeout(5)
# repeat as long as message strings are not empty
while msg:
print('Received: '+ msg.decode())
msg, addr = s.recvfrom(1024)
except socket.timeout:
print('Time is over and hence terminating...')
# disconnect the client
s.close()
__________________________________________________________________

164
Adv Python Nageswarao Datatechs
# 69.a server that sends file contents to client
import socket
# take server name and portnumber
host = 'localhost'
port = 6767
# create a TCP socket
s = socket.socket()
# bind socket to host and port number
s.bind((host, port))
# maximum 1 connection is accepted
s.listen(1)
# wait till client accepts a connection
c, addr = s.accept()
print('A client accepted connection')

# accept file name from client


fname = c.recv(1024)

# convert file name into a normal string


fname = str(fname.decode())
print("File name received from client: "+fname)
try:
# open the file at server side
f = open(fname, 'rb')
# read content of the file
content = f.read()
# send file content to client
c.send(content)
print('File content sent to client')

# close the file


f.close()

except FileNotFoundError:
c.send(b'File does not exist')

# disconnect server
c.close()
__________________________________________________________________
# 70.a client that sends and receives data
import socket
# take server name and port number
host = 'localhost'
port = 6767
# create a TCP socket
s = socket.socket()
# connect to server
s.connect((host, port))
# type file name from the keyboard
filename = input("Enter filename: ")

165
Adv Python Nageswarao Datatechs
# send the file name to the server
s.send(filename.encode())
# receive file content from server
content = s.recv(1024)
print(content.decode())
# disconnect the client
s.close()
__________________________________________________________________

# 71.sending email using a Python program


import smtplib
from email.mime.text import MIMEText
# first type the body text for our mail
body = '''This is my text mail. This is sent to you from my Python program.
I think you appreciated me.'''
# create MIMEText class object with body text
msg = MIMEText(body)
# from which address the mail is sent
fromaddr = "nagesh.faculty@gmail.com"
# to which address the mail is sent
toaddr = "nageswara.r@rediffmail.com"
# store the addresses into msg object
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "HAI FRIEND"
# connect to gmail.com server using 587 port number
server = smtplib.SMTP('smtp.gmail.com', 587)
# put the smtp connection in TLS mode.
server.starttls()
# login to the server with your correct password
server.login(fromaddr, "mypassword")
# send the message to the server
server.send_message(msg)
print('Mail sent...')
# close connection with server
server.quit()
__________________________________________________________________
# 72.displaying all rows of emptab
import pymysql
# connect to MySQL database
conn = pymysql.connect(host='localhost', database='world', user='root',
password='nag123')
# prepare a cursor object using cursor() method
cursor = conn.cursor()
# execute a SQL query using execute() method
cursor.execute("select * from emptab")
# get only one row

166
Adv Python Nageswarao Datatechs
row = cursor.fetchone()

# if the row exists


while row is not None:
print(row) # display it
row = cursor.fetchone() # get the next row

# close connection
cursor.close()
conn.close()
__________________________________________________________________
# 73.displaying all rows of emptab - v2.0
import pymysql
# connect to MySQL database
conn = pymysql.connect(host='localhost', database='world', user='root',
password='nag123')

# prepare a cursor object using cursor() method


cursor = conn.cursor()
# execute a SQL query using execute() method
cursor.execute("select * from emptab")
# get all rows
rows = cursor.fetchall()
# display the number of rows
print('Total number of rows= ', cursor.rowcount)
# display the rows from rows object
for row in rows:
print(row) # display each row
# close connection
cursor.close()
conn.close()
__________________________________________________________________
# 74.inserting a row into emptab
import pymysql
# connect to MySQL database
conn = pymysql.connect(host='localhost', database='world', user='root',
password='nag123')
# prepare a cursor object using cursor() method
cursor = conn.cursor()
# prepare SQL query string to insert a row
str = "insert into emptab(eno, ename, sal) values(9999, 'Srinivas',
9999.99)"
try:
# execute the SQL query using execute() method
cursor.execute(str)
# save the changes to the database
conn.commit()
print('1 row inserted...')

167
Adv Python Nageswarao Datatechs
except:
# rollback if there is any error
conn.rollback()
# close connection
cursor.close()
conn.close()
__________________________________________________________________
# 75.deleting a row from emptab depending on eno
import pymysql
# function to delete row from the emptab table
def delete_rows(eno):
# connect to MySQL database
conn = pymysql.connect(host='localhost', database='world',
user='root', password='nag123')
# prepare a cursor object using cursor() method
cursor = conn.cursor()
# prepare SQL query string to delete a row
str = "delete from emptab where eno = '%d'"
# define the arguments
args = (eno)
try:
# execute the SQL query using execute() method
cursor.execute(str % args)

# save the changes to the database


conn.commit()
print('1 row deleted...')
except:
# rollback if there is any error
conn.rollback()
finally:
# close connection
cursor.close()
conn.close()
# enter employee number whose row is to be deleted
x = int(input('Enter eno: '))
# pass eno to delete_rows() function
delete_rows(x)
__________________________________________________________________
# 76.updating the salary in emptab depending on eno
import pymysql
# function to update row from the emptab table
def update_rows(eno):
# connect to MySQL database
conn = pymysql.connect(host='localhost', database='world',
user='root', password='nag123')
# prepare a cursor object using cursor() method
cursor = conn.cursor()

168
Adv Python Nageswarao Datatechs

# prepare SQL query string to update the salary in a row


str = "update emptab set sal = sal+1000 where eno = '%d'"
# define the arguments
args = (eno)
try:
# execute the SQL query using execute() method
cursor.execute(str % args)

# save the changes to the database


conn.commit()
print('1 row updated...')
except:
# rollback if there is any error
conn.rollback()
finally:
# close connection
cursor.close()
conn.close()
# enter employee number whose row is to be updated
x = int(input('Enter eno: '))
# pass eno to update_rows() function
update_rows(x)
__________________________________________________________________
# 77.to retrieve all rows of emptab from Oracle database
import cx_Oracle
# connect to Oracle database
conn = cx_Oracle.connect('SYSTEM/Nagesh123@localhost')
# prepare a cursor object using cursor() method
cursor = conn.cursor()
# execute a SQL query using execute() method
cursor.execute("select * from emptab")
# get only one row
row = cursor.fetchone()
# if the row exists
while row is not None:
print(row) # display it
row = cursor.fetchone() # get the next row
# close connection
cursor.close()
conn.close()
__________________________________________________________________

******* ALL THE BEST FOR YOUR CAREER *********

169

You might also like