Python Part2 New
Python Part2 New
INTRODUCTION TO OOPS
Procedure oriented approach
The main and sub tasks are represented by functions and procedures.
Ex: C, Pascal, FORTRAN.
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
An object is anything that really exists in the world. Object contains behavior -> attributes and actions ->
variables and methods.
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.
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
□ 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.
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.
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
2. Multiple inheritance: deriving sub class from more than one super class.
Syntax: class Subclass(Baseclass1, Baseclass2, … ):
PROGRAMS
12. Derive Child class from both Father and Mother class.
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
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:
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:
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’.
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:
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.
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):
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.
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:
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:
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.
□ 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.
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.
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
91
Adv Python Nageswarao Datatechs
Files with characters
PROGRAMS
25. Create a file and store a group of chars.
26. Read the chars from the file.
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.
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:
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:
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.
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.
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.
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
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)
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’
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.
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.
‘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:
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.
□ 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 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.
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 ', '']
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.
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’
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']
Characters with special significance shown in the following Table can be used in regular expressions.
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'
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.
‘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.
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.
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.
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’)
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)
Example 2: To find current year’s day number and week day name.
Example 3: To format the current time and show it as HH: MM: SS.
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:
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.
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
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.
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:
104
Adv Python Nageswarao Datatechs
time.sleep(2.5) # sleep for 2.5 seconds
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.
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.
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.
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.
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:
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.
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.
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:
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:
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:
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.
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
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:
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:
We can also display an image on the button as shown in the following two steps:
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:
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:
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:
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.
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:
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:
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:
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:
Here, the fixed strings that are displayed in the spin box are mentioned in the ‘values’ option as a tuple, as:
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:
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:
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:
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 = []
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.
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:
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.
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:
PROGRAMS
116
Adv Python Nageswarao Datatechs
63. A program to download a web page from Internet and save it into our computer.
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.
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:
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:
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:
4. The server should wait till a client accepts connection. This is done using accept() method as:
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
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:
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.
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:
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:
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 [email protected].
Note: If the above does not work, try the below way.
Examples for DBMS are MySQL, Oracle, Sybase, SQL Server etc.
□ 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.
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:
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:
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.
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
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:
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:
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:
PROGRAMS
73. To retrieve and display all rows from employee table.
To insert a row into a table, we can use SQL insert command, as:
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:
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.
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:
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.
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:
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.
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:
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:
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.
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 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:
Please see the following sample data in the excel file: empdata.xlsx.
126
Adv Python Nageswarao Datatechs
is possible from csv files, excel files, python dictionaries, tuples list, json data etc.
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
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
>>> r, c = df.shape
>>> r
6
128
Adv Python Nageswarao Datatechs
To display the first 2 or last 2 rows
>>> df.head(2)
>>> df.tail(2)
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
>>> 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
130
Adv Python Nageswarao Datatechs
4 1005 Laxmi Prasanna 12000.75 08-10-00
5 1006 Anant Nag 9999.99 09-09-99
131
Adv Python Nageswarao Datatechs
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
132
Adv Python Nageswarao Datatechs
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
For example, we can plot the empid and salaries from 2 departments: Sales team and Production
team.
import matplotlib.pyplot as plt
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.
plt.show()
135
Adv Python Nageswarao Datatechs
A pie chart shows a circle that is divided into sectors that each represents a proportion of the whole.
136
Adv Python Nageswarao Datatechs
137
Adv Python Nageswarao Datatechs
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)
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()
__________________________________________________________________
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()
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.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 getName(self):
return self.name
def getAddress(self):
return self.addr
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
__________________________________________________________________
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()
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)
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
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')
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))
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())
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
151
Adv Python Nageswarao Datatechs
print('Hello Iam running')
# 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...')
class Theatre:
# constructor that accepts a string
def __init__(self, str):
self.str = str
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,))
154
Adv Python Nageswarao Datatechs
# 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)
155
Adv Python Nageswarao Datatechs
# 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
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()
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)
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()
__________________________________________________________________
160
Adv Python Nageswarao Datatechs
root = Tk()
# create frame
f = Frame(root, width=700, height=400)
# 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)
161
Adv Python Nageswarao Datatechs
root = Tk()
root.title("My Menu")
root.geometry('600x400')
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()
__________________________________________________________________
163
Adv Python Nageswarao Datatechs
print('Received: '+ msg.decode())
msg = s.recv(1024)
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')
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()
__________________________________________________________________
166
Adv Python Nageswarao Datatechs
row = cursor.fetchone()
# 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')
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)
168
Adv Python Nageswarao Datatechs
169