SCSA1204
SCSA1204
SCSA1204
SCHOOL OF COMPUTING
1
SCSA1204- Python Programming
INTRODUCTION
1. Program
a. About Python
“http:// python.org/”
Python is portable: It runs on different operating systems / platforms3
Python has automatic memory management
Python is flexible with both procedural oriented and object oriented
programming
Python is easy to learn, read and maintain
It is very flexible with the console program, Graphical User Interface (GUI)
applications, Web related programs etc.
3
SCSA1204- Python Programming
Fig 2 indentation
It is a command line shell which gives immediate output for each statement,
while keeping previously fed statements in active memory. This mode is used
when a user wishes to run one single line or small block of code. It runs very
quickly and gives instant output. A sample code is executed using interactive
mode as below.
5
SCSA1204- Python Programming
The symbol “>>>” in the above screen indicates that the Python environment
is in interactive mode.
ii) From the start menu select Python (As shown below)
6
SCSA1204- Python Programming
When the programmer wishes to use more than one line of code or a block of
code, script mode is preferred. The Script mode works the following way:
7
SCSA1204- Python Programming
iii) Select File New, to open editor. Type the complete program.
iv) Select File again; Choose Save.
8
SCSA1204- Python Programming
VARIABLES:
9
SCSA1204- Python Programming
10
SCSA1204- Python Programming
In the above three variables x,y,z is assigned with same value 25.
11
SCSA1204- Python Programming
Expression:
12
SCSA1204- Python Programming
Fig 14 expression
Fig 15 expression
Invalid Expression:
Always values should be assigned in the right hand side of the variable, but in
the below example ,the value is given in the left hand side of the variable,
which is an invalid syntax for expression.
13
SCSA1204- Python Programming
Data Types:
Float: Values that use decimal point and therefore may have fractional point
E.g.: 3.415, -5.15
By default when a user gives input it will be stored as string. But strings
cannot be used for performing arithmetic operations. For example while
attempting to perform arithmetic operation add on string values it just
14
SCSA1204- Python Programming
Fortunately python have an option of converting one date type into another
data type (Called as “Casting”) using build in functions in python. The build
function int() converts the string into integer before performing operation to
give the right answer. (As in the below Program)
i) List
The List is an ordered sequence of data items. It is one of the flexible and very
frequently used data type in Python. All the items in a list are not necessary to
be of the same data type.
Declaring a list is straight forward methods. Items in the list are just separated
by commas and enclosed within brackets [ ].
ii) Tuple
Tuple is also an ordered sequence of items of different data types like list. But,
in a list data can be modified even after creation of the list whereas Tuples are
immutable and cannot be modified after creation.
The advantages of tuples is to write-protect data and are usually very fast
when compared to lists as a tuple cannot be changed dynamically.
16
SCSA1204- Python Programming
The elements of the tuples are separated by commas and are enclosed inside
open and closed brackets.
Table 2 Tuple
List Tuple
i) Set
The Set is an unordered collection of unique data items.Items in a set are not
ordered, separated by comma and enclosed inside { } braces. Sets are helpful
inperforming operations like union and intersection. However, indexing is not
done because sets are unordered.
Table 3 Set
List Set
>>> L1 = [1,20,25] >>> S1= {1,20,25,25}
>>> print(L1[1]) >>> print(S1)
>>> 20 >>> {1,20,25}
>>> print(S1[1])
17
SCSA1204- Python Programming
18
SCSA1204- Python Programming
List Vs Set
ii) Dictionary
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.
>>> d1={1:'value','key':2}
>>> type(d)
19
SCSA1204- Python Programming
Simple Functions
Function Description Output
abs() Return the absolute value of a >>> a = -10
number. The argument may be >>> print(abs(a))
an floating point number or a >>> 10
integer.
max() Returns the largest number from >>> max(12,20,30)
the list of numbers >>> 30
min() Returns the smallest number >>> min(12,20,30)
from the list of numbers >>> 12
pow() Returns the power of the given >>> pow(5,2)
number >>>25
round() It rounds off the number to the # E.g. 1:
nearest integer. >> round(4.5)
21
SCSA1204- Python Programming
>> 5
# Eg 2
>> round(4.567,2)
>> 4.57
Mathematical Functions (Using math module)
ceil(x) It rounds x up to its nearest >>math.ceil(2.3)
integer and returns that integer >> 3
>>math.ceil(-3.3)
>> -3
floor(x) It rounds x down to its nearest >>math.floor(3.2)
integer and returns that integer >> 3
>>math.floor(-3.4)
>> -4
Function Description Example
cos(x) Returns the cosine of x , where >> math.cos(3.14159/2)
x represents angle in radians >> 0
>> math.cos(3.14159)
>> -1
sin(x) Returns the sine of x, where x >> math.sin(3.14159/2)
represents angle in radians >> 1
>> math.sin(3.14159)
>> 0
exp(x) Returns the exponential of x to >> math.exp(1)
the base ‘e’. i.e. ex >> 2.71828
log(x) Returns the logarithm of x for >>> math.log(2.71828)
the base e (2.71828) >>> 1
import math
23
SCSA1204- Python Programming
Conditional Statements
C Program Python
x = 500 x = 500
y = 200 y = 200
if (x > y) if x > y:
{ print("x is greater than y")
printf("x is greater than y") elif x == y:
} print("x and y are equal")
else if(x == y) else:
{ print("x is less than y")
printf("x and y are equal")
}
else
{ Indentation (At least one White Space
24
SCSA1204- Python Programming
x = 500
y = 200
if x > y:
print("x is greater than y")
If statement :
Syntax:
if<Boolean>:
<block>
25
SCSA1204- Python Programming
26
SCSA1204- Python Programming
Example:
x = 200
y = 100
if x > y:
print("X is greater than Y")
print(“End”)
Output :
X is greater than Y
End
In the above the value of x is greater than y , hence it executed the print
statement whereas in the below example x is not greater than y hence it is not
executed the first print statement
x = 100
y = 200
if x > y:
print("X is greater than Y")
print(“End”)
Output :
End
27
SCSA1204- Python Programming
Elif
The elif keyword is useful for checking another condition when one condition
is false.
Example
mark = 55
if (mark >=75):
print("FIRST CLASS")
print("PASS")
Output :
28
SCSA1204- Python Programming
In the above the example, the first condition (mark >=75) is false then the
control is transferred to the next condition (mark >=50), Thus, the keyword
elif will be helpful for having more than one condition.
Else
The else keyword will be used as a default condition. i.e. When there are
many conditions, whentheif-condition is not trueand all elif-conditionsare
also not true, then else part will be executed..
Example
mark = 10
29
SCSA1204- Python Programming
Iterative Statements
Sometimes certain section of the code (block) may need tobe repeated again
and again as long as certain condition remains true. In order to achieve this,
the iterativestatements are used.The number of times the block needs to be
repeated is controlled by the test condition used in that statement. This type
of statement is also called as the “Looping Statement”. Looping statements
add a surprising amount of new power to the program.
Suppose the programmer wishes to display the string “Sathyabama !...” 150
times. For this,one can use the print command 150 times.
30
150 times
SCSA1204- Python Programming
print(“Sathyabama
!...”)
print(“Sathyabama
!...”)
…..
…..
print(“Sathyabama
!...”)
The above method is somewhat difficult and laborious. The same result can
be achieved by a loop using just two lines of code.(As below)
for count in
range(1,150) :
print (“Sathyabama
!...”)
Types of looping statements
1) for loop
2) while loop
31
SCSA1204- Python Programming
Flow Chart:
# Sum.py
total = 0
n = int (input ("Enter a Positive Number"))
for i in range(1,n+1):
total = total + i
print ("The Sum is ", total)
Note:Why (n+1)? Check in table given below.
32
SCSA1204- Python Programming
Output:
In the above program, the statement total = total + i is repeated again and
again ‘n’ times. The number of execution count is controlled by the variable
‘i’. The range value is specified earlier before it starts executing the body of
loop. The initial value for the variable i is 1 and final value depends on ‘n’.
You may also specify any constant value.
The range() function can be called in three different ways based on the
number of parameters. All parameter values must be integers.
Table 7 range()
Type Example Explanation
33
SCSA1204- Python Programming
# harmonic.py
total = 0
for i in range(1,n+1):
total+= 1/i
Example:
factorial = 1
if n < 0:
elif n == 0:
else:
35
SCSA1204- Python Programming
Fig 25factorial
The while loop allows the program to repeat the body of a loop, any
number of times, when some condition is true.The drawback of while loop
is that, if the condition not proper it may lead to infinite looping. So the
user has to carefully choose the condition in such a way that it will
terminate at a particular stage.
36
SCSA1204- Python Programming
Flow Chart:
Syntax:
while (condition):
37
SCSA1204- Python Programming
In this type of loop, The executionof the loopbody is purely based on the
output of the given condition.As long as the condition is TRUE or in other
words until the condition becomes FALSE the program will repeat the body
of loop.
Table 8 Example
n2 = 1
count = 0
# count -- To check number of terms
if n <= 0: # To check whether valid number of terms
print ("Enter a positive integer")
elif n == 1:
print("Fibonacci sequence up to",n,":")
print(n2)
else:
print("Fibonacci sequence of ",n, “ terms :” )
while count < n:
print(n1,end=' , ')
nth = n1 + n2
n1 = n2
n2 = nth
count = count + 1
Programmer often has a need to interact with users, either to get data or to
provide some sort of result.
For Example: In a program to add two numbers, first the program needs to
have an input of two numbers ( The numbers which they prefer to add) and
after processing, the output should be displayed. So to get the input of two
39
SCSA1204- Python Programming
numbers, the program need to have an Input Statement and in order to display
the result i.e. the sum of two numbers, it needs to have an Output Statement.
Input Statement: Helpful to take input from the user through input
devices like keyboard.In Python, the standard input function is
‘input()’
input()
Example:
The above statement will wait till the user, enters the input value.
Output:
Enter a number:
>>>num
Output Statement:
40
SCSA1204- Python Programming
Syntax:
print(‘prompt’)
Example 1:
Output:
Example 2:
X=5
Output:
The value of X is 5
Example 3:
print(1,2,3,4)
41
SCSA1204- Python Programming
Output: 1 2 3 4
Example 4:
print(100,200,300,4000,sep='*')
Output:
100*200*300*4000
Example 5:
print(1,2,3,4,sep='#',end='&')
Output:
1#2#3#4&
Output formatting
>>>x = 5; y = 10
>>>print('The value of x is {} and y is {}'.format(x,y))
The value of x is5and y is10
42
SCSA1204- Python Programming
Here, the curly braces {} are used as placeholders. We can specify the order
in which they are printed by using numbers (tuple index).
Output
43
SCSA1204- Python Programming
44
SCSA1204- Python Programming
Example :
class Student:
def __init__(self, name, regno):
self.name = name
self.regno = regno
s1 = Student("John", 36)
print(s1.name)
print(s1.regno)
Note :
Output :
>>> John
36
class Student:
def __init__(self,name, regno):
45
SCSA1204- Python Programming
self.name = name
self.regno = regno
def display(self):
print("Name of the student is " + self.name )
s1 = Student("James", 43)
s1.display()
Inheritance:
Inheritance allows to create anew class (Child Class) from the existing
class (Parent Class).
The child class inherits all the attributes of its parent class.
Child class is the class that inherits properties from another class. The
child class is also called as Sub class or Derived Class.
Example :
46
SCSA1204- Python Programming
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printdetails(self):
print(self.firstname, self.lastname)
#Use the Person class to create an object and then execute the
printdetails method:
x = Person("John", "Doe")
x.printdetails()
classEmployee(Person):
pass
y = Employee("Mike", "Olsen")
y.printdetails()
Output :
>>>
RESTART:
C:/Users/Administrator/AppData/Local/Programs/Python/Python37-
32/f1.py
John Doe
Mike Olsen
>>>
47
SCSA1204- Python Programming
In the above example the base class is Person. The first object “x” is created
through the base class “Person” and the method printdetails() is invoked
with that object which produces an output “John Doe”. Again, another
object “y” is created through derived class “Employee” and the same
method printdetails() (belongs to base class) is invoked to produce the
output “Mike Olsen”. Thus, the derived class is having the ability to invoke
the method from base class just because ofthe inheritance property which
reduces the code length or in other words it is helpful for reusability of
code.
Note: Use the pass keyword when the programmer does not wish to
add any other properties or methods to the derived class.
Example 2:
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printdetails(self):
print(self.firstname, self.lastname)
48
SCSA1204- Python Programming
class Employee(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
self.doj = 2019
defgreetings(self):
print("Welcome", self.firstname, self.lastname, "who joined in the
year ", self.doj)
# Object for derived class
y = Employee("Samuel", "Ernest")
y.printdetails()
y.greetings()
The object “y” is able to invoke both the methods printdetails() and
greetings().
Questions :
49
SCSA1204- Python Programming
4. What is __init__?
50
SCSA1204- Python Programming
SCHOOL OF COMPUTING
1
SCSA1204- Python Programming
UNIT II
FileOperations–Iterators-Exceptionhandling-RegularExpressions-Creating
Modules-Import Statement-Introduction to PIP-Installing Packages via PIP-
Using Python Packages.
Opening a file
Method:open()
Syntax:
File_object=open(filename,Access_mode,buffering)
Attributes:
2
SCSA1204- Python Programming
Example:
f= open(‘abc.txt’) (or)
f=open(“D:/Mypython/abc.txt”)
f= open(‘abc.txt’, r)
3
SCSA1204- Python Programming
The above code is a sample snippet for understanding the file modes and file
properties.
write() method is used to write the contents to a file. The following code is for
writing the contents to the file aa.txt.
fo=open(‘aa.txt’,’w’)
fo.close()
4
SCSA1204- Python Programming
Output:
In the above example, the contents of the file can be viewed by opening the
file ‘aa.txt’.
read() method is used to read the contents from a file. The following code is
for reading the first 10 bytes of the file ‘aa.txt’.
5
SCSA1204- Python Programming
To know about the file offset positions in Python, the following methods are
used:
seek()
tell()
seek():
Syntax:seek(offset,from)
Description: Sets the file's current position at the offset. The offset values are
as follows:
tell() :
2.1.3.1.File Offset
6
SCSA1204- Python Programming
In the above code, initially the position of the file pointer is at 0. After reading
the contents, the position of the file pointer is moved to 10 (from 0 to 9). Now
up on giving the command seek(2,0), the file will be read from the beginning
after skipping the first 2 positions.
Detailed Example:
7
SCSA1204- Python Programming
8
SCSA1204- Python Programming
Syntax:
2.2 ITERATORS
For example if we have a list A=[1,2,3] , then iterator is used to return the
items in the list one at a time.
In the above code the list items of mylist object are retrieved one by one using
‘next()’ method. When the list reaches its end and if next() method is used , it
shows error in the output.
Alternate way for retrieving the items is to use for loop and retrieve the item
using __next__() inside the for loop. To find the length of the list ‘len()’
method is used.
10
SCSA1204- Python Programming
We can also build our own iterators. The following code is for implementing
user defined iterators for finding powers of two.
11
SCSA1204- Python Programming
Similarly , the following code uses while loop to print the odd numbers
starting from 1 to infinite number of times. The execution is manually
terminated by providing keyboard interrupt(Ctrl+c).
Generator functions are alternates for iterators that contain one or more yield()
statements. Methods like __iter__(), __next__() are implemented and are
iterated using next() automatically. Local variables are remembered between
successive calls. When function terminates, StopIterator exception is raised
automatically.
2.2.5.1.Example
In the following code, n value is initiated to 1 in the first step. In the second
step n is incremented by two and the value yielded is now 3. In the last step n
is incremented by 1 and now the value is 4.
13
SCSA1204- Python Programming
Easy to implement
Memory efficient
Represents infinite stream
Generators can be pipelined
While handling exception, keep the suspicious code in try block and following
the try block, include except: statement
15
SCSA1204- Python Programming
The following code raises exception when a run time error occurs upon
writing the file ‘aa.txt’. In case of normal program flow, the else clause will
be invoked and the statements in else block will be executed.
In python, we can also have except clause with no specific exception. In this
case any type of exception can be handled. The following is the syntax for
except statement with no specific exception type.
16
SCSA1204- Python Programming
Syntax:
Example:
In the following code, except clause is alone given, without mentioning the
type of exception. In the sample runs when the value of ‘b’ is given as 0,
exception is caught and ‘divide by zero error’ is printed. Whereas, in case of
normal run, the output is displayed.
17
SCSA1204- Python Programming
Syntax:
Example:
18
SCSA1204- Python Programming
Like other object oriented programming languages, try has optional finally
clause. The statements given in finally block will be executed even after the
exceptions are handled.
Example:
ex=RunTimeError(‘Something Wrong’)
raise ex
OR
19
SCSA1204- Python Programming
20
SCSA1204- Python Programming
2.4 REGULAREXPRESSIONS
Syntax:
import re
21
SCSA1204- Python Programming
22
SCSA1204- Python Programming
2.4.2. RE Methods
Method:search()
Example:
The above code returns the Match object with a span position from 0 to n-1
when the search information is found.
Method:split()
Description: For creating space in the string.
Example:
23
SCSA1204- Python Programming
In the above code, split() method is applied twice on the string, ‘This is a
string’. When the matching character \s is applied, the spaces in the string are
split up. When the regular expression r’([a-i]) is applied, the string is split
ignoring the range of characters from a to i.
Method:findall()
Description: Finds all the matches and returns them as a list of strings.
Example:
Method:match()
Description:To match the RE pattern to string with optional flags.
24
SCSA1204- Python Programming
Example:
Method:compile()
Description: Compiling a pattern without rewriting it.
25
SCSA1204- Python Programming
Example:
In the above code the compiled pattern is ‘Python’. The result objects return
each and every occurrence of the matched pattern line by line. Other Regular
Expression methods are given in Table 2.2 and RE Compilation flags are
given in Table 2.3.
Method/Attribute Purpose
26
SCSA1204- Python Programming
Example:
27
SCSA1204- Python Programming
28
SCSA1204- Python Programming
2.5.1.Definition
Syntax:
29
SCSA1204- Python Programming
import module_name
Files, containing the Python definitions and statements, can be created by the
user, and the same file can be imported on another Python program using
import statement. The following example explains importing a python
module(File1) over another python code(File 2).
Example:
30
SCSA1204- Python Programming
Let us have two different files File1 & File 2. If we want to import any
module of File1 into File2, then we need to import File1 module in File2
using ‘import’ statement.
File1.py
def max(n1,n2):
if n1>n2:
result=n1
else:
result=n2
return result
File 2.py
import File1
x,y=eval(input('enter x and y'))
z=max(x,y)
print("the max is",z)
Python import statement enables the user to import particular modules in the
corresponding program.Import in Python is similar to #include header file in
C/C++. Python modules can get access to code from another module by
importing the file/function using import. The import statement is the most
31
SCSA1204- Python Programming
common way of invoking the import machinery, but it is not the only way.
Import statement consists of the import keyword along with the name of the
module.
The import statement involves two operations, it searches for a module and
it binds the result of the search to name in local scope. When a module is
imported, Python runs all of the code in the module file and made available
to the importer file.
Syntax:
import module_name
Example:
import collections
1. Importing class/functions from a module
Example:
fromcollections importOrderedDict
fromos importpath
frommath importpi
print(pi)
Output:
3.141592653589793
frommath import*
print(pi)
print(floor(3.15))
Output:
3.141592653589793
3
33
SCSA1204- Python Programming
# python import as
importmath as M
print(M.pi)
print(M.floor(3.18))
Output:
3.141592653589793
3
test.py:
defsub(a, b):
returnint(a) -int(b)
deflower_case(str1):
returnstr(str1).lower()
Then create another python script, wherein we need to import the above create
test.py script.
test2.py
importtest
print(test.sub(5,4))
34
SCSA1204- Python Programming
print(test.lower_case('SafA'))
Output:
1
safa
test1.py
defsub(a, b):
returnint(a) -int(b)
deflower_case(str1):
returnstr(str1).lower()
Then, we will create another python script and save it into another directory
and then import the functionalities from test1.py (which resides into another
directory).
design.py
importimportlib, importlib.util
defmodule_directory(name_module, path):
P =importlib.util.spec_from_file_location(name_module, path)
35
SCSA1204- Python Programming
import_module =importlib.util.module_from_spec(P)
P.loader.exec_module(import_module)
returnimport_module
print(result.sub(3,2))
print(result.lower_case('SaFa'))
Output:
1
safa
Another alternative way is to add the module directory to the sys.path list.
def__init__(self, result):
self.designation =result
defshow_designation(self):
print(self.designation)
classDetails(Employee):
36
SCSA1204- Python Programming
id=0
def__init__(self, ID, name):
Employee.__init__(self, name)
self.id=name
defget_Id(self):
returnself.id
design.py
importimportlib, importlib.util
defmodule_directory(name_module, path):
P =importlib.util.spec_from_file_location(name_module, path)
import_module =importlib.util.module_from_spec(P)
P.loader.exec_module(import_module)
returnimport_module
a =result.Employee('Project Manager')
a.show_designation()
x =result.Details(4001,'Safa')
x.show_designation()
print(x.get_Id())
Output:
Project Manager
Safa
Safa
37
SCSA1204- Python Programming
In order to mange and install software packages Python use PIP as Package
Management System. PIP is written in Python and available in PyPI(Python
Package Index). PIP is otherwise known as PiP Installs Python or PIP installs
Packages.
Step 1: Download get-pip.py and save this folder in the system’s local drive to
a folder on your computer.
Step 2: Open the command prompt and explore the folder containing get-
pip.py.
Python codes can also be executed online without installing Python IDLE or
PIP packages. One of the weblink used for running python codes online is:
‘https://www.onlinegdb.com/online_python_compiler#’.
The following are some of the python editors where Python libraries
necessary for advanced scientific programming are almost readily available.
38
SCSA1204- Python Programming
If the Python library is not available then the command ‘pip install
lib_name’, could be given for installing the specific library.
JuPYter Notebook
Pycharm Community Edition & Professional Edition
Wing IDE
NINJA IDE
Spyder
Pyzo
2.8.2. Python Libraries for running real time projects
2.8.2.1.Numpy
import numpy as np
a = np.arange(15).reshape(3, 5)
print(a)
print ('type of a', type(a))
#Output:
[[ 0 1 2 3 4] [ 5 6 7 8 9]
[10 11 12 13 14]]
type of a <class 'numpy.ndarray'>
39
SCSA1204- Python Programming
40
SCSA1204- Python Programming
[[10 11 12 13 14]
[15 16 17 18 19]
[20 21 22 23 24]]
2.8.2.2. Scipy
Syntax:
from scipy import module_name
Example:
import scipy
from scipy.constants import pi
print("sciPy - pi = %.16f"%scipy.constants.pi)
Output:
sciPy - pi = 3.1415926535897931
The following are the real time applications which can be implemented using
Scipy:
Signal Processing
Image manipulation
Interpolation
Optimization and fit
Statistics and random numbers
File input/output
Special Function
41
SCSA1204- Python Programming
2.8.2.2. matplotlib
Matplotlib library is used for plotting graphs. The basic methods in matplotlib
are:
Example:
Fig.2.3 Output
42
SCSA1204- Python Programming
SCHOOL OF COMPUTING
79
SCSA1204- Python Programming
button
canvas
checkbutton
combobox
80
SCSA1204- Python Programming
entry
frame
label
listbox
menu
message
progressbar
radiobutton
scrollbar
spinbox
text
Layout Management
81
SCSA1204- Python Programming
1. Pack Layout
2. Grid Layout
3. Place Layout
Example:
fromtkinter import *
top=Tk()
l1=Label(top,text="Label1",bg="blue")
l2=Label(top,text="Label2",bg="red" )
l1.pack(fill=X,side=TOP,expand=True)
l2.pack(fill=X,side=RIGHT)
top.mainloop()
82
SCSA1204- Python Programming
Output:
l2.pack(fill=X,side=TOP,padx=10)
top.mainloop()
Output:
Example:
fromtkinter import *
top=Tk()
l1=Label(top,text="Label1",bg="blue")
l2=Label(top,text="Label2",bg="red" )
l1.pack(fill=X,side=TOP,expand=True,pady=10)
l2.pack(fill=X,side=TOP,pady=10)
top.mainloop()
Output:
84
SCSA1204- Python Programming
fromtkinter import *
top=Tk()
l1=Label(top,text="Label1",bg="blue")
l2=Label(top,text="Label2",bg="red" )
l1.pack(fill=X,side=TOP,expand=True,ipadx=10)
l2.pack(fill=X,side=TOP,ipadx=10)
top.mainloop()
Output:
85
SCSA1204- Python Programming
Example:
fromtkinter import *
top=Tk()
l1=Label(top,text="Label1",bg="blue")
l2=Label(top,text="Label2",bg="red" )
l1.pack(fill=X,side=TOP,expand=True,ipadx=10)
l2.pack(fill=X,side=TOP,ipady=10)
top.mainloop()
Output:
86
SCSA1204- Python Programming
Place Layout:
Place is the most complex manager out of the 3 managers. It uses
absolute positioning, when we choose place lay out in our design, then we
need to specify the position of the widgets using x and y coordinates. The size
and position of the widgets will not be changed when we resize the window.
Example:
fromtkinter import *
top=Tk()
l1=Label(top,text="Label1",bg="blue")
l2=Label(top,text="Label2",bg="red" )
l1.place(x=10,y=50)
l2.place(x=10,y=100)
top.mainloop()
Output:
Explanation:
87
SCSA1204- Python Programming
Here Label1 is placed in the position (10,50) and label2 is placed in the
position (10,100).
Grid Layout
Example:
fromtkinter import *
top=Tk()
l1=Label(top,text="Label1",bg="blue")
l2=Label(top,text="Label2",bg="red" )
l3=Label(top,text="Label2",bg="green" )
l1.grid(row=0,column=0)
l2.grid(row=0,column=1)
l3.grid(row=1,column=1)
top.mainloop()
Output:
88
SCSA1204- Python Programming
Explanation:
Here Label 1 is placed in 0 th row and 0th column. Label 2 is placed in 0th row
and 1st column and Label 3 is placed in 1st row and 1st column.
FONT
Ex: t =(“Arial”,14,”Bold”)
Example:
fromtkinter import *
top=Tk()
b1=Button(text="submit",font=("Arial","16","bold"))
b1.pack()
top.mainloop()
Output:
89
SCSA1204- Python Programming
Explanation:
Text for the Button has been set in the Arial font with size 16 and Bold style.
Font Object
Import tkFont
Font f1=tkFont.Font(parameters,…..)
Example:
fromtkinter import *
fromtkFont import *
top=Tk()
f1=Font(family="Helvetica",size=20,weight="bold",slant="italic",underline=1
,overstrike=1)
l1=Label(top,text="Label1",bg="blue",font=f1)
l1.pack()
top.mainloop()
X Window Fonts:
If you are running under the X Window System, you can use any of the X font
names.
COLORS
Tkinter represents colors with strings. There are two general ways to specify
colors in Tkinter :
91
SCSA1204- Python Programming
We can use a string specifying the proportion of red, green and blue in
hexadecimal digits. For example,
"#fff" -- white,
"#000000" -- black,
"#000fff000" -- pure green
"#00ffff" -- pure cyan
We can also use any locally defined standard following color names.
"white"
"black"
"red"
"green"
"blue"
"cyan"
"yellow"
"magenta"
92
SCSA1204- Python Programming
Active background − Specifies Background color for the widget when the
widget is active.
Example:
fromtkinter import *
93
SCSA1204- Python Programming
top=Tk()
b1=Button(text="submit",bg="red",fg="white")
b1.pack()
top.mainloop()
Output:
Explanation:
Here the back ground of the button is red in color and foreground color of the
button is white in colour.
CANVAS
Syntax:
w = Canvas ( top, option=value, ... )
top – It represents the parent window.
Options − commonly used options for this widget. These options can be
used as key-value pairs separated by commas.
Commonly used Options are:
94
SCSA1204- Python Programming
1.Arc
2.Image
3.Line
4.Oval
5.Polygon
ARC
Creates an arc item, which can be a chord or a simple arc.
Syntax:
95
SCSA1204- Python Programming
Example:
fromtkinter import *
root=Tk()
w.pack()
Output:
Explanation:
96
SCSA1204- Python Programming
Here Arc is drawn with blue color and within the bounded rectangle with top
left(10,50)position and bottom right(240,210) position and started from angle
0 and extended till 150 degree.
IMAGE
Syntax:
Create_image(x,y,options….)
image=image object
Example:
fromtkinter import *
root=Tk()
w.create_image("F:\img2",50,50)
w.pack()
97
SCSA1204- Python Programming
root.mainloop()
LINE
Syntax:
x0,y0,x1,y1->coordinates of line
Example:
fromtkinter import *
root=Tk()
w.create_line(10,10,100,100,activefill="red")
w.pack()
root.mainloop()
Output:
98
SCSA1204- Python Programming
OVAL
Syntax:
x0, y0, x1, y1- the top left and bottom right corners of the bounding
rectangle
Options:
Example:
fromtkinter import *
root=Tk()
w = Canvas(root, width=500, height=500)
w.create_oval(10,10,100,100,activefill="red")
w.pack()
root.mainloop()
Output:
POLYGON
Syntax:
Options:
Example
fromtkinter import *
root=Tk()
w.create_polygon(50,50,20,20,100,100,activefill="red")
w.pack()
root.mainloop()
WIDGETS IN PYTHON
Widgets are standard graphical user interface (GUI) elements, like different
kinds of buttons and menus.
LABEL
101
SCSA1204- Python Programming
A Label widget shows text to the user about other widgets used in the
application. The widget can be updated programmatically.
Option Description
anchor It specifies the exact position of the text within the size provided to
the widget. The default value is CENTER, which is used to center
the text within the specified space.
bg Specifies background color of the widget
bd Specifies border width. Default is 2 pixels
cursor Specifies type of cursor.eg:dot,arrow,circle
font Specifies font type of the text written inside the widget
fg Foreground color of the widget
height Height of the widget
width Width of the widget
image Specifies image to be displayed in the widget
padx Horizontal padding of text
pady Vertical padding of text
102
SCSA1204- Python Programming
Example:
fromtkinter import *
root=Tk()
l1.pack()
root,mainloop()
Output:
Explanation:
103
SCSA1204- Python Programming
Here Label has been created with green background color and white
foreground color with the text “Enter User Name”.
ENTRY
The Entry widget is used to create the single line text-box to the user to
accept a value from the user. It can accept the text strings from the user. It can
receive one line of text from the user. For multiple lines of text, the text
widget will be used.
w=Entry(root, options)
root-Main Window
Option Description
bg Specifies background color of the widget
bd Specifies border width. Default is 2 pixels
cursor Specifies type of cursor.eg:dot,arrow,circle
font Specifies font type of the text written inside the widget
fg Foreground color of the widget
height Height of the widget
width Width of the widget
104
SCSA1204- Python Programming
Option Description
image Specifies image to be displayed in the widget
padx Horizontal padding of text
pady Vertical padding of text
relief Specifies type of border
text Text to be displayed in the widget
undeline Underline the label text
selectbackground Background color of the selected text
selectforeground Foreground color of the selected text
show Specifies the character used to mask characters in the
text box
Table 2: Widget
Example:
fromtkinter import *
root=Tk()
e1=Entry(root,show="*")
l1.pack(side=LEFT)
105
SCSA1204- Python Programming
e1.pack(side=RIGHT)
root.mainloop()
Output:
Explanation:
Here Label and entry widgets are created.Since the show attribute value is
*,the characters entered in the text box appeared as “*”.
BUTTON
Button Widget is used to create various kinds of buttons.The user can interact
with the button.They can contain text or images.
106
SCSA1204- Python Programming
b=Button(root,options)
root-main window
Option Description
bg Specifies background color of the widget
bd Specifies border width. Default is 2 pixels
cursor Specifies type of cursor.eg:dot,arrow,circle
font Specifies font type of the text written inside the widget
fg Foreground color of the widget
height Height of the widget
width Width of the widget
image Specifies image to be displayed in the widget
padx Horizontal padding of text
pady Vertical padding of text
relief Specifies type of border
text Text to be displayed in the widget
underline Underline the label text
command It is set to function name which will be called the button is
clicked
Table 3: Budget Widget
107
SCSA1204- Python Programming
Example:
fromtkinter import *
root=Tk()
b1=Button(root,text="Submit",bg="blue",fg="white")
b1.pack()
root.mainloop()
Output:
Checkbutton
b=CheckButton(root,options)
root-main window
Option Description
bg Specifies background color of the widget
bd Specifies border width. Default is 2 pixels
cursor Specifies type of cursor.eg:dot,arrow,circle
font Specifies font type of the text written inside the widget
fg Foreground color of the widget
height Height of the widget
width Width of the widget
image Specifies image to be displayed in the widget
padx Horizontal padding of text
pady Vertical padding of text
relief Specifies type of border
text Text to be displayed in the widget
undeline Underline the label text
command It is set to function name whicjh will be called the button is
clicked
offvalue Set value to the control variable if the button is
checked.Default Value is 1
onvalue Set value to the control variable if the button is
unchecked.Default Value is 0
selectcolor Set color of the check button when it is checked.
selectimage Set the image to be shown when it is checked.
109
SCSA1204- Python Programming
Example:
fromtkinter import *
root=Tk()
c1.pack()
c2.pack()
c3.pack()
root.mainloop()
Output:
110
SCSA1204- Python Programming
Radiobutton
b=RadioButton(root,options)
root-main window
111
SCSA1204- Python Programming
Option Description
bg Specifies background color of the widget
bd Specifies border width. Default is 2 pixels
cursor Specifies type of cursor.eg:dot,arrow,circle
font Specifies font type of the text written inside the widget
fg Foreground color of the widget
height Height of the widget
width Width of the widget
image Specifies image to be displayed in the widget
padx Horizontal padding of text
pady Vertical padding of text
relief Specifies type of border
text Text to be displayed in the widget
underline Underline the label text
command It is set to function name whicjh will be called the button
is clicked
value Set value to the control variable if the button is selected.
selectcolor Set color of the check button when it is checked.
selectimage Set the image to be shown when it is checked.
variable It is used to keep track of user choices.
112
SCSA1204- Python Programming
Example:
fromtkinter import *
root=Tk()
r1.pack()
r2.pack()
r3.pack()
root.mainloop()
Output:
113
SCSA1204- Python Programming
LISTBOX
The Listbox widget is used to display the list items to the user.The user can
choose one or more items from the list depending upon the configuration.
b=Listbox(root,options)
root-main window
Option Description
bg Specifies background color of the widget
bd Specifies border width. Default is 2 pixels
cursor Specifies type of cursor.eg:dot,arrow,circle
114
SCSA1204- Python Programming
font Specifies font type of the text written inside the widget
fg Foreground color of the widget
height Height of the widget
width Width of the widget
image Specifies image to be displayed in the widget
padx Horizontal padding of text
pady Vertical padding of text
relief Specifies type of border
value Set value to the control variable if the button is selected.
selectbackground Set back ground color of the selected text.
xscrollcommand User can scroll the list box horizontally
yscrollcommand User can scroll the list box vertically
Example:
fromtkinter import *
top = Tk()
listbox = Listbox(top)
listbox.insert(1,"India")
115
SCSA1204- Python Programming
listbox.insert(2, "USA")
listbox.insert(3, "Japan")
listbox.insert(4, "Austrelia")
lbl.pack()
listbox.pack()
top.mainloop()
116
SCSA1204- Python Programming
Output:
MESSAGE
m=Message(root,options)
root-main window
Option Description
117
SCSA1204- Python Programming
Option Description
font Specifies font type of the text written inside the widget
Example:
fromtkinter import *
top = Tk()
msg.pack()
top.mainloop()
118
SCSA1204- Python Programming
119
SCSA1204- Python Programming
Output:
TEXT
Tkinter provides us the Entry widget which is used to implement the single
line text box. Text widget provides advanced capabilities that allow us to edit
a multiline text and format the way it has to be displayed, such as changing its
color and font. We can also use the structures like tabs and marks to locate
specific sections of the text, and apply changes to those areas.
T=Text(root,options)
root-main window
120
SCSA1204- Python Programming
Option Description
bg Specifies background color of the widget
bd Specifies border width. Default is 2 pixels
cursor Specifies type of cursor.eg:dot,arrow,circle
font Specifies font type of the text written inside the widget
fg Foreground color of the widget
height Height of the widget
width Width of the widget
image Specifies image to be displayed in the widget
padx Horizontal padding of text
pady Vertical padding of text
relief Specifies type of border
xscrollcommand User can scroll the text widget horizontally
yscrollcommand User can scroll the text widget vertically
selectbackground Background color of the selected text
General Methods:
Method Description
delete(startindex, This method is used to delete the characters of the
endindex) specified range
get(startindex,endindex) It returns the characters present in the specified
121
SCSA1204- Python Programming
range.
insert(index, string)It is used to insert the specified string at the given
index.
Mark Handling Methods:
Marks are used to bookmark the specified position between the characters of
the associated text.List of Mark handling methods are given below:
Method Description
mark_set(mark,index) It is used to create mark at the specified index.
mark_unset(mark) It is used to clear the given mark
mark_names() It is used to return names of all the marks
The tags are the names given to the specific areas of the text. The tags are
used to configure the different areas of the text separately. The list of tag-
handling methods are given below:
Method Description
tag_add(tagname, startindex, It is used to tag the characters in the
endindex) given range
tag_config() It is used to configure the tag properties
tag_delete(tagname) It is used to delete the given tag
122
SCSA1204- Python Programming
Example:
fromtkinter import *
top = Tk()
text = Text(top)
text.insert(INSERT, "Name.....")
text.insert(END, "Salary.....")
text.pack()
Output:
123
SCSA1204- Python Programming
Explanation:
The tag “Write Here” tags the characters from the index 0 to 4.The tag “Click
Here” tags the characters from the index 8 to 13.These tags are configured
using the method tag_config().
SPINBOX
S=Spinbox(root,options)
root-main window
Option Description
bg Specifies background color of the widget
bd Specifies border width. Default is 2 pixels
cursor Specifies type of cursor.eg:dot,arrow,circle
font Specifies font type of the text written inside the widget
fg Foreground color of the widget
height Height of the widget
width Width of the widget
padx Horizontal padding of text
pady Vertical padding of text
relief Specifies type of border
xscrollcommand User can scroll the text widget horizontally
from_ It is used to show the starting range of the widget.
to It specify the maximum limit of the widget value. The
other is specified by the from_ option.
values It represents the tuple containing the values for this
widget.
Table :Spinbox
Example:
fromtkinter import *
top = Tk()
spin.pack()
125
SCSA1204- Python Programming
top.mainloop()
Output:
FRAME
Frame widget is used to organize the group of widgets. It acts like a container
which can be used to hold the other widgets. The rectangular areas of the
screen are used to organize the widgets to the python application.
S=Frame(root,options)
root-main window
126
SCSA1204- Python Programming
Option Description
bg Specifies background color of the widget
bd Specifies border width. Default is 2 pixels
cursor Specifies type of cursor.eg:dot,arrow,circle
height Height of the widget
width Width of the widget
Relief Specifies type of border
Table: Frame Widget
Example:
fromtkinter import *
top = Tk()
Topframe = Frame(top)
Topframe.pack(side = TOP)
Bottomframe = Frame(top)
Bottomframe.pack(side =BOTTOM)
btn1 = Button(Topframe, text="Submit", fg="red",activebackground = "red")
btn1.pack(side = LEFT)
btn2 = Button(Topframe, text="Remove", fg="brown", activebackground =
"brown")
btn2.pack(side = RIGHT)
127
SCSA1204- Python Programming
Output:
Explanation:
Here two frames (Top Frame and Bottom Frame) have been
created.Topframe contains submit and remove buttons and Bottom frame
contains Add and modify buttons .
128
SCSA1204- Python Programming
Binding function is used to deal with the events. We can bind Python’s
Functions and methods to an event as well as we can bind these functions to
any particular widget. Events can come from various sources, including key
presses and mouse operations by the user. Tkinter provides a powerful
mechanism to let you deal with events yourself. For each widget, you
can bind Python functions and methods to events.
widget.bind(event, handler)
Example:
fromtkinter import *
fromtkinter.ttk import *
# creates tkinter window or root window
root = Tk()
# function to be called when button-2 of mouse is pressed
def pressed2(event):
print('Button-2 pressed at x = % d, y = % d'%(event.x, event.y))
# function to be called when button-3 of mouse is pressed
def pressed3(event):
print('Button-3 pressed at x = % d, y = % d'%(event.x, event.y))
## function to be called when button-1 is double clocked
129
SCSA1204- Python Programming
defdouble_click(event):
print('Double clicked at x = % d, y = % d'%(event.x, event.y))
frame1 = Frame(root, height = 100, width = 200)
# Binding mouse buttons with the Frame widget
frame1.bind('<Button-2>', pressed2)
frame1.bind('<Button-3>', pressed3)
frame1.bind('<Double 1>', double_click)
frame1.pack()
root.mainloop()
Output:
130
SCSA1204- Python Programming
Example:
fromtkinter import *
fromtkinter.ttk import *
defkey_press(event):
key = event.char
root = Tk()
root.geometry('200x100')
mainloop()
Output:
131
SCSA1204- Python Programming
132
SCSA1204- Python Programming
QUESTIONS
6. Write the GUI program to create List Box for shopping cart.
10. Wrtite a Pyhton program to create check button for selecting multiple
hobbies.
133
SCSA1204- Python Programming
SCHOOL OF COMPUTING
129
SCSA1204- Python Programming
Database(usingNoSQL):ConnectorModule–Cursor–Statements-
Exceptionsin database.Networkconnectivity:Socketmodule-
Client–Server–Email–URLAccess.
DBMS
To store data, a file or database can be used. A file stores data in the
secondary storage device like hard disk, either in the text format or binary
format.
130
SCSA1204- Python Programming
1. Databasesupport
SQL
NoSQL
MongoDB
Big Data
Content Management and Delivery
Mobile and Social Infrastructure
User Data Management
Data Hub
PyMongo
C:\Users\Your Name\AppData\Local\Programs\Python\Python36-
32\Scripts>python -m pip install pymongo
Big Data
Content Management and Delivery
Mobile and Social Infrastructure
User Data Management
Data Hub
Test PyMongo
132
SCSA1204- Python Programming
demo_mongodb_test.py:
import pymongo
Creating a Database
MongoDB will create the database if it does not exist, and make a connection
to it.
Example
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
MongoDB waits until you have created a collection (table), with at least one
document (record) before it actually creates the database (and collection).
Creating a Collection
To create a collection in MongoDB, use database object and specify the name
of the collection you want to create.
133
SCSA1204- Python Programming
Program
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
Example
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
134
SCSA1204- Python Programming
mycol = mydb["customers"]
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
mylist = [
{ "name": "Amy", "address": "Apple st 652"},
{ "name": "Hannah", "address": "Mountain 21"},
{ "name": "Michael", "address": "Valley 345"},
{ "name": "Sandy", "address": "Ocean blvd 2"},
{ "name": "Betty", "address": "Green Grass 1"},
{ "name": "Richard", "address": "Sky st 331"},
{ "name": "Susan", "address": "One way 98"},
{ "name": "Vicky", "address": "Yellow Garden 2"},
135
SCSA1204- Python Programming
x = mycol.insert_many(mylist)
Just like the SELECT statement is used to find data in a table in a MySQL
database.
Find One
Example
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
136
SCSA1204- Python Programming
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
x = mycol.find_one()
print(x)
Output
Find All
To select data from a table in MongoDB, we can also use the find() method.
The first parameter of the find() method is a query object. In this example we
use an empty query object, which selects all documents in the collection.
Example
Return all documents in the "customers" collection, and print each document:
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
137
SCSA1204- Python Programming
for x in mycol.find():
print(x)
When finding documents in a collection, you can filter the result by using a
query object.
The first argument of the find() method is a query object, and is used to limit
the search.
Example
138
SCSA1204- Python Programming
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
mydoc = mycol.find(myquery)
for x in mydoc:
print(x)
output
Example
Find documents where the address starts with the letter "S" or higher:
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
139
SCSA1204- Python Programming
mydoc = mycol.find(myquery)
for x in mydoc:
print(x)
Output
Fig No 1
This parameter is optional, and if omitted, all fields will be included in the
result.
Example
140
SCSA1204- Python Programming
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
Output
Use the sort() method to sort the result in ascending or descending order.
141
SCSA1204- Python Programming
The sort() method takes one parameter for "fieldname" and one parameter for
"direction" (ascending is the default direction).
Example
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
mydoc = mycol.find().sort("name")
for x in mydoc:
print(x)
OUTPUT
Sort Descending
sort("name", 1) #ascending
sort("name", -1) #descending
Example
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
for x in mydoc:
print(x)
Output
Note: If the query finds more than one document, only the first occurrence is
deleted.
Example
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
144
SCSA1204- Python Programming
mycol.delete_one(myquery)
Example
Delete all documents were the address starts with the letter S:
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
x = mycol.delete_many(myquery)
output
2 documents deleted.
145
SCSA1204- Python Programming
Example
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
x = mycol.delete_many({})
Output:
11 documents deleted
Delete Collection
146
SCSA1204- Python Programming
Example
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
mycol.drop()
The drop() method returns true if the collection was dropped successfully, and
false if the collection does not exist.
Note: If the query finds more than one record, only the first occurrence is
updated.
Example
147
SCSA1204- Python Programming
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
mycol.update_one(myquery, newvalues)
148
SCSA1204- Python Programming
OUTPUT
Update Many
To update all documents that meets the criteria of the query, use
the update_many() method.
Example
Update all documents where the address starts with the letter "S":
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
149
SCSA1204- Python Programming
Output
2 documents updated.
The limit() method takes one parameter, a number defining how many
documents to return.
Example
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
myresult = mycol.find().limit(5)
OUTPUT
{'_id': 1, 'name': 'John', 'address': 'Highway37'}
{'_id': 2, 'name': 'Peter', 'address': 'Lowstreet 27'}
{'_id': 3, 'name': 'Amy', 'address': 'Apple st 652'}
{'_id': 4, 'name': 'Hannah', 'address': 'Mountain 21'}
{'_id': 5, 'name': 'Michael', 'address': 'Valley 345'}
151
SCSA1204- Python Programming
Cursor Class
import mysql.connector;
conn=mysql.connector.connect(host=’localhost’,database=’university’,user=’r
oot’, password=’***’)
The next step is to create cursor class object by calling the cursor() method on
‘conn’ object as:
cursor=con.cursor()
The resultant rows retirieved from the table are stored in cursor object. the
result can be fetched using fetchone() or fetchall() methods.
Finally, the connection with MySQL can be closed by closing the cursor and
connection objects as:
cursor.close()
conn.close()
Program: A python program to retrieve and display all rows from the student
table:
import mysql.connector;
conn=mysql.connector.connect(host=’localhost’,database=’university’,user=’r
oot’, password=’***’)
cursor=con.cursor()
row = cursor.fetchone()
print(row)
row=cursor.fetchone()
cursor.close()
conn.close()
153
SCSA1204- Python Programming
Output:
Exceptions Classes
Table No 1
Built in Exceptions
Exception Description
Warning Used for non-fatal issues. Must subclass
StandardError.
Error
Base class for errors. Must subclass
StandardError.
InterfaceError Used for errors in the database module, not the
database itself. Must subclass Error.
DatabaseError Used for errors in the database. Must subclass
Error.
DataError Subclass of DatabaseError that refers to errors in
154
SCSA1204- Python Programming
the data.
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.
Exception Description
IntegrityError Subclass of DatabaseError for situations that
would damage the relational integrity, such as
uniqueness constraints or foreign keys.
InternalError Subclass of DatabaseError that refers to errors
internal to the database module, such as a cursor
no longer being active.
ProgrammingError Subclass of DatabaseError that refers to errors
such as a bad table name and other things that can
safely be blamed on you.
NETWORKING
155
SCSA1204- Python Programming
IP : Internet Protocol
FTP : File Transfer Protocol
SMTP : Simple Mail Transfer Protocol
HTTP : Hyper Text Transfer Protocol
The Network reference models were developed to allow products from
different manufacturers to interoperate on a network. A network reference
model serves as a blueprint, detailing standards for how protocol
communication should occur.
The most widely recognized reference models are, the Open Systems
Interconnect ( OSI ) Model and Department of Defense ( DoD, also known
as TCP/IP ) model.
156
SCSA1204- Python Programming
For example:
A socket is a link between two applications that can communicate with one
another (either locally on a single machine or remotely between two machines
in separate locations).
157
SCSA1204- Python Programming
In order to create a socket, you use the socket.socket() function, and the
syntax is as simple as:
import socket
After obtaining your socket object, you can then create a server or client as
desired using the methods available in the socket module.
Before we get started, let's look at the client socket methods available in
Python.
s= socket.socket(socket.AF_INET, socket.sock_STREAM)
To create a new socket, you first import the socket method of the socket class.
import socket
server = "localhost"
port =80
159
SCSA1204- Python Programming
stream_socket.connect(server_address)
It's important to note that the host and port must be a tuple.
message = 'message'
stream_socket.sendall(message)
data = sock.recv(10)
print data
stream_socket.close()
import socket
import sys
160
SCSA1204- Python Programming
# Define host
host = 'localhost'
port = 8080
print "connecting"
stream_socket.connect(server_address)
# Send data
message = 'message'
stream_socket.sendall(message)
# response
data = stream_socket.recv(10)
print data
stream_socket.close()
161
SCSA1204- Python Programming
Now let's take a look at a simple Python server. The following are the socket
server methods available in Python.
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Create a socket.
import socket
import sys
# Define host
host = 'localhost'
162
SCSA1204- Python Programming
port = 8080
sock.bind((host, port))
sock.listen(1)
data = connection.recv(16)
if data:
connection.sendall(data)
else:
163
SCSA1204- Python Programming
connection.close()
Now run the client and server programs in separate terminal windows, so they
can communicate with each other.
Server Output
$ python server.py
received "message"
Client Output
$ python client.py
connecting
message
socket closed
164
SCSA1204- Python Programming
Here is a simple syntax to create one SMTP object, which can later be used
to send an e-mail –
import smtplib
host − This is the host running your SMTP server. You can specify IP
address of the host or a domain name like tutorialspoint.com. This is
optional argument.
port − If you are providing host argument, then you need to specify a
port, where SMTP server is listening. Usually this port would be 25.
165
SCSA1204- Python Programming
Example
Here is a simple way to send one e-mail using Python script. Try it once −
import smtplib
sender = 'from@fromdomain.com'
receivers = ['to@todomain.com']
"""
try:
smtpObj = smtplib.SMTP('localhost')
except SMTPException:
166
SCSA1204- Python Programming
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. Unless you
are using a webmail service (such as Hotmail or Yahoo! Mail), your e-mail
provider must have provided you with outgoing mail server details that you
can supply them, as follows − smtplib.SMTP('mail.your-domain.com', 25)
167
SCSA1204- Python Programming
SCHOOL OF COMPUTING
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
1
SCSA1204- Python Programming
In psychology and other medical treatment institutions, sentiment analysis can be used to
detect whether the individuals’ emotion is normal or abnormal, and based on the data
record they can decide person health.
Politics:
In the political field, candidates to be elected can use sentiment analysis to predict their
political status, to measure people’s acceptance. It can also be used to predict election
results for electoral board commissions.
Education:
Universities and other higher institutes like colleges can use sentiment analysis to know
their student’s feedback and comment, therefore they can take consideration to revise or
improve their education curriculum.
Installations in Anaconda
NLTK:is used for understanding of human natural language.
Installation Using conda command.
conda install -c anaconda nltk
2
SCSA1204- Python Programming
NumPy: is a python package used for scientific and computional methods in python.
Installation Using conda.
conda install -c conda-forge numpy
Using pip.
Matplotlib: is a python module used for data visulalization and and 2D plotting for
representation of data.
Installation Using conda.
Authentication
There are many ways to fetch Facebook comments those are:
3
SCSA1204- Python Programming
importtime
importpandas as pd
importnumpy as np
importmatplotlib.pyplot as plt
importnltk
importio
importunicodedata
importnumpy as np
importre
importstring
fromnumpyimportlinalg
fromnltk.sentiment.vaderimportSentimentIntensityAnalyzer
fromnltk.tokenizeimportsent_tokenize, word_tokenize
fromnltk.tokenizeimportPunktSentenceTokenizer
fromnltk.tokenizeimportPunktSentenceTokenizer
fromnltk.corpusimportwebtext
fromnltk.stem.porterimportPorterStemmer
fromnltk.stem.wordnetimportWordNetLemmatizer
with open('kindle.txt', encoding ='ISO-8859-2') as f:
text =f.read()
sent_tokenizer=PunktSentenceTokenizer(text)
sents=sent_tokenizer.tokenize(text)
print(word_tokenize(text))
print(sent_tokenize(text))
porter_stemmer=PorterStemmer()
nltk_tokens=nltk.word_tokenize(text)
forwinnltk_tokens:
print("Actual: % s Stem: % s"%(w, porter_stemmer.stem(w)))
wordnet_lemmatizer=WordNetLemmatizer()
nltk_tokens=nltk.word_tokenize(text)
4
SCSA1204- Python Programming
forwinnltk_tokens:
print("Actual: % s Lemma: % s"%(w, wordnet_lemmatizer.lemmatize(w)))
text =nltk.word_tokenize(text)
print(nltk.pos_tag(text))
sid=SentimentIntensityAnalyzer()
tokenizer =nltk.data.load('tokenizers / punkt / english.pickle')
with open('kindle.txt', encoding ='ISO-8859-2') as f:
fortextinf.read().split('\n'):
print(text)
scores =sid.polarity_scores(text)
forkeyinsorted(scores):
print('{0}: {1}, '.format(key, scores[key]), end ='')
print()
Output:
Downloading(fetching) facebook comment from Kaggle site and save it as text format.
5
SCSA1204- Python Programming
Preprocessing the data through SkLearn and nltk libraries .we first tokenize the data and
then after tokenizing we stemize and lemmatize.
Parse the comments using Vader library . Classify each comment as positive, negative
or neutral.
Now, let us try to understand the above piece of code:
First we open a file named kindle which is downloaded from Kaggle site and saved in
local disk.
with open(‘kindle.txt’, encoding=’ISO-8859-2′) as f:
After we open a file we preprocess the text through tokenize, stemize and then
lemmatize:
Tokenize the text, i.e split words from text.
sent_tokenizer = PunktSentenceTokenizer(text)
sents = sent_tokenizer.tokenize(text)
print(word_tokenize(text))
print(sent_tokenize(text))
POS( 5t of speech) tagging of the tokens and select only significant features/tokens like
6
SCSA1204- Python Programming
print(nltk.pos_tag(text))
Pass the tokens to a sentiment intensity analyzer which classifies the Facebook
Let us to understand what the sentiment code is and how VADER performs on the output of
the above code:
i love my kindle
7
SCSA1204- Python Programming
python -m textblob.download_corpora
Authentication:
In order to fetch tweets through Twitter API, one needs to register an App through their
twitter account. Follow these steps for the same:
Fill the application details. You can leave the callback url field empty.
Once the app is created, you will be redirected to the app page.
Copy ‘Consumer Key’, ‘Consumer Secret’, ‘Access token’ and ‘Access Token
Secret’.
Implementation:
importre
importtweepy
fromtweepyimportOAuthHandler
fromtextblobimportTextBlob
classTwitterClient(object):
'''
Generic Twitter Class for sentiment analysis.
'''
8
SCSA1204- Python Programming
def__init__(self):
'''
Class constructor or initialization method.
'''
# keys and tokens from the Twitter Dev Console
consumer_key='XXXXXXXXXXXXXXXXXXXXXXXX'
consumer_secret='XXXXXXXXXXXXXXXXXXXXXXXXXXXX'
access_token='XXXXXXXXXXXXXXXXXXXXXXXXXXXX'
access_token_secret='XXXXXXXXXXXXXXXXXXXXXXXXX'
# attempt authentication
try:
# create OAuthHandler object
self.auth=OAuthHandler(consumer_key, consumer_secret)
# set access token and secret
self.auth.set_access_token(access_token, access_token_secret)
# create tweepy API object to fetch tweets
self.api=tweepy.API(self.auth)
except:
print("Error: Authentication Failed")
defclean_tweet(self, tweet):
'''
Utility function to clean tweet text by removing links, special characters
using simple regex statements.
'''
return' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])
|(\w+:\/\/\S+)", "", tweet).split())
defget_tweet_sentiment(self, tweet):
'''
Utility function to classify sentiment of passed tweet
9
SCSA1204- Python Programming
try:
# call twitter api to fetch tweets
fetched_tweets=self.api.search(q =query, count =count)
10
SCSA1204- Python Programming
excepttweepy.TweepError as e:
# print error (if any)
print("Error : "+str(e))
defmain():
# creating object of TwitterClient Class
api=TwitterClient()
# calling function to get tweets
tweets =api.get_tweets(query ='Donald Trump', count =200)
11
SCSA1204- Python Programming
if__name__ =="__main__":
# calling main function
main()
Here is how a sample output looks like when above program is run:
Positive tweets:
#MakeAme…
RT @vooda1: CNN Declines to Air White House Press Conference Live YES!
POTUS plans new deal for UK as Theresa May to be first foreign leader to meet new
Negative tweets:
12
SCSA1204- Python Programming
Their lies are not just lies. Their lies are authoritarian propaganda.
Me: https://t.co/GPgy8R8HB5
It's ridiculous that people are more annoyed at this than Donald Trump's sexism.
about Donald Trump news conference it seems he can't face the truth eithe…
RT @fravel: With False Claims, Donald Trump Attacks Media on Crowd Turnout
Aziz Ansari Just Hit Donald Trump Hard In An Epic Saturday NIght Live Monologue
First of all, we create a TwitterClient class. This class contains all the methods to
interact with Twitter API and parsing tweets. We use __init__ function to handle the
authentication of API client.
In get_tweets function, we use:
fetched_tweets = self.api.search(q = query, count = count)
TextBlob is actually a high level library built over top of NLTK library. First we
call clean_tweet method to remove links, special characters, etc. from the tweet using some
simple regex.
Then, as we pass tweet to create a TextBlob object, following processing is done over text
by textblob library:
13
SCSA1204- Python Programming
TextBlob uses a Movies Reviews dataset in which reviews have already been labelled as
positive or negative.
Positive and negative features are extracted from each positive and negative review
respectively.
Training data now consists of labelled positive and negative features. This data is trained on
a Naive Bayes Classifier.
Then, we use sentiment.polarity method of TextBlob class to get the polarity of tweet
between -1 to 1.
Then, we classify polarity as:
if analysis.sentiment.polarity> 0:
return 'positive'
elifanalysis.sentiment.polarity == 0:
return 'neutral'
else:
return 'negative'
Finally, parsed tweets are returned. Then, we can do various type of statistical analysis on
the tweets. For example, in above program, we tried to find the percentage of positive,
negative and neutral tweets about a query.
14
SCSA1204- Python Programming
15