CS 33
CS 33
BCA Semester - 6
Unit-1
Introduction to Python
Page 1 of 65
Unit – 3 Plotting using PyLab
Overview of Python
Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to
be highly readable. It uses English keywords frequently where as other languages use punctuation, and it has
fewer syntactical constructions than other languages.
Python is Interpreted − Python is processed at run me by the interpreter. You do not need to
compile your program before executing it. This is similar to PERL and PHP.
Python is Interactive − You can actually sit at a Python prompt and interact with the interpreter
directly to write your programs.
Python is Object-Oriented − Python supports Object-Oriented style or technique of programming
that encapsulates code within objects.
Python is a Beginner's Language − Python is a great language for the beginner-level programmers
and supports the development of a wide range of applications from simple text processing to WWW
browsers to games.
History of Python
Python was developed by Guido van Rossum in the late eighties and early nineties at the National Research
Institute for Mathematics and Computer Science in the Netherlands.
Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk, and Unix
shell and other scripting languages. Python is copyrighted. Like Perl, Python source code is now available
under the GNU General Public License (GPL). Python is now maintained by a core development team at the
institute, although Guido van Rossum still holds a vital role in directing its progress.
Python 3.0 (Emphasis on removing duplicative constructs and module) December 3, 2008
Python 3.5 (Last updated version) September 13, 2015
Python Features
A simple language which is easier to learn
Python has a very simple and elegant syntax. It's much easier to read and write Python programs compared
to other languages like: C++, Java, C#. Python makes programming fun and allows you to focus on the
solution rather than syntax. If you are a newbie, it's a great choice to start your journey with Python.
Free and open-source: You can freely use and distribute Python, even for commercial use. Not only can you
use and distribute software written in it, you can even make changes to the Python's source code. Python
has a large community constantly improving it in each iteration.
Portability: You can move Python programs from one platform to another, and run it without any changes. It
runs seamlessly on almost all platforms including Windows, Mac OS X and Linux.
Extensible and Embeddable: Suppose an application requires high performance. You can easily combine
pieces of C/C++ or other languages with Python code. This will give your application high performance as
well as scripting capabilities which other languages may not provide out of the box.
Page 2 of 65
CS-33: Programming in Python
A high-level, interpreted language: Unlike C/C++, you don't have to worry about daunting tasks like memory
management, garbage collection and so on. Likewise, when you run Python code, it automatically converts
your code to the language your computer understands. You don't need to worry about any lower-level
operations.
Large standard libraries to solve common tasks: Python has a number of standard libraries which makes life
of a programmer much easier since you don't have to write all the code yourself. For example: Need to
connect MySQL database on a Web server? You can use MySQLdb library using import MySQLdb . Standard
libraries in Python are well tested and used by hundreds of people. So you can be sure that it won't break
your application.
Object-oriented: Everything in Python is an object. Object oriented programming (OOP) helps you solve a
complex problem intuitively. With OOP, you are able to divide these complex problems into smaller sets by
creating objects.
Python Environment Setup: Python is available on a wide variety of platforms including Linux and Mac OS X.
Let's understand how to set up our Python environment.
Applications of Python
Web Applications: You can create scalable Web Apps using frameworks and CMS (Content Management
System) that are built on Python. Some of the popular platforms for creating Web Apps are: Django, Flask,
Pyramid, Plone, Django CMS. Sites like Mozilla, Reddit, Instagram and PBS are written in Python.
Scientific and Numeric Computing: There are numerous libraries available in Python for scientific and
numeric computing. There are libraries like: SciPy and NumPy that are used in general purpose computing.
And, there are specific libraries like: EarthPy for earth science, AstroPy for Astronomy and so on. Also, the
language is heavily used in machine learning, data mining and deep learning.
Creating software Prototypes: Python is slow compared to compiled languages like C++ and Java. It might
not be a good choice if resources are limited and efficiency is a must. However, Python is a great language
for creating prototypes. For example: You can use Pygame (library for creating games) to create your game's
prototype first. If you like the prototype, you can use language like C++ to create the actual game.
Good Language to Teach Programming: Python is used by many companies to teach programming to kids
and newbie. It is a good language with a lot of features and capabilities. Yet, it's one of the easiest languages
to learn because of its simple easy-to-use syntax.
Getting Python
The most up-to-date and current source code, binaries, documentation, news, etc., is available on the official
website of Python https://www.python.org/. You can download Python documentation from
https://www.python.org/doc/. The documentation is available in HTML, PDF, and PostScript formats.
Setting up PATH
Programs and other executable files can be in many directories, so operating systems provide a search path
that lists the directories that the OS searches for executables. The path is stored in an environment variable,
which is a named string maintained by the operating system. This variable contains information available to
the command shell and other programs.
The path variable is named as PATH in Unix or Path in Windows (Unix is case sensitive; Windows is not). In
Mac OS, the installer handles the path details. To invoke the Python interpreter from any particular
directory, you must add the Python directory to your path.
1 PYTHONPATH
It has a role similar to PATH. This variable tells the Python interpreter where to locate the module files imported
into a program. It should include the Python source library directory and the directories containing Python
source code. PYTHONPATH is sometimes preset by the Python installer.
2 PYTHONSTARTUP
It contains the path of an initialization file containing Python source code. It is executed every time you start the
interpreter. It is named as .pythonrc.py in Unix and it contains commands that load utilities or modify
PYTHONPATH.
3 PYTHONCASEOK
It is used in Windows to instruct Python to find the first case-insensitive match in an import statement. Set this
variable to any value to activate it.
4 PYTHONHOME
It is an alternative module search path. It is usually embedded in the PYTHONSTARTUP or PYTHONPATH
directories to make switching module libraries easy.
1. Immediate mode: Typing python in the command line will invoke the interpreter in immediate mode.
We can directly type in Python expressions and press enter to get the output. >>> is the Python prompt.
It tells us that the interpreter is ready for our input. Try typing in 1 + 1 and press enter. We get 2 as the
output. This prompt can be used as a calculator. To exit this mode type exit() or quit() and press enter.
2. Script mode: This mode is used to execute Python program written in a file. Such a file is called a script.
Scripts can be saved to disk for future use. Python scripts have the extension .py, meaning that the
Page 4 of 65
CS-33: Programming in Python
filename ends with .py. To execute this file in script mode we simply write python helloWorld.py at the
command prompt. We can use any text editing software to write a Python script file.
We just need to save it with the .py extension. But using an IDE can make our life a lot easier. IDE is a piece
of software that provides useful features like code hinting, syntax highlighting and checking, file explorers
etc. to the programmer for application development. Using an IDE can get rid of redundant tasks and
significantly decrease the time required for application development. IDLE is a graphical user interface (GUI)
that can be installed along with the Python programming language and is available from the official website.
Python Keywords
Keywords are the reserved words in Python. We cannot use a keyword as variable name, function name or
any other identifier. They are used to define the syntax and structure of the Python language. In Python,
keywords are case sensitive. There are 33 keywords in Python 3.3. This number can vary slightly in course of
time. All the keywords except True, False and None are in lowercase and they must be written as it is. The
list of all the keywords are given below.
Keywords in Python programming language
as elif if or yield
Looking at all the keywords at once and trying to figure out what they mean might be overwhelming. If you
want to have an overview, here is the complete list of all the keywords with examples.
Python Identifiers
Identifier is the name given to entities like class, functions, variables etc. in Python. It helps differentiating
one entity from another.
Page 5 of 65
Unit – 3 Plotting using PyLab
Python Indentation
Most of the programming languages like C, C++, Java use braces { } to define a block of code. Python uses
indentation. A code block (body of a function, loop etc.) starts with indentation and ends with the first
unindebted line. The amount of indentation is up to you, but it must be consistent throughout that block.
Generally four whitespaces are used for indentation and is preferred over tabs. Here is an example.
for i in range(1,11):
print(i)
if i == 5:
break
The enforcement of indentation in Python makes the code look neat and clean. This results into Python
programs that look similar and consistent. Indentation can be ignored in line continuation. But it's a good
idea to always indent. It makes the code more readable.
Python Comments
Comments are very important while writing a program. It describes what's going on inside a program so that
a person looking at the source code does not have a hard time figuring it out. You might forget the key
details of the program you just wrote in a month's time. So taking time to explain these concepts in form of
comments is always fruitful. In Python, we use the hash (#) symbol to start writing a comment. It extends up
to the newline character. Comments are for programmers for better understanding of a program. Python
Interpreter ignores comment.
Multi-line comments
If we have comments that extend multiple lines, one way of doing it is to use hash (#) in the beginning of
each line. Another way of doing this is to use triple quotes, either ''' or """. These triple quotes are generally
used for multi-line strings. But they can be used as multi-line comment as well. Unless they are not
docstrings, they do not generate any extra code.
Docstring in Python
Docstring is short for documentation string. It is a string that occurs as the first statement in a module,
function, class, or method definition. We must write what a function/class does in the docstring. Triple
quotes are used while writing docstrings. For example:
def double(num):
"""Function to double the value"""
return 2*num
Docstring is available to us as the attribute __doc__ of the function. Issue the following code in shell once
you run the above program.
print(double.__doc__)
Variable
In most of the programming languages a variable is a named location used to store data in the memory. Each
variable must have a unique name called identifier. It is helpful to think of variables as container that hold
data which can be changed later throughout programming. None technically, you can suppose variable as a
bag to store books in it and those books can be replaced at any time. Note: In Python we don't assign values
to the variables, whereas Python gives the reference of the object (value) to the variable.
Constants
A constant is a type of variable whose value cannot be changed. It is helpful to think of constants as
containers that hold information which cannot be changed later. Non technically, you can think of constant
as a bag to store some books and those books cannot be replaced once placed inside the bag.
Literals
Literal is a raw data given in a variable or constant. In Python, there are various types of literals they are as
follows:
Page 6 of 65
CS-33: Programming in Python
Numeric Literals
Numeric Literals are immutable (unchangeable). Numeric literals can belong to 3 different numerical types
Integer, Float and Complex.
String literals
A string literal is a sequence of characters surrounded by quotes. We can use both single, double or triple
quotes for a string. And, a character literal is a single character surrounded by single or double quotes.
Boolean literals
A Boolean literal can have any of the two values: True or False.
Special literals
Python contains one special literal i.e. None. We use it to specify to that field that is not created.
Python List
List is an ordered sequence of items. It is one of the most used datatype in Python and is very flexible. All the
items in a list do not need to be of the same type. Declaring a list is pretty straight forward. Items separated
by commas are enclosed within brackets [ ].
a = [1, 2.2, 'python']
>>> a = [1,2,3]
>>> a[2]=4
>>> a
[1, 2, 4]
Python Tuple
Tuple is an ordered sequence of items same as list. The only difference is that tuples are immutable. Tuples
once created cannot be modified. Tuples are used to write-protect data and are usually faster than list as it
cannot change dynamically. It is defined within parentheses () where items are separated by commas.
t = (5,'program', 1+3j)
Python Strings
String is sequence of Unicode characters. We can use single quotes or double quotes to represent strings.
Multi-line strings can be denoted using triple quotes, ''' or """. Like list and tuple, slicing operator [ ] can be
used with string. Strings are immutable.
Python Set
Set is an unordered collection of unique items. Set is defined by values separated by comma inside braces { }.
Items in a set are not ordered. We can perform set operations like union, intersection on two sets. Set have
unique values. They eliminate duplicates.
>>> a = {1,2,2,3,3,3}
>>> a
{1, 2, 3}
Python Dictionary
Dictionary is an unordered collection of key-value pairs. It is generally used when we have a huge amount of
data. Dictionaries are optimized for retrieving data. We must know the key to retrieve the value. In Python,
dictionaries are defined within braces {} with each item being a pair in the form key:value. Key and value can
be of any type.
>>> d = {1:'value','key':2}
Page 7 of 65
Unit – 3 Plotting using PyLab
>>> type(d)
<class 'dict'>
We use key to retrieve the respective value. But not the other way around.
Output formatting
Sometimes we would like to format our output to make it look attractive. This can be done by using the
str.format() method. This method is visible to any string object.
Python Input
Up till now, our programs were static. The value of variables were defined or hard coded into the source
code. To allow flexibility we might want to take the input from the user. In Python, we have the input()
function to allow this. The syntax for input() is
input([prompt])
Python Import
When our program grows bigger, it is a good idea to break it into different modules.
A module is a file containing Python definitions and statements. Python modules have a filename and end
with the extension .py. Definitions inside a module can be imported to another module or the interactive
interpreter in Python. We use the import keyword to do this. For example, we can import the math module
by typing in import math.
import math
print(math.pi)
Now all the definitions inside math module are available in our scope. We can also import some specific
attributes and functions only, using the from keyword.
Arithmetic operators
Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication
etc.
/ Divide left operand by the right one (always results into float) x/y
x % y (remainder of
% Modulus - remainder of the division of left operand by the right
x/y)
// Floor division - division that results into whole number adjusted to the x // y
Page 8 of 65
CS-33: Programming in Python
left in the number line
** Exponent - left operand raised to the power of right x**y (x to the power y)
Comparison operators
Comparison operators are used to compare values. It either returns True or False according to the condition.
> Greater that - True if left operand is greater than the right x>y
< Less that - True if left operand is less than the right x<y
>= Greater than or equal to - True if left operand is greater than or equal to the right x >= y
<= Less than or equal to - True if left operand is less than or equal to the right x <= y
Logical operators
Logical operators are the and, or, not operators.
Bitwise operators
Bitwise operators act on operands as if they were string of binary digits. It operates bit by bit, hence the
name. For example, 2 is 10 in binary and 7 is 111. In the table below: Let x = 10 (0000 1010 in binary) and y =
4 (0000 0100 in binary)
Page 9 of 65
Unit – 3 Plotting using PyLab
Assignment operators
Assignment operators are used in Python to assign values to variables. a = 5 is a simple assignment operator
that assigns the value 5 on the right to the variable a on the left. There are various compound operators in
Python like a += 5 that adds to the variable and later assigns the same. It is equivalent to a = a + 5.
= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
|= x |= 5 x=x|5
^= x ^= 5 x=x^5
Identity operators
is and is not are the identity operators in Python. They are used to check if two values (or variables) are
located on the same part of the memory. Two variables that are equal does not imply that they are identical.
is True if the operands are identical (refer to the same object) x is True
is not True if the operands are not identical (do not refer to the same object) x is not True
Membership operators
in and not in are the membership operators in Python. They are used to test whether a value or variable is
found in a sequence (string, list, tuple, set and dictionary). In a dictionary we can only test for presence of
key, not the value.
Page 10 of 65
CS-33: Programming in Python
These different namespaces are isolated. Hence, the same name that may exist in different modules do not
collide. Modules can have various functions and classes. A local namespace is created when a function is
called, which has all the names defined in it. Similar, is the case with class. Following diagram may help to
clarify this concept.
Here, the variable a is in the global namespace. Variable b is in the local namespace of outer_function() and c
is in the nested local namespace of inner_function(). When we are in inner_function(), c is local to us, b is
nonlocal and a is global. We can read as well as assign new values to c but can only read b and a from
inner_function(). If we try to assign as a value to b, a new variable b is created in the local namespace which
is different than the nonlocal b. Same thing happens when we assign a value to a. However, if we declare a
as global, all the reference and assignment go to the global a. Similarly, if we want to rebind the variable b, it
must be declared as nonlocal.
if test expression:
Page 11 of 65
Unit – 3 Plotting using PyLab
Body of if
else:
Body of else
Here, val is the variable that takes the value of the item inside the sequence on each iteration. Loop
continues until we reach the last item in the sequence. The body of for loop is separated from the rest of the
code using indentation.
Page 12 of 65
CS-33: Programming in Python
In Python, break and continue statements can alter the flow of a normal loop. Loops iterate over a block of
code until test expression is false, but sometimes we wish to terminate the current iteration or even the
whole loop without checking test expression. The break and continue statements are used in these cases.
def function_name(parameters):
"""docstring"""
statement(s)
Above shown is a function definition which consists of following components.
For example:
def greet(name):
"""This function greets to
the person passed in as
parameter"""
print("Hello, " + name + ". Good morning!")
x = 20
my_func()
print("Value outside function:",x)
Output:
Value inside function: 10
Value outside function: 20
Here, we can see that the value of x is 20 initially. Even though the function my_func() changed the value of
x to 10, it did not effect the value outside the function. This is because the variable x inside the function is
different (local to the function) from the one outside. Although they have same names, they are two
different variables with different scope. On the other hand, variables outside of the function are visible from
inside. They have a global scope. We can read these values from inside the function but cannot change
(write) them. In order to modify the value of variables outside the function, they must be declared as global
variables using the keyword global.
Types of Functions
Basically, we can divide functions into the following two types:
Built-in functions - Functions that are built into Python.
User-defined functions - Functions defined by the users themselves.
In the above example, calc_factorial() is a recursive functions as it calls itself. When we call this function with
a positive integer, it will recursively call itself by decreasing the number. Each function call multiples the
number with the factorial of number 1 until the number is equal to one. This recursive call can be explained
in the following steps.
Advantages of Recursion
1. Recursive functions make the code look clean and elegant.
2. A complex task can be broken down into simpler sub-problems using recursion.
3. Sequence generation is easier with recursion than using some nested iteration.
Disadvantages of Recursion
1. Sometimes the logic behind recursion is hard to follow through.
2. Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
3. Recursive functions are hard to debug.
What is a file?
File is a named location on disk to store related information. It is used to permanently store data in a non-
volatile memory (e.g. hard disk). Since, random access memory (RAM) is volatile which loses its data when
computer is turned off, we use files for future use of the data. When we want to read from or write to a file
we need to open it first. When we are done, it needs to be closed, so that resources that are tied with the
file are freed. Hence, in Python, a file operation takes place in the following order.
1. Open a file
2. Read or write (perform operation)
3. Close the file
Page 16 of 65
CS-33: Programming in Python
We can specify the mode while opening a file. In mode, we specify whether we want to read 'r', write 'w' or
append 'a' to the file. We also specify if we want to open the file in text mode or binary mode. The default is
reading in text mode. In this mode, we get strings when reading from the file. On the other hand, binary
mode returns bytes and this is the mode to be used when dealing with non-text files like image or exe files.
Mode Description
'w' Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists.
'x' Open a file for exclusive creation. If the file already exists, the operation fails.
'a' Open for appending at the end of the file without truncating it. Creates a new file if it does not exist.
f = open("test.txt",encoding = 'utf-8')
# perform file operations
f.close()
Page 17 of 65
Unit – 3 Plotting using PyLab
>>> f.read(4) # read the next 4 data
' is '
>>> f.read() # read in the rest till end of file
'my first file\nThis file\ncontains three lines\n'
>>> f.read() # further reading returns empty sting
''
Python File Methods
There are various methods available with the file object. Some of them have been used in above examples.
Here is the complete list of methods in text mode with a brief description.
Python File Methods
Method Description
close() Close an open file. It has no effect if the file is already closed.
detach() Separate the underlying binary buffer from the TextIOBaseand return it.
Read atmost n characters form the file. Reads till end of file if it is
read(n)
negative or None.
Read and return one line from the file. Reads in at most nbytes if
readline(n=-1)
specified.
Resize the file stream to size bytes. If size is not specified, resize to
truncate(size=None)
current location.
write(s) Write string s to the file and return the number of characters written.
Page 18 of 65
CS-33: Programming in Python
directories. Python has the os module, which provides us with many useful methods to work with directories
(and files as well).
#prints 7
print(next(my_iter))
## next(obj) is same as obj.__next__()
#prints 0
print(my_iter.__next__())
#prints 3
print(my_iter.__next__())
## This will raise error, no items left
next(my_iter)
Page 19 of 65
Unit – 3 Plotting using PyLab
Page 20 of 65
CS- 33 Programing in Python
Unit-2
OOP Using Python
CS-33: Programming in Python
Illegal operations can raise exceptions. There are plenty of built-in exceptions in Python that are raised when
corresponding errors occur. This will return us a dictionary of built-in exceptions, functions and attributes.
Some of the common built-in exceptions in Python programming along with the error that cause then are
tabulated below.
KeyboardInterrupt Raised when the user hits interrupt key (Ctrl+c or delete).
RuntimeError Raised when an error does not fall under any other category.
ValueError Raised when a function gets argument of correct type but improper value.
We can also define our own exception in Python (if required). Visit this page to learn more about user-
defined exceptions. We can handle these built-in and user-defined exceptions in Python using try, except
and finally statements.
Page 2 of 65
CS-33: Programming in Python
# import module sys to get the type of exception
import sys
randomList = ['a', 0, 2]
In this program, we loop until the user enters an integer that has a valid reciprocal. The portion that can
cause exception is placed inside try block. If no exception occurs, except block is skipped and normal flow
continues. But if any exception occurs, it is caught by the except block. Here, we print the name of the
exception using ex_info() function inside sys module and ask the user to try again. We can see that the
values 'a' and '1.3' causes ValueError and '0' causes ZeroDivisionError.
try...finally
The try statement in Python can have an optional finally clause. This clause is executed no matter what, and
is generally used to release external resources. For example, we may be connected to a remote data center
through the network or working with a file or working with a Graphical User Interface (GUI). In all these
circumstances, we must clean up the resource once used, whether it was successful or not. These actions
(closing a file, GUI or disconnecting from network) are performed in the finally clause to guarantee
execution. Here is an example of file operations to illustrate this.
try:
f = open("test.txt",encoding = 'utf-8')
# perform file operations
finally:
Page 3 of 65
f.close()
This type of construct makes sure the file is closed even if an exception occurs.
In Python, users can define such exceptions by creating a new class. This exception class has to be derived,
either directly or indirectly, from Exception class. Most of the built-in exceptions are also derived form this
class. When we are developing a large Python program, it is a good practice to place all the user-defined
exceptions that our program raises in a separate file. Many standard modules do this. They define their
exceptions separately as exceptions.py or errors.py (generally but not always).
User-defined exception class can implement everything a normal class can do, but we generally make them
simple and concise. Most implementations declare a custom base class and derive others exception classes
from this base class. This concept is made clearer in the following example.
Page 4 of 65
CS-33: Programming in Python
It is also a debugging tool as it brings the program on halt as soon as any error is occurred and shows on
which point of the program error has occurred. You can learn more about assertions in the article: The
benefits of programming with Assertions. We can be clear by looking at the flowchart below:
Polymorphism A concept of using common operation in different ways for different data input.
Class
A class is a blueprint for the object. We can think of class as an sketch of a parrot with labels. It contains all
the details about the name, colors, size etc. Based on these descriptions, we can study about the parrot.
Here, parrot is an object. The example for class of parrot can be :
class Parrot:
pass
Here, we use class keyword to define an empty class Parrot. From class, we construct instances. An instance
is a specific object created from a particular class.
Object
An object (instance) is an instantiation of a class. When class is defined, only the description for the object is
defined. Therefore, no memory or storage is allocated. The example for object of parrot class can be:
obj = Parrot()
Here, obj is object of class Parrot. Suppose we have details of parrot. Now, we are going to show how to
build the class and objects of parrot. Example to Creating Class and Object in Python:
class Parrot:
# class attribute
species = "bird"
# instance attribute
def __init__(self, name, age):
self.name = name
self.age = age
# instantiate the Parrot class
blu = Parrot("Blu", 10)
woo = Parrot("Woo", 15)
# access the class attributes
print("Blu is a {}".format(blu.__class__.species))
print("Woo is also a {}".format(woo.__class__.species))
Page 6 of 65
CS-33: Programming in Python
# access the instance attributes
print("{} is {} years old".format( blu.name, blu.age))
print("{} is {} years old".format( woo.name, woo.age))
When we run the program, the output will be:
Blu is a bird
Woo is also a bird
Blu is 10 years old
Woo is 15 years old
In the above program, we create a class with name Parrot. Then, we define attributes. The attributes are a
characteristic of an object. Then, we create instances of the Parrot class. Here, blu and woo are references
(value) to our new objects.
Then, we access the class attribute using __class __.species. Class attributes are same for all instances of a
class. Similarly, we access the instance attributes using blu.name and blu.age. However, instance attributes
are different for every instance of a class. To learn more about classes and objects, go to Python Classes and
Objects
Methods
Methods are functions defined inside the body of a class. They are used to define the behaviors of an object.
Example to Creating Methods in Python:
class Parrot:
# instance attributes
def __init__(self, name, age):
self.name = name
self.age = age
# instance method
def sing(self, song):
return "{} sings {}".format(self.name, song)
def dance(self):
return "{} is now dancing".format(self.name)
# instantiate the object
blu = Parrot("Blu", 10)
# call our instance methods
print(blu.sing("'Happy'"))
print(blu.dance())
When we run program, the output will be:
Blu sings 'Happy'
Blu is now dancing
In the above program, we define two methods i.e sing() and dance(). These are called instance method
because they are called on an instance object i.e blu.
Inheritance
Inheritance is a way of creating new class for using details of existing class without modifying it. The newly
formed class is a derived class (or child class). Similarly, the existing class is a base class (or parent class).
Example to Use of Inheritance in Python:
# parent class
class Bird:
def __init__(self):
print("Bird is ready")
def whoisThis(self):
print("Bird")
def swim(self):
print("Swim faster")
# child class
class Penguin(Bird):
def __init__(self):
# call super() function
super().__init__()
Page 7 of 65
print("Penguin is ready")
def whoisThis(self):
print("Penguin")
def run(self):
print("Run faster")
peggy = Penguin()
peggy.whoisThis()
peggy.swim()
peggy.run()
When we run this program, the output will be:
Bird is ready
Penguin is ready
Penguin
Swim faster
Run faster
In the above program, we created two classes i.e. Bird (parent class) and Penguin (child class). The child class
inherits the functions of parent class. We can see this from swim() method. Again, the child class modified
the behavior of parent class. We can see this from whoisThis() method. Furthermore, we extend the
functions of parent class, by creating a new run() method. Additionally, we use super() function before
__init__() method. This is because we want to pull the content of __init__() method from the parent class
into the child class.
Encapsulation
Using OOP in Python, we can restrict access to methods and variables. This prevent data from direct
modification which is called encapsulation. In Python, we denote private attribute using underscore as prefix
i.e single “ _ “ or double “ __“. Example for Data Encapsulation in Python:
class Computer:
def __init__(self):
self.__maxprice = 900
def sell(self):
print("Selling Price: {}".format(self.__maxprice))
def setMaxPrice(self, price):
self.__maxprice = price
c = Computer()
c.sell()
# change the price
c.__maxprice = 1000
c.sell()
# using setter function
c.setMaxPrice(1000)
c.sell()
When we run this program, the output will be:
Selling Price: 900
Selling Price: 900
Selling Price: 1000
In the above program, we defined a class Computer. We use __init__() method to store the maximum selling
price of computer. We tried to modify the price. However, we can’t change it because Python treats the
__maxprice as private attributes. To change the value, we used a setter function i.e setMaxPrice() which
takes price as parameter.
Polymorphism
Polymorphism is an ability (in OOP) to use common interface for multiple form (data types). Suppose, we
need to color a shape, there are multiple shape option (rectangle, square, circle). However we could use
same method to color any shape. This concept is called Polymorphism. Example for Using Polymorphism in
Python:
Page 8 of 65
CS-33: Programming in Python
class Parrot:
def fly(self):
print("Parrot can fly")
def swim(self):
print("Parrot can't swim")
class Penguin:
def fly(self):
print("Penguin can't fly")
def swim(self):
print("Penguin can swim")
# common interface
def flying_test(bird):
bird.fly()
#instantiate objects
blu = Parrot()
peggy = Penguin()
# passing the object
flying_test(blu)
flying_test(peggy)
When we run above program, the output will be:
Parrot can fly
Penguin can't fly
In the above program, we defined two classes Parrot and Penguin. Each of them have common method fly()
method. However, their functions are different. To allow polymorphism, we created common interface i.e
flying_test() function that can take any object. Then, we passed the objects blu and peggy in the flying_test()
function, it ran effectively.
class MyClass:
"This is my second class"
Page 9 of 65
a = 10
def func(self):
print('Hello')
# Output: 10
print(MyClass.a)
# Output: <function MyClass.func at 0x0000000003079BF8>
print(MyClass.func)
# Output: 'This is my second class'
print(MyClass.__doc__)
When you run the program, the output will be:
10
<function 0x7feaa932eae8="" at="" myclass.func="">
This is my second class
Creating an Object in Python
We saw that the class object could be used to access different attributes. It can also be used to create new
object instances (instantiation) of that class. The procedure to create an object is similar to a function call.
>>> ob = MyClass()
This will create a new instance object named ob. We can access attributes of objects using the object name
prefix. Attributes may be data or method. Method of an object are corresponding functions of that class. Any
function object that is a class attribute defines a method for objects of that class. This means to say, since
MyClass.func is a function object (attribute of class), ob.func will be a method object.
class MyClass:
"This is my second class"
a = 10
def func(self):
print('Hello')
# create a new MyClass
ob = MyClass()
# Output: <function MyClass.func at 0x000000000335B0D0>
print(MyClass.func)
# Output: <bound method MyClass.func of <__main__.MyClass object at
0x000000000332DEF0>>
print(ob.func)
# Calling function func()
# Output: Hello
ob.func()
You may have noticed the self parameter in function definition inside the class but, we called the method
simply as ob.func() without any arguments. It still worked. This is because, whenever an object calls its
method, the object itself is passed as the first argument. So, ob.func() translates into MyClass.func(ob). In
general, calling a method with a list of n arguments is equivalent to calling the corresponding function with
an argument list that is created by inserting the method's object before the first argument.
For these reasons, the first argument of the function in class must be the object itself. This is conventionally
called self. It can be named otherwise but we highly recommend to follow the convention. Now you must be
familiar with class object, instance object, function object, method object and their differences.
Constructors in Python
Class functions that begins with double underscore (__) are called special functions as they have special
meaning. Of one particular interest is the __init__() function. This special function gets called whenever a
new object of that class is instantiated. This type of function is also called constructors in Object Oriented
Programming (OOP). We normally use it to initialize all the variables.
class ComplexNumber:
def __init__(self,r = 0,i = 0):
self.real = r
self.imag = i
def getData(self):
print("{0}+{1}j".format(self.real,self.imag))
Page 10 of 65
CS-33: Programming in Python
# Create a new ComplexNumber object
c1 = ComplexNumber(2,3)
# Call getData() function
# Output: 2+3j
c1.getData()
# Create another ComplexNumber object
# and create a new attribute 'attr'
c2 = ComplexNumber(5)
c2.attr = 10
# Output: (5, 0, 10)
print((c2.real, c2.imag, c2.attr))
# but c1 object doesn't have attribute 'attr'
# AttributeError: 'ComplexNumber' object has no attribute 'attr'
c1.attr
In the above example, we define a new class to represent complex numbers. It has two functions, __init__()
to initialize the variables (defaults to zero) and getData() to display the number properly. An interesting thing
to note in the above step is that attributes of an object can be created on the fly. We created a new attribute
attr for object c2 and we read it as well. But this did not create that attribute for object c1.
What is Inheritance?
Inheritance is a powerful feature in object oriented programming. It refers to defining a new class with little
or no modification to an existing class. The new class is called derived (or child) class and the one from which
it inherits is called the base (or parent) class. Python Inheritance Syntax:
class BaseClass:
Body of base class
class DerivedClass(BaseClass):
Body of derived class
Derived class inherits features from the base class, adding new features to it. This results into re-usability of
code.
Generally when overriding a base method, we tend to extend the definition rather than simply replace it.
The same is being done by calling the method in base class from the one in derived class (calling
Polygon.__init__() from __init__() in Triangle). A better option would be to use the built-in function super().
Page 11 of 65
So, super().__init__(3) is equivalent to Polygon.__init__(self,3) and is preferred. You can learn more about
the super() function in Python.
Two built-in functions isinstance() and issubclass() are used to check inheritances. Function isinstance()
returns True if the object is an instance of the class or other classes derived from it. Each and every class in
Python inherits from the base class object.
Search Algorithms
A search algorithm is a method for finding an item or group of items with specific properties within a
collection of items. We refer to the collection of items as a search space. The search space might be
something concrete, such as a set of electronic medical records, or something abstract, such as the set of all
integers. A large number of problems that occur in practice can be formulated as search problems.
Many of the algorithms presented earlier in this book can be viewed as search algorithms. We formulated
finding an approximation to the roots of a polynomial as a search problem, and looked at three algorithms—
exhaustive enumeration, bisection search, and Newton-Raphson—for searching the space of possible
answers. In this section, we will examine two algorithms for searching a list. Each meets the specification:
Page 12 of 65
CS-33: Programming in Python
def search(L, e):
"""Assumes L is a list.
Returns True if e is in L and False otherwise"""
The astute reader might wonder if this is not semantically equivalent to the Python expression e in L. The
answer is yes, it is. And if one is unconcerned about the efficiency of discovering whether e is in L, one
should simply write that expression.
Sorting Algorithms
We have just seen that if we happen to know that a list is sorted, we can exploit that information to greatly
reduce the time needed to search a list. Does this mean that when asked to search a list one should first sort
it and then perform the search?
Let O(sortComplexity(L)) be the complexity of sorting a list. Since we know that we can always search a list in
O(len(L)) time, the question of whether we should first sort and then search boils down to the question, is
(sortComplexity(L) + log(len(L))) < len(L)? The answer, sadly, is no. One cannot sort a list without looking at
each element in the list at least once, so it is not possible to sort a list in sub-linear time.
Does this mean that binary search is an intellectual curiosity of no practical import? Happily, no. Suppose
that one expects to search the same list many times. It might well make sense to pay the overhead of sorting
the list once, and then amortize the cost of the sort over many searches. If we expect to search the list k
times, the relevant question becomes, is (sortComplexity(L) + k*log(len(L))) less than k*len(L)? As k becomes
large, the time required to sort the list becomes increasingly irrelevant.
How big k needs to be depends upon how long it takes to sort a list. If, for example, sorting were exponential
in the size of the list, k would have to be quite large.
Page 13 of 65
Hash Tables
If we put merge sort together with binary search, we have a nice way to search lists. We use merge sort to
preprocess the list in O(n*log(n)) time, and then we use binary search to test whether elements are in the
list in O(log(n)) time. If we search the list k times, the overall time complexity is O(n*log(n) + k*log(n)). This is
good, but we can still ask, is logarithmic the best that we can do for search when we are willing to do some
preprocessing?
When we introduced the type dict we said that dictionaries use a technique called hashing to do the lookup
in time that is nearly independent of the size of the dictionary. The basic idea behind a hash table is simple.
We convert the key to an integer, and then use that integer to index into a list, which can be done in
constant time. In principle, values of any immutable type can be easily converted to an integer. After all, we
know that the internal representation of each object is a sequence of bits, and any sequence of bits can be
viewed as representing an integer. For example, the internal representation of 'abc' is the string of bits
011000010110001001100011, which can be viewed as a representation of the decimal integer 6,382,179. Of
course, if we want to use the internal representation of strings as indices into a list, the list is going to have
to be pretty darn long.
Page 14 of 65
CS- 33 Programing in Python
Unit-3
Plotting using PyLab
CS-33: Programming in Python
Often text is the best way to communicate information, but sometimes there is a lot of truth to the Chinese
proverb, “A picture's meaning can express ten thousand words”. Yet most programs rely on textual output
to communicate with their users. Why? Because in many programming languages presenting visual data is
too hard. Fortunately, it is simple to do in Python.
Pylab is a programming environment, built on a set of unofficial python tools and libraries that turns Python
into a high-performance scientific computing platform. The name pylab comes in part from the resemblance
of the resulting environment to MATLAB. The components of pylab have developed largely independently,
so there's no unique or "official" distribution. Nonetheless, there are at least four core components (in
addition the standard python distribution) required to have an environment that can reasonably be
considered a pylab environment. These are:
NumPy: this is a set of high-performance libraries (implemented in Fortran and C) that implement
contiguous-memory multidimensional arrays, BLAS and LAPACK linear algebra routines and many other
useful numerical tools. This is listed first because all other components depend on it.
Matplotlib: this is pylab's plotting library. It is set up to seem familiar to users accustomed to Matlab's
plotting utilities, but it is in many ways much more powerful and flexible (It lets you choose between many
different backend renderers, for example, and allows you to build plots in an object-oriented manner).
Matplotlib is an excellent 2D and 3D graphics library for generating scientific figures. Some of the many
advantages of this library include:
Easy to get started
Support for LATEX formatted labels and texts
Great control of every element in a figure, including figure size and DPI.
High-quality output in many formats, including PNG, PDF, SVG, EPS.
GUI for interactively exploring figures and support for headless generation of figure files (useful for
batch jobs).
One of the key features of matplotlib is that all aspects of the figure can be controlled programmatically (i.e.,
without needing to muck around with the GUI). This is important for reproducibility and convenient when
one needs to regenerate the figure with updated data or change its appearance. More information at the
Matplotlib web page: http://matplotlib.org/
Matplotlib is automatically included as part of the interactive pylab namespace, but if you need to import it
in its own namespace (e.g., in a non-interactive script or module).
SciPy: this is a set of mostly distinct modules implementing a variety of really useful scientific computing
tasks, including signal processing, FFTs, optimization, statistics, interpolation, numerical integration, etc. It
contains a lot of stuff that you would expect to see in any good scientific programming environment. Though
it depends strongly on Numpy, it is not as completely integrated into the pylab environment as are the other
components. As a result, you'll need to explicitly import most modules from scipy even if you've already
imported the pylab namespace.
Page 1 of 65
Let’s start with a simple example that uses pylab.plot to produce two plots.
import pylab
pylab.figure(1) #create figure 1
pylab.plot([1,2,3,4], [1,7,3,5]) #draw on figure 1
pylab.show() #show figure on screen
will cause a window to appear on your computer monitor. Its exact appearance may depend on the
operating system on your machine, but it will look similar to the following:
Parts of a Chart:
Page 2 of 65
CS-33: Programming in Python
Functions used for plotting:
Plot():
The two parameters of pylab.plot must be sequences of the same length. The first specifies the x-
coordinates of the points to be plotted, and the second specifies the y-coordinates. Together, they provide a
sequence of four <x, y> coordinate pairs, [(1,1), (2,7), (3,3), (4,5)]. These are plotted in order. As each point is
plotted, a line is drawn connecting it to the previous point. plot() is a versatile command, and will take an
arbitrary number of arguments. For example, to plot x versus y. For every x, y pair of arguments, there is an
optional third argument which is the format string that indicates the color and line type of the plot. The
letters and symbols of the format string are from MATLAB, and you concatenate a color string with a line
style string. The default format string is ‘b-‘, which is a solid blue line.
Show():
pylab.show(), causes the window to appear on the computer screen. If that line were not present, the figure
would still have been produced, but it would not have been displayed. pylab.show() causes the process
running Python to be suspended until the figure is closed. The usual workaround is to ensure that
pylab.show() is the last line of code to be executed.
Xlabel():
Pylab.xlabel(), causes to set title of x-axis. One should pass the string value with the method that shows the
values on x-axis.
Ylabel():
Pylab.ylabel(), causes to set title of y-axis. One should pass the string value with the method that shows the
values on x-axis.
Title():
Pylab.title(), causes to display title on the entire plot. One should pass the string value with the method, and
it should be relevant with the entire plot area.
Hist():
Plot a histogram. Compute and draw the histogram of x. The return value is a tuple (n, bins, patches) or ([n0,
n1, ...], bins, [patches0, patches1,...]) if the input contains multiple data. Multiple data can be provided via x
as a list of datasets of potentially different length ([x0, x1, ...]), or as a 2-D ndarray in which each column is a
dataset. Note that the ndarray form is transposed relative to the list form.
Legend():
Places a legend on the axes. To make a legend for lines which already exist on the axes (via plot for instance),
simply call this function with an iterable of strings, one for each legend item. For example:
pylab.plot([1, 2, 3])
pylab.legend(['A simple line'])
Towards the end of the twentieth century, mortgages started getting a lot more complicated. People could
get lower interest rates by paying “points” at the time they took on the mortgage. A point is a cash payment
of 1% of the value of the loan. People could take mortgages that were “interest-only” for a period of time.
That is to say, for some number of months at the start of the loan the borrower paid only the accrued
interest and none of the principal. Other loans involved multiple rates. Typically the initial rate (called a
Page 3 of 65
“teaser rate”) was low, and then it went up over time. Many of these loans were variable-rate—the rate to
be paid after the initial period would vary depending upon some index intended to reflect the cost to the
lender of borrowing on the wholesale credit market. We worked our way through a hierarchy of mortgages
as way of illustrating the use of subclassing.
We concluded that chapter by observing that “our program should be producing plots designed to show how
the mortgage behaves over time.” enhances class Mortgage by adding methods that make it convenient to
produce such plots. (The function findPayment, which is used in Mortgage) The methods plotPayments and
plotBalance are simple one-liners, but they do use a form of pylab.plot that we have not yet seen.
def findPayment(loan, r, m):
"""Assumes: loan and r are floats, m an int
Returns the monthly payment for a mortgage of size
loan at a monthly rate of r for m months"""
return loan*((r*(1+r)**m)/((1+r)**m - 1))
class Mortgage(object):
"""Abstract class for building different kinds of mortgages"""
def __init__(self, loan, annRate, months):
"""Create a new mortgage"""
self.loan = loan
self.rate = annRate/12.0
self.months = months
self.paid = [0.0]
self.owed = [loan]
self.payment = findPayment(loan, self.rate, months)
self.legend = None #description of mortgage
def makePayment(self):
"""Make a payment"""
self.paid.append(self.payment)
reduction = self.payment - self.owed[-1]*self.rate
self.owed.append(self.owed[-1] - reduction)
def getTotalPaid(self):
"""Return the total amount paid so far"""
return sum(self.paid)
def __str__(self):
return self.legend
Page 4 of 65
CS-33: Programming in Python
Notice that we are computing the same values over and over again. For example fib gets called with 3 three
times, and each of these calls provokes four additional calls of fib. It doesn’t require a genius to think that it
might be a good idea to record the value returned by the first call, and then look it up rather than compute it
each time it is needed. This is called memoization, and is the key idea behind dynamic programming.
def fastFib(n, memo = {}):
"""Assumes n is an int >= 0, memo used only by recursive calls
Returns Fibonacci of n"""
if n == 0 or n == 1:
return 1
try:
return memo[n]
except KeyError:
result = fastFib(n-1, memo) + fastFib(n-2, memo)
memo[n] = result
return result
If you try running fastFib, you will see that it is indeed quite fast: fib(120) returns almost instantly. What is
the complexity of fastFib? It calls fib exactly once for each value from 0 to n. Therefore, under the
assumption that dictionary lookup can be done in constant time, the time complexity of fastFib(n) is O(n).
Fortunately, the situation is not as bad as it seems. Dynamic programming provides a practical method for
solving most 0/1 knapsack problems in a reasonable amount of time. As a first step in deriving such a
solution, we begin with an exponential solution based on exhaustive enumeration. The key idea is to think
about exploring the space of possible solutions by constructing a rooted binary tree that enumerates all
states that satisfy the weight constraint. A rooted binary tree is an acyclic directed graph in which
• There is exactly one node with no parents. This is called the root.
• Each non-root node has exactly one parent.
• Each node has at most two children. A childless node is called a leaf.
Each node in the search tree for the 0/1 knapsack problem is labeled with a quadruple that denotes a partial
solution to the knapsack problem
For example, computing the 19th Fibonacci number is not a substantially smaller problem than computing
the 20th Fibonacci number. Another important distinction is that the efficiency of divide-and-conquer
algorithms does not depend upon structuring the algorithm so that the same problems are solved
repeatedly. In contrast, dynamic programming is efficient only when the number of distinct subproblems is
significantly smaller than the total number of subproblems.
Page 5 of 65
CS- 33 Programing in Python
Unit-4
Network Programming and GUI using Python
Network Programming
Python provides two levels of access to network services. At a low level, you can access the basic socket
support in the underlying operating system, which allows you to implement clients and servers for both
connection-oriented and connectionless protocols. Python also has libraries that provide higher-level access
to specific application-level network protocols, such as FTP, HTTP, and so on.
Protocol: In networking, a protocol is a set of rules for formatting and processing data. Network protocols
are like a common language for computers. The computers within a network may use vastly different
software and hardware; however, the use of protocols enables them to communicate with each other
regardless. Standardized protocols are like a common language that computers can use, similar to how two
people from different parts of the world may not understand each other's native languages, but they can
communicate using a shared third language. If one computer uses the Internet Protocol (IP) and a second
computer does as well, they will be able to communicate — just as the United Nations relies on its 6 official
languages to communicate amongst representatives from all over the globe. But if one computer uses IP and
the other does not know this protocol, they will be unable to communicate. On the Internet, there are
different protocols for different types of processes. Protocols are often discussed in terms of which OSI
model layer they belong to.
Sockets: Sockets are the endpoints of a bidirectional communications channel. Sockets may communicate
within a process, between processes on the same machine, or between processes on different continents.
Sockets may be implemented over a number of different channel types: Unix domain sockets, TCP, UDP, and
so on. The socket library provides specific classes for handling the common transports as well as a generic
interface for handling the rest.
To create a socket, you must use the socket.socket() function available in socket module, which has the
general syntax:
s = socket.socket (socket_family, socket_type, protocol=0)
Once you have socket object, then you can use required functions to create your client or server program.
Following is the list of functions required:
Server Socket Methods
1 s.bind()
This method binds address (hostname, port number pair) to socket.
2 s.listen()
This method sets up and start TCP listener.
3 s.accept()
This passively accept TCP client connection, waiting until connection
arrives (blocking).
Page 1 of 65
Unit – 4 Regular Expressions
Client Socket Methods
1 s.connect()
This method actively initiates TCP server connection.
1 s.recv()
This method receives TCP message
2 s.send()
This method transmits TCP message
3 s.recvfrom()
This method receives UDP message
4 s.sendto()
This method transmits UDP message
5 s.close()
This method closes socket
6 socket.gethostname()
Returns the hostname.
Python Internet modules: A list of some important modules in Python Network/Internet programming.
o Knowing IP Address
o URL, Reading the Source Code of a Web Page
o Downloading a Web Page from Internet
Page 2 of 65
o Downloading an Image from Internet
o A TCP/IP Server, A TCP/IP Client
o A UDP Server, A UDP Client
o File Server, File Client
A Simple Client: Let us write a very simple client program which opens a connection to a given port 12345
and given host. This is very simple to create a socket client using Python's socket module function. The
socket.connect(hosname, port ) opens a TCP connection to hostname on the port. Once you have a socket
open, you can read from it like any IO object. When done, remember to close it, as you would close a file.
The following code is a very simple client that connects to a given host and port, reads any available data
from the socket, and then exits:
import socket # Import socket module
s.connect((host, port))
print s.recv(1024)
s.close()
Sending a Simple Mail: Simple Mail Transfer Protocol (SMTP) is a protocol, which handles sending e-mail and
routing e-mail between mail servers. Python provides smtplib module, which defines an SMTP client session
object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener daemon. Here
is a simple syntax to create one SMTP object, which can later be used to send an e-mail:
import smtplib
smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )
An SMTP object has an instance method called sendmail, which is typically used to do the work of mailing a
message. It takes three parameters:
The sender − A string with the address of the sender.
The receivers − A list of strings, one for each recipient.
The message − A message as a string forma ed as specified in the various RFCs.
Example…
import smtplib
sender = '[email protected]'
receivers = ['[email protected]']
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
Here, you have placed a basic e-mail in message, using a triple quote, taking care to format the headers
correctly. An e-mail requires a From, To, and Subject header, separated from the body of the e-mail with a
blank line. To send the mail you use smtpObj to connect to the SMTP server on the local machine and then
use the sendmail method along with the message, the from address, and the destination address as
parameters (even though the from and to addresses are within the e-mail itself, these aren't always used to
route mail). If you are not running an SMTP server on your local machine, you can use smtplib client to
communicate with a remote SMTP server.
GUI Programming
Event-driven programming paradigm: Eventually, the flow of a program depends upon the events, and
programming which focuses on events is called Event-Driven programming. We were only dealing with
either parallel or sequential models, but now we will discuss the asynchronous model. The programming
model following the concept of Event-Driven programming is called the Asynchronous model. The working of
Event-Driven programming depends upon the events happening in a program. Other than this, it depends
Page 4 of 65
upon the program's event loops that always listen to a new incoming event in the program. Once an event
loop starts in the program, then only the events will decide what will execute and in which order.
Example:
import Tkinter
top = Tkinter.Tk()
# Code to add widgets will go here...
top.mainloop()
Tkinter Widgets: Tkinter provides various controls, such as buttons, labels and text boxes used in a GUI
application. These controls are commonly called widgets. There are currently different types of widgets in
Tkinter. We present these widgets as well as a brief description in the following sections:
Buttons: The Button widget is used to add buttons in a Python application. These buttons can display text or
images that convey the purpose of the buttons. You can attach a function or a method to a button which is
called automatically when you click the button. Here is the simple syntax to create this widget:
w = Button (master, option=value, ...)
Parameters
master − This represents the parent window.
options − Here is the list of most commonly used op ons for this widget. These op ons can be used
as key-value pairs separated by commas.
1 activebackground
Background color when the button is under the cursor.
2 activeforeground
Foreground color when the button is under the cursor.
3 bd
Border width in pixels. Default is 2.
4 bg
Normal background color.
5 command
Function or method to be called when the button is clicked.
6 fg
Normal foreground (text) color.
Page 5 of 65
Unit – 4 Regular Expressions
7 font
Text font to be used for the button's label.
8 height
Height of the button in text lines (for textual buttons) or pixels (for
images).
9 highlightcolor
The color of the focus highlight when the widget has focus.
10 image
Image to be displayed on the button (instead of text).
11 justify
How to show multiple text lines: LEFT to left-justify each line; CENTER
to center them; or RIGHT to right-justify.
12 padx
Additional padding left and right of the text.
13 pady
Additional padding above and below the text.
14 relief
Relief specifies the type of the border. Some of the values are
SUNKEN, RAISED, GROOVE, and RIDGE.
15 state
Set this option to DISABLED to gray out the button and make it
unresponsive. Has the value ACTIVE when the mouse is over it.
Default is NORMAL.
16 underline
Default is -1, meaning that no character of the text on the button will
be underlined. If nonnegative, the corresponding text character will
be underlined.
17 width
Width of the button in letters (if displaying text) or pixels (if displaying
an image).
18 wraplength
If this value is set to a positive number, the text lines will be wrapped
to fit within this length.
1 flash()
Causes the button to flash several times between active and normal colors.
Leaves the button in the state it was in originally. Ignored if the button is
disabled.
Page 6 of 65
2 invoke()
Calls the button's callback, and returns what that function returns. Has no effect
if the button is disabled or there is no callback.
Example:
import Tkinter
import tkMessageBox
top = Tkinter.Tk()
def helloCallBack():
tkMessageBox.showinfo( "Hello Python", "Hello World")
Labels: This widget implements a display box where you can place text or images. The text displayed by this
widget can be updated at any time you want. It is also possible to underline part of the text (like to identify a
keyboard shortcut) and span the text across multiple lines. Here is the simple syntax to create this widget:
w = Label ( master, option, ... )
Parameters:
master − This represents the parent window.
options − Here is the list of most commonly used op ons for this widget. These op ons can be used
as key-value pairs separated by commas.
1 anchor
This options controls where the text is positioned if the widget has more space than the text
needs. The default is anchor=CENTER, which centers the text in the available space.
2 bg
The normal background color displayed behind the label and indicator.
3 bitmap
Set this option equal to a bitmap or image object and the label will display that graphic.
4 bd
The size of the border around the indicator. Default is 2 pixels.
5 cursor
If you set this option to a cursor name (arrow, dot etc.), the mouse cursor will change to that
pattern when it is over the checkbutton.
6 font
If you are displaying text in this label (with the text or textvariable option, the font option
specifies in what font that text will be displayed.
7 fg
If you are displaying text or a bitmap in this label, this option specifies the color of the text. If
Page 7 of 65
Unit – 4 Regular Expressions
you are displaying a bitmap, this is the color that will appear at the position of the 1-bits in
the bitmap.
8 height
The vertical dimension of the new frame.
9 image
To display a static image in the label widget, set this option to an image object.
10 justify
Specifies how multiple lines of text will be aligned with respect to each other: LEFT for flush
left, CENTER for centered (the default), or RIGHT for right-justified.
11 padx
Extra space added to the left and right of the text within the widget. Default is 1.
12 pady
Extra space added above and below the text within the widget. Default is 1.
13 relief
Specifies the appearance of a decorative border around the label. The default is FLAT; for
other values.
14 text
To display one or more lines of text in a label widget, set this option to a string containing the
text. Internal newlines ("\n") will force a line break.
15 textvariable
To slave the text displayed in a label widget to a control variable of class StringVar, set this
option to that variable.
16 underline
You can display an underline (_) below the nth letter of the text, counting from 0, by setting
this option to n. The default is underline=-1, which means no underlining.
17 width
Width of the label in characters (not pixels!). If this option is not set, the label will be sized to
fit its contents.
18 wraplength
You can limit the number of characters in each line by setting this option to the desired
number. The default value, 0, means that lines will be broken only at newlines.
Example:
from Tkinter import *
root = Tk()
var = StringVar()
label = Label( root, textvariable=var, relief=RAISED )
Page 8 of 65
Entry: The Entry widget is used to accept single-line text strings from a user. If you want to display multiple
lines of text that can be edited, then you should use the Text widget. If you want to display one or more lines
of text that cannot be modified by the user, then you should use the Label widget. Here is the simple syntax
to create this widget:
w = Entry( master, option, ... )
Parameters:
master − This represents the parent window.
options − Here is the list of most commonly used op ons for this widget. These op ons can be used
as key-value pairs separated by commas.
1 bg
The normal background color displayed behind the label and indicator.
2 bd
The size of the border around the indicator. Default is 2 pixels.
3 command
A procedure to be called every time the user changes the state of this checkbutton.
4 cursor
If you set this option to a cursor name (arrow, dot etc.), the mouse cursor will change
to that pattern when it is over the checkbutton.
5 font
The font used for the text.
6 exportselection
By default, if you select text within an Entry widget, it is automatically exported to the
clipboard. To avoid this exportation, use exportselection=0.
7 fg
The color used to render the text.
8 highlightcolor
The color of the focus highlight when the checkbutton has the focus.
9 justify
If the text contains multiple lines, this option controls how the text is justified:
CENTER, LEFT, or RIGHT.
10 relief
With the default value, relief=FLAT, the checkbutton does not stand out from its
background. You may set this option to any of the other styles
11 selectbackground
The background color to use displaying selected text.
12 selectborderwidth
The width of the border to use around selected text. The default is one pixel.
Page 9 of 65
Unit – 4 Regular Expressions
13 selectforeground
The foreground (text) color of selected text.
14 show
Normally, the characters that the user types appear in the entry. To make a
.password. entry that echoes each character as an asterisk, set show="*".
15 state
The default is state=NORMAL, but you can use state=DISABLED to gray out the control
and make it unresponsive. If the cursor is currently over the checkbutton, the state is
ACTIVE.
16 textvariable
In order to be able to retrieve the current text from your entry widget, you must set
this option to an instance of the StringVar class.
17 width
The default width of a checkbutton is determined by the size of the displayed image or
text. You can set this option to a number of characters and the checkbutton will
always have room for that many characters.
18 xscrollcommand
If you expect that users will often enter more text than the onscreen size of the
widget, you can link your entry widget to a scrollbar.
2 get()
Returns the entry's current text as a string.
3 icursor ( index )
Set the insertion cursor just before the character at the given index.
4 index ( index )
Shift the contents of the entry so that the character at the given index is the leftmost visible
character. Has no effect if the text fits entirely within the entry.
5 insert ( index, s )
Inserts string s before the character at the given index.
6 select_adjust ( index )
This method is used to make sure that the selection includes the character at the specified
index.
7 select_clear()
Clears the selection. If there isn't currently a selection, has no effect.
Page 10 of 65
8 select_from ( index )
Sets the ANCHOR index position to the character selected by index, and selects that
character.
9 select_present()
If there is a selection, returns true, else returns false.
11 select_to ( index )
Selects all the text from the ANCHOR position up to but not including the character at the
given index.
12 xview ( index )
This method is useful in linking the Entry widget to a horizontal scrollbar.
top = Tk()
L1 = Label(top, text="User Name")
L1.pack( side = LEFT)
E1 = Entry(top, bd =5)
E1.pack(side = RIGHT)
top.mainloop()
Dialogs
Layouts (What is a layout manager?): When you create graphical interfaces, the widgets in the window
must have a way to be arranged relative to each other. For example, placing widgets can be accomplished
using their relative positions to other widgets or by defining their positions by specifying pixel locations. In
Tkinter there are three types of layout managers -- pack, place, and grid. Each manager uses a different
method to help us arrange widgets.
Pack Layout Manager: The simplest way to think about it is that the pack() method turns each individual
widget into a block. Each widget has its own size and the pack manager fits them all together just like you
would do with real blocks. Each widget already has its own size and parameters. Of course, you can change
these to better fit your needs. Once every widget's size is determined, the manager does its job to arrange
them in the window.
Let's take a moment to learn some of the basics of the pack layout manager. With pack, the manager stacks
widgets on top of each other vertically like blocks. Of course, you can also achieve a horizontal layout by
Page 11 of 65
Unit – 4 Regular Expressions
changing the side parameter to 'left' or 'right'. You can also change the height, width, and locations of the
widgets. Some of the pack manager's more useful parameters are listed below:
side -- specifies the general location of the widget in the window, arguments are 'top', 'bottom',
'left', 'right' (default is 'top').
fill -- which directions you want the widget to fill in the parent window, can choose 'x', 'y' directions,
or 'both'.
padx, pady -- the number of pixels surrounding the widget to create a padding between other
widgets, for horizontal or vertical padding.
ipadx, ipady -- how many pixels to use for padding inside the widget, also for horizontal or vertical
padding
expand -- set to True if you want the widget to stretch if the parent window expands. Default is
False.
anchor -- where the widget is placed in the parent widget, specified by 'n', 's', 'e', 'w', or some
combination of them. Default is 'center'.
Place Layout Manager: The place layout manager allows for you to have more absolute control about the
arrangement of your widgets. With place, you can specify the size of the widget, as well as the exact x and y
coordinates to arrange it within the parent window. In many cases, this can prove to be easier when you are
thinking about the layout of your GUI. But it also means that you may have to spend a little more time
playing around with the x and y values. The place manager is most useful for arranging buttons or other
smaller widgets together within a larger dialog window. A few of the parameters you can play around with
are listed below.
in_ -- specifies the master window for the widget
x, y -- specifies the specific x and y values of the widget in the parent window
Page 12 of 65
relx, rely -- horizontal and vertical offset relative to the size of the parent widget, values between 0.0
and 0.1
relwidth, relheight -- set height and width of widget relative to the size of the parent widget, values
between 0.0 and 0.1
anchor -- where the widget is placed in the parent widget, specified by 'n', 's', 'e', 'w', or some
combination of them. Default is 'center'
Frames: The Frame widget is very important for the process of grouping and organizing other widgets in a
somehow friendly way. It works like a container, which is responsible for arranging the position of other
widgets. It uses rectangular areas in the screen to organize the layout and to provide padding of these
widgets. A frame can also be used as a foundation class to implement complex widgets. Here is the simple
syntax to create this widget:
w = Frame ( master, option, ... )
Parameters:
master − This represents the parent window.
options − Here is the list of most commonly used options for this widget. These options can be used
as key-value pairs separated by commas.
1 bg
The normal background color displayed behind the label and indicator.
2 bd
The size of the border around the indicator. Default is 2 pixels.
3 cursor
If you set this option to a cursor name (arrow, dot etc.), the mouse cursor will
change to that pattern when it is over the checkbutton.
4 height
The vertical dimension of the new frame.
5 highlightbackground
Color of the focus highlight when the frame does not have focus.
6 highlightcolor
Color shown in the focus highlight when the frame has the focus.
7 highlightthickness
Thickness of the focus highlight.
8 relief
With the default value, relief=FLAT, the checkbutton does not stand out from its
background. You may set this option to any of the other styles
9 width
The default width of a checkbutton is determined by the size of the displayed
image or text. You can set this option to a number of characters and the
checkbutton will always have room for that many characters.
Page 13 of 65
Unit – 4 Regular Expressions
Example:
# Import Module
from tkinter import *
# Set Geometry
root.geometry("400x400")
# Frame 1
frame1 = Frame(root,bg="black",width=500,height=300)
frame1.pack()
# Frame 2
frame2 = Frame(frame1,bg="white",width=100,height=100)
frame2.pack(pady=20,padx=20)
# Execute Tkinter
root.mainloop()
Page 14 of 65
CS- 33 Programing in Python
Unit-5
Connecting with Database
Verifying the MySQLdb Interface Installation
The Python standard for database interfaces is the Python DB-API. Most Python database interfaces adhere
to this standard. You can choose the right database for your application. Python Database API supports a
wide range of database servers like: MySQL, SQLite, Oracle, Sybase, MS SQL Server, and Informix. We must
download a separate DB API module for each database we need to access. For example, if you need to
access an Oracle database as well as a MySQL database, you must download both the Oracle and the MySQL
database modules. The DB API provides a minimal standard for working with databases using Python
structures and syntax wherever possible. This API includes the following:
Importing the API module.
Acquiring a connection with the database.
Issuing SQL statements and stored procedures.
Closing the connection
MySQLdb is an interface for connecting to a MySQL database server from Python. It implements the Python
Database API v2.0 and is built on top of the MySQL C API. The following Packages need to Install:
mysql-connector-python
mysql-python
The following example verify that python module is installed and connect with MySQL database server:
import MySQLdb
def mysqlconnect():
try:
db_connection= MySQLdb.connect("localhost","root","","db")
except:
print("Can't connect to database")
return 0
print("Connected")
cursor=db_connection.cursor()
cursor.execute("SELECT CURDATE();")
m = cursor.fetchone()
print("Today's Date Is ",m[0])
db_connection.close()
mysqlconnect()
Page 1 of 65
Unit – 5 Python and Data Analytics
MySQL is customizable. The open-source GPL license allows programmers to modify the MySQL
software to fit their own specific environments.
Retrieving All Rows from a Table: READ Operation on any database means to fetch some useful information
from the database. Once the database connection is established, you are ready to make a query into this
database. You can use either fetchone() method to fetch a single record or fetchall() method to fetch
multiple values from a database table.
fetchone() − It fetches the next row of a query result set. A result set is an object that is returned
when a cursor object is used to query a table.
fetchall() − It fetches all the rows in a result set. If some rows have already been extracted from the
result set, then it retrieves the remaining rows from the result set.
rowcount − This is a read-only attribute and returns the number of rows that were affected by an
execute() method.
Example:
import mariadb as MySQLdb
myconn = MySQLdb.connect(host="localhost", user="root", passwd="",
database="mydatabase")
cur = myconn.cursor()
try:
cur.execute("select * from employee")
result = cur.fetchall()
for x in result:
print(x)
except:
myconn.rollback()
myconn.close()
Inserting Rows into a Table: The INSERT Operation is required when you want to create your records into a
database table. Example:
import mariadb as MySQLdb
db = MySQLdb.connect(host="localhost", user="root", password="",
database="mydatabase" )
cursor = db.cursor()
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME, AGE, INCOME)
VALUES ('Malay', 'Dave', 42, 5000)"""
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()
Page 2 of 65
Deleting Rows from a Table: DELETE operation is required when you want to delete some records from your
database. Following is the procedure to delete all the records from EMPLOYEE where AGE is more than 20:
Updating Rows in a Table: UPDATE Operation on any database means to update one or more records, which
are already available in the database. The following procedure updates all the records having SEX as 'M'.
Here, we increase the AGE of all the males by one year.
import mariadb as MySQLdb
Creating Database Tables through Python: Once a database connection is established, we are ready to
create tables or records into the database tables using execute method of the created cursor. Example:
Performing Transactions: Transactions are a mechanism that ensures data consistency. Transactions have
the following four properties:
Atomicity − Either a transac on completes or nothing happens at all.
Consistency − A transac on must start in a consistent state and leave the system in a consistent
state.
Page 3 of 65
Unit – 5 Python and Data Analytics
Isolation − Intermediate results of a transac on are not visible outside the current transac on.
Durability − Once a transac on was commi ed, the effects are persistent, even a er a system
failure.
The Python DB API 2.0 provides two methods to either commit or rollback a transaction.
COMMIT Operation: Commit is an operation, which gives a green signal to the database to finalize the
changes, and after this operation, no change can be reverted back. Here is a simple example to call the
commit method.
db.commit()
ROLLBACK Operation: If you are not satisfied with one or more of the changes and you want to revert back
those changes completely, then use the rollback() method. Here is a simple example to call the rollback()
method.
db.rollback()
Disconnecting Database: To disconnect the Database connection, use the close() method.
db.close()
If the connection to a database is closed by the user with the close() method, any outstanding transactions
are rolled back by the DB. However, instead of depending on any of the DB lower level implementation
details, your application would be better off calling commit or rollback explicitly.
Handling Errors: There are many sources of errors. A few examples are a syntax error in an executed SQL
statement, a connection failure, or calling the fetch method for an already canceled or finished statement
handle. The DB API defines a number of errors that must exist in each database module. The following table
lists these exceptions.
1 Warning
Used for non-fatal issues. Must subclass StandardError.
2 Error
Base class for errors. Must subclass StandardError.
3 InterfaceError
Used for errors in the database module, not the database itself.
Must subclass Error.
4 DatabaseError
Used for errors in the database. Must subclass Error.
5 DataError
Subclass of DatabaseError that refers to errors in the data.
6 OperationalError
Subclass of DatabaseError that refers to errors such as the loss of
a connection to the database. These errors are generally outside
of the control of the Python scripter.
7 IntegrityError
Subclass of DatabaseError for situations that would damage the
Page 4 of 65
relational integrity, such as uniqueness constraints or foreign
keys.
8 InternalError
Subclass of DatabaseError that refers to errors internal to the
database module, such as a cursor no longer being active.
9 ProgrammingError
Subclass of DatabaseError that refers to errors such as a bad table
name and other things that can safely be blamed on you.
10 NotSupportedError
Subclass of DatabaseError that refers to trying to call
unsupported functionality.
Your Python scripts should handle these errors, but before using any of the above exceptions, make sure
your MySQLdb has support for that exception. You can get more information about them by reading the DB
API 2.0 specification.
Page 5 of 65