SlideShare a Scribd company logo
PYTHON
Chapter 1 : Introduction
Python is general purpose high level programming language.
It was invented by Guido Van Rossam .The development of python started from
1989 and it launched in Feb 20th 1991.
The idea of python started from yearly 1980’s and real implementation started
from year 1989 and finally published in year 27th Feb 1991. Professionally first
version in 1994.
The Guido developed python while working in national research institute of
Netherlands. Birth date of Guido was 31st Jan 1956 in Netherland. He has
completed his master degree in 1982 in mathematics and computer science.
Computer Science in Amstredam University. After completing Master Degree he
has worked in Netherland Organisation of Research Center.
Python developed Centrum Wiskunda and informatica research center in the
field of mathematics and computers.
Ancestor of Python
SETL Language is a very high level programming language based on
mathematics and theory off sets.
SETL appeared in 1969, developed in NewYork University. ABC language came
from this language. ABC is an interpreter language. And ABC developed in CWI.
The Guido worked long time in this language and learned interpreter and
designing of language through this language.
After working few year in ABC Guido came to know that there are many
limitation in ABC, because it is extensible(it means we cannot add any features
in this language). So whatever Guido wanted to make changes in ABC, it became
impossible.
Guido worked in Modula2+ and it takes information about Modula3 from
developer. In Modula3, he found out the exception handling concept ,which is
not available in ABC. And also worked in Ameabo Operating System, it is a
distributed Operating System and he find out drawback in this system also. And
it is very difficult to find the error in this operating system.
Reason behind python is to release the drawback of Abc for eg. Exception
Handling. And this happened in year 1999 in December Christmas holiday.
How Python name came into the picture?
Monty Python Client Circus was the name of comedy series and Guido was fan of
this series , so he was inspired by the name, and named it as Python.
python program is a combination of :
1.Functional programming Language from c
2.oops concept from c++.
3.Scripting language from perl and shell script
4.Modular programming language from Modula-3.
Syntax from c and ABC Language.
Features of python
1.Simple and easy to learn:
Python is easy to learn and use. It is developer-friendly and high level
programming language. Python has few keywords, simple structure, and a
clearly defined syntax. This allows the student to pick up the language quickly.
2.Open Source:
Python language is freely available at offical web address.The source-code is also
available. Therefore it is open source
3.High Level Programming Language:
4:Platform Independent:
Python can run equally on different platforms such as Windows, Linux, Unix and
Macintosh etc. So, we can say that Python is a portable language.
5:Portability:
Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.
6.Dynamicall30,40]y Typed:
No need to defined data type for the variable
7.Both Procedure Orented and Object Oriented:
Python supports object oriented language and concepts of classes and objects
come into existence and also we can create the programs without using class
8.Interpreted Language:
Python is an interpreted language i.e. interpreter executes the code line by line
at a time. This makes debugging easy and thus suitable for beginners.
9.Extensible:
It implies that other languages such as C/C++ can be used to compile the code
and thus it can be used further in our python code.
10.A broad standard library:
Python's bulk of the library is very portable and cross-platform compatible on
UNIX, Windows, and Macintosh.
11.Databases:
Python provides interfaces to all major commercial databases
Python version:
python 1.0 introduced in Jan 1994
python 2.0 introduced in October 2000
python 3.0 introduced in Dec 2008
Python is not backward compatible.
Flavour of Python
1. Cpython, can be used to work with C language application.
2. Jpython or jython, it is for java applications.
3. Ironpython ,this python is used to work with C++ and .Net Applications.
4. Pypython, inside python it contain Virtual Machine with JIT Compiler
so it’s performance is relatively improved. If you want high performance go for
this python.
5. Ruby Python, used to work with ruby.
6. Anaconda Python, it is used to work with Big Data Python .
7. Stackless Python, for concretely multithreaded concept.
Where we can use python
1.Desktop application
2.Web applications
3.Database Application
4.For Networking applications
5.Games
6.Data analysis
7.Machin Language
8.AI
9.For IOT Appplication
The company using python
1.Google
2.YouTube
3.Dropbox
4.NASA
Reserve key words:
There are 33 key words.
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del',
'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda',
'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
Rules of identifer
1. A-Z and a-z and 0-9 this are only allowed in symbol.
2. It should not start with digit.
3. Case Sensitive.
4. Keyword is not allowed.
5. No long limit.
6. $ symbol is not allowed for identifer.
Data types:
1.int
2.float
3.complex
4.bool
5.str
6.bytes
7.bytearray
8.range
9.list
10.tuple
11.set
12.frozenset
13.dict
14.None
Long Datatype used only in python-2 but not in python-3 and double,character
is not allowed in python.
In python every thing implemented as a object and all objects are immutable we
cannot modifies the original object.
In python 0 to 256 objects are created when you interpreted the programs
In python when we create object for int ,bool,str it can be reused
for
ex if we define one object:
x=10
y=10
z=10
now only one object created and three reference refer the same object
for eg:
x=10
y=10
z=10
print("Id of x ",id(x))
print("Id of y ",id(y))
print("Id of z ",id(z))
print(x is y)
o/p
Id of x 10919712
Id of y 10919712
Id of z 10919712
True
name="coder"
name1="coder"
print("Id of name ",id(name))
print("Id of name1 ",id(name1))
print(name is name1)
o/p
Id of name 140530020957576
Id of name1 140530020957576
True
b=True
b1=True
print("Id of b ",id(b))
print("Id of b1 ",id(b1))
print(b is b1)
Id of b 10744160
Id of b1 10744160
True
the reusing of object in int is possible from 0 to 256
python accept:
1.Decimal form
2.Binary form
a=0B1111
print(a)
o/p 15
a=-0B1111
print(a)
o/p -15
3.octal form
a=0o1111
print(a)
o/p 585
4.Hexa Decimal.
a=0XFace
print(a)
o/p 64206
For Type cast we need this method
1)int()
2)float()
3)bool()
4)str()
print(int(123.33)) #converting float to int
print(int(True)) #converting bool to int
print(int("10")) #converting String to int
#(int("123.33")) #converting String to int it give type cast error we can
applicable only base vakue in s String
print(float(12))
print(float(True))
print(float(False))
print(float("10"))
print(float("10.2"))
print#(float("sad")) give error
print(bool(0))
print(bool(1))
print(bool(10))
print(bool(0.0))
print(bool(0.1))
print(bool("coder")) #o/p true
print(bool(""))# o/p false
print(bool(" "))#o/p True
print(str(10))
print(str(10.0))
print(str(True))
print(str(10))
''' Slice'''
name="Coder technology"
print(name)
print(name[2])
print(name[1:3])
print(name[2:7])
print(name[-1])
print(name[-2])
print(name[-5])
print(name[-5:-1])
print("-5 :-8 ",name[-5:-8])#this is not possible
print("-8 :-5 ",name[-8:-5])
print("-8 :-2 ",name[-8:-2])
o/p
Coder technology
d
od
der t
y
g
o
olog
-5 :-8
-8 :-5 chn
-8 :-2 chnolo
Chaptar 2: Basic Programs
Variable = it is used to store the value;
data type = in python no need to give data type
it change its data type according to the value
for eg
num=10 // no need to give datatype
print(type(num))
print method is used to print in console it is inbuilt method type method is use to
find the data type
o/p
10
<class 'int'>
st="coder"
print(type(st))
print("Name is =",st) ''' , is used for concatination'''
o/p
<class 'str'>
Name is = coder
Addition
num=10
num1=20
result=num+num1
30,40]
print("Addition of two number is =",result)
o/p
Addition of two number is = 30
Taking input from the user
'''
input method is used to take input from the user and its return type is by default
String so we want convert it according to our input by casting
'''
num=int(input("enter the first number= "))
num1=int(input("enter the second number= "))
result=num+num1
print("Addition =",result)
o/p
enter the first number= 10
enter the second number= 20
Addition = 30
Division
num=int(input("enter the first number ="))
num1=int(input("enter the second number ="))
result=num/num1
print("Division =",result)
o/p
enter the first number =5
enter the second number =3
Division = 1.6666666666666667
Control Statements
1)if..else
Syntax:
if condition:
#code
else:
#code
'''if else
Even or odd
'''
num=int(input("Enter the number to check ="))
if num%2 is 0:
print("even number")
else:
print("odd number")
'''
for if else no need to give the bracket jest we want to give ":"
'''
Nested if else syntax:
if condition:
#code
if condition:
#code
else:
#code
else:
#code
''' nested if else
'''
percentage=int(input("Enter the percentage ="))
if percentage >= 90:
exp=int(input("Enter the number to experience = "))
if exp >= 2:
print("eligible for job")
else:
print("not eligible for job")
else:
print("not qualified")
'’'Ladder if else'''
mark1=int(input("Enter the mark one ="))
mark2=int(input("Enter the mark two ="))
mark3=int(input("Enter the mark three ="))
total=mark1+mark2+mark3
print("Total mark is = ",total)
per=total/300*100
print("Percentage is =",per)
if per >= 90:
print("A grade")
elif per >=70 and per<90:
print("B grade")
elif per >=50 and per<70:
print("c grade")
else:
print("fail")
'''Areat of the triangle'''
base = float(input('Enter the value of base : '))
height = float(input('Enter the value of height : ' ))
area = 0.6* base * height;
print('Area of Triangle is ',area)
num=10;
print("number is"+str(num))#we cannot use + operators for concatination of
other datatype
#we can concat only string so if we use + operators then we have cast it in
String
Loops
num=1
while num<10:
print(num)
num+= 1
num=int(input("enter the number"))
num1=1;
while num1<=num:
if num1%2==0:
print(num1)
num1+=1
for i in range(1,5):
'''by default it increment by 1'''
print(i)
o/p
1
2
3
4
for i in range(5,0,-1): #
''' for decrement we want to use -1'''
print(i)
o/p
5
4
3
2
1
for i in range(1,5):
print(i,end=" ")
'''
bydefault print go to next line so for continuing in one line we use end=”” ''
o/p
1 2 3 4
Prime number
num=int(input("enter the number to check "))
for i in range(2,num):
if (num%i)==0:
print(num,"is not a prime number")
break;
else:
print(" is a prime number")
Pattern 1:
for i in range(1,6):
for j in range(1,6):
print(i,end=" ")
print()
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
5 5 5 5 5
Patterns 2:
for i in range(1,6):
for j in range(1,i+1):
print(j,end=" ")
print()
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Pattern 3:
for i in range(6,0,-1):
for j in range(5,i-1,-1):
print(j,end=" ")
print()
5
5 4
5 4 3
5 4 3 2
5 4 3 2 1
Patterns 4:
for i in range(1,6):
for j in range(5,i-1,-1):
print(j,end=" ")
print()
5 4 3 2 1
5 4 3 2
5 4 3
5 4
5
for i in range(1,6):
for space in range(5,i,-1):
print(" ",end="")
for j in range(1,i):
print("* ",end="")
print()
*
* *
* * *
* * * *
Pattern 5:
for i in range(1,6):
for space in range(5,i,-1):
print(" ",end="")
for j in range(1,i):
print("* ",end="")
print()
for i in range(1,5):
for space in range(0,i,):
print(" ",end="")
for j in range(4,i,-1):
print("* ",end="")
print()
*
* *
* * *
* * * *
* * *
* *
*
pattern 6:
for i in range(1,6):
for space in range(5,i,-1):
print(" ",end="")
for j in range(1,i):
print(j," ",end="")
print()
for i in range(1,5):
for space in range(0,i,):
print(" ",end="")
for j in range(4,i,-1):
print(j," ",end="")
print()
1
1 2
1 2 3
1 2 3 4
4 3 2
4 3
4
pattern 7:
for i in range(1,6):
for j in range(1,6):
if i==1 and j==1 or i==1 and j==5 or i==5 and j==1 or i==5 and j==5:
print("*" ,end="")
else:
print(" ",end="")
print()
* *
* *
Python Collections (Arrays)
There are four collection data types in the Python programming language:
 List is a collection which is ordered and changeable. Allows duplicate
members.
 Tuple is a collection which is ordered and unchangeable. Allows duplicate
members.
 Set is a collection which is unordered and unindexed. No duplicate
members.
 Dictionary is a collection which is unordered, changeable and
indexed. No duplicate members.
1)cars = ["maruthi", "suzuki", "BMW"]
print(cars)
2)x = cars[0]
print(x)
3)cars[0] = "Toyota"
print(cars)
4)for x in cars:
print(x)
''' Add one more element to the cars array:'''
5)cars.append("Honda")
print(cars)
''' Delete the second element of the cars array:'''
6)cars.pop(1)
print(cars)
7)cars.remove("BMW")
print(cars)
8)a = [1, 2, 3, 4]
print(len(a))
print(a[0])
for i in range(len(a), 0, -1):
print(i, end=' ')
'''it just acts like for loop in range paass arguemnts like u pass in for loop
first aregument in range is from where do u want to start
second is until where it should go
and thirs is the amount it should be increased or decreased
'''
print()
for i in range(5):
for j in range(5, i, -1):
print('*', end=' ')
print()
9)size=int(input("enter the size"))
arr=[]
print("enter %d"%size+"value:")
for i in range(size):
n=int(input("enter %d =" %(i+1)+ "value:"))
arr.append(n)
for i in range(len(arr)):
print(arr[i],end=" ")
print()
arr1=[]
print("enter the second array")
for i in range(size):
n=int(input("enter %d =" %(i+1)+ "value:"))
arr1.append(n)
for i in range(len(arr)):
print(arr1[i],end=" ")
print()
addition=[]
for i in range(size):
addition.append((int)(arr[i]+arr1[i]))
for i in range(len(addition)):
print(addition[i],end=' ')
-------------------------------------------------
find put largest number in array
size=int(input("enter the size"))
arr=[]
for i in range(size):
n=int(input("enter the "+str((i+1))+" value:"))
arr.append(n)
largest=arr[0]
for i in range(size):
if arr[i]>largest:
largest=arr[i]
print("largest",largest)
1) l=["apple","banana","mango"]
print(l)
2) l=[1,12,123.0,"hello"]
print(l)
3)l.append("world")
''' we can modify the list'''
print(l)
4)for i in l:
print(i)
''' this work like a enhansed for loop'''
5)for i in range(0,len(l)):
print(l[i])
6)l1=[]
a=int(input("Enter the size"))
''' take size from the user '''
for k in range(0,a):
b=input("inter the value");
l1.append(b);
print(l1)
print(len(l1))
7)if "12" in l1:
print("yes")
else:
print("no")
8)l=[10,4,15,24,85,9]
for i in l:
print (i);
9)print("set the value at position one")
l.insert(1,55)
for i in l:
print (i);
10)l.remove(15)
print ("after removing")
for i in l:
print (i);
11)l.pop()
print ("after pop it remoove the last elements")
for i in l:
print (i);
12)del l[1]
print("after del :")
for i in l:
print (i);
13)print("To clear the list")
l.clear()
print(l)
14)del l
print(l)
2-Dimentional array:
A two dimensional array is usually represented in Python by a list of lists.
However, the
initialization of such a value is not as easy as the initialization of a one-
dimensional list.
Here is an example that illustrates the most common technique.
Example:
row=int(input("Enter number of rows for matrix:"))
column=int(input("Enter number of columns for matrix"))
first_matrix=[]
second_matrix=[]
result_matrix=[]
print("Enter {} * {} Matrix".format(row,column))
print("Enter first Matrix:")
for r1 in range(row):
rows=[]
for c1 in range(column):
ele=int(input("Enter element:"))
rows.append(ele)
first_matrix.append(rows)
#print("first matrix is: ".format(first_matrix))
print("Enter second Matrix:")
for r1 in range(row):
rows=[]
for c1 in range(column):
ele=int(input("Enter element:"))
rows.append(ele)
second_matrix.append(rows)
#print(second_matrix)
for r1 in range(row):
rows=[]
for c1 in range(column):
row=int(first_matrix[r1][c1])+int(second_matrix[r1][c1])
#print(row)
rows.append(row)
result_matrix.append(rows)
print("Addition of {}+{}={}".format(first_matrix,second_matrix,result_matrix))
Output
Enter number of rows for matrix:2
Enter number of columns for matrix2
Enter 2 * 2 Matrix
Enter first Matrix:
Enter element:1
Enter element:1
Enter element:2
Enter element:2
Enter second Matrix:
Enter element:1
Enter element:3
Enter element:4
Enter element:5
Addition of [[1, 1], [2, 2]]+[[1, 3], [4, 5]]=[[2, 4], [6, 7]]
Tuple
A tuple is a collection which is ordered and unchangeable. In Python tuples are
written with round brackets.
t = ("apple", "banana", "cherry")
print(t)
t = ("apple", "banana", "cherry")
print(t[1])
t = ("apple", "banana", "cherry")
t[1] = "blackcurrant"
# The values will remain the same:
print(t)
Set
A set is a collection which is unordered and unindexed. In Python sets are
written with curly brackets.
s = {"geetha", "ramesh", "cherry"}
print(s)
o/p
{'ramesh', 'geetha', 'cherry'}
Access Items
You cannot access items in a set by referring to an index, since sets are
unordered the items has no index.
But you can loop through the set items using a for loop, or ask if a specified value
is present in a set, by using the in keyword.
1)thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
2)thisset = {"apple", "banana", "cherry"}
print("banana" in thisset) //to check the content
Add Items
To add one item to a set use the add() method.
To add more than one item to a set use the update() method.
3)s1 = {"pineApple", "mango", "cherry"}
s1.add("orange")
print(s1)
4)s2 = {"pineApple", "mango", "cherry"}
s2.update(["orange","graps","watermilon"])
print(s2)
5)s3 = {"apple", "banana", "cherry"}
s3.remove("banana")
print(s3)
6)s4 = {"apple", "banana", "cherry"}
s4.discard("banana")
print(s4)
7) = {"apple", "banana", "cherry"}
x = s5.pop()
print(x)
print(s5)
Dictionary
A dictionary is a collection which is unordered, changeable and indexed. In
Python dictionaries are written with curly brackets, and they have keys and
values.
1)dis={
"empName":"Ramesh",
"id":105,
"salary":1000,
"designation":"Acc"
}
print(dis)//to print the dictionary
2)s=dis["id"]// to fetch the value
print(s)
3)''' Get the value of the "model" key:'''
n=dis.get("empName")
print(n)
''' to change the value'''
4)dis["salary"]=5000;
print(dis)
5)for x in dis:
print(x)
6)for x in dis:
print(dis[x])
''' You can also use the values() function to return values of a dictionary:'''
6)for x in dis.values():
print(x)
'''Loop through both keys and values, by using the items() function:'''
7)for x, y in dis.items():
print(x,y)
8)if "empName" in dis:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
The popitem() method removes the last inserted item (in versions before 3.7, a
random item is removed instead):
'''while loop'''
1)i = 1
while i < 6:
print(i)
i += 1
'''while loop with break'''
2)i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
'''Build in function'''
x=abs(12.30)
print(x)
x=abs(120.3000)
print(x)
x=abs(-12.3000)
print(x)
o/p
12.3
120.3
12.3
The all() function returns True if all items in an iterable are true, otherwise it
returns False.
list=[True,True,True]
x=all(list)
print(x)
list=[True,False,True]
x=all(list)
print(x)
list=[0,10,10]
x=all(list)
print(x)
list=[10,10,10]
x=all(list)
print(x)
o/p
True
False
False
True
Definition and Usage
The any() function returns True if any item in an iterable are true, otherwise it
returns False.
If the iterable object is empty, the any() function will return False.
mylist = [False, True, False]
x = any(mylist)
print(x)
mylist = [0, 10, 20]
x = any(mylist)
print(x)
o/p
True
True
print(math.sqrt(49))
print (pow(3,4)) o/p 9
The bin() function returns the binary version of a specified integer.
The result will always start with the prefix 0b.
x = bin(36)
print(x)
o/p 0b100100
x = chr(97)
print(x) o/p a
The frozenset() function returns an unchangeable frozenset object (which is like
a set object, only unchangeable).
mylist = ['apple', 'banana', 'cherry']
x = frozenset(mylist)
x[1] = "strawberry"
print(x)
o/p
Traceback (most recent call last):
File "/home/ctuser01/Desktop/Backup/new
Python/BsicProject/basicprograms/ClassAndConstructor.py", line 120, in
<module>
x[1] = "strawberry"
TypeError: 'frozenset' object does not support item assignment
5) import calendar
print(calendar.month(1995,5))
bytes operator
b=[12,25,255]
x=bytes(b)
print(x[1])
print(x[2])
print(x[0])
o/p
25
255
12
b=[12,25,258]
x=bytes(b)
print(x[1])
print(x[2])it will give error because we can add in byte elements from 1 to 256
o/p
Traceback (most recent call last):
File "/home/ctuser01/Desktop/Backup/new
Python/BsicProject/basicprograms/Array.py", line 15, in <module>
x=bytes(b)
ValueError: bytes must be in range(0, 256)
bytes are immutable we cannot modifies the elements
for ex:
b=[12,25,250]
x=bytes(b)
print(x[1])
print(x[2])
x[2]=90
print(x[2])
o/p
Traceback (most recent call last):
File "/home/ctuser01/Desktop/Backup/new
Python/BsicProject/basicprograms/Array.py", line 18, in <module>
x[2]=90
TypeError: 'bytes' object does not support item assignment
bytearray is as same as byte
but bytearray is mutable
b=[12,25,250]
x=bytearray(b)
print(x[1])
print(x[2])
x[2]=90
print(x[2])
Chapter 3: Class and Constructor
3. Python Concepts:
. Object - Objects have states and behaviors. Example: A dog has states -
color, name, breed
as well as behaviors -wagging, barking, eating. An object is an instance of a
class.
• Class - A class can be defined as a template/ blue print that describes the
behaviors/states that object of its type support. It is a logical costruct.
• Methods - A method is basically a behavior. A class can contain many
methods. It is in methods where the logics are written, data is manipulated
and all the actions are executed.
• Instance Variables - Each object has its unique set of instance variables.
An object's state is created by the values assigned to these instance
variables.
OOPs concepts
1. Inheritance:
It is a mechanism where one class can acquire the properties of another class.
Using inheritance, a
class can inherit the general properties from its parent class and it has to define
only its unique
properties. This mechanism achieves code reusability.
For example, The company manufactures different versions of car but the car is
extended from its
previous version, so that new features will get added with original features
remain same. In
technical, java also has several classes which can be extended to add the new
functionality and
accesssing existing functionality.
2. Polymorphism:
Polymorphism means many forms where different actions are performed
though one interface. In
java polymorphism is achieved through overloading and overriding.
For example, If a dog smells cat it will bark and if a dog smells food, it salivates.
Here 'smelling' is
behaviour but whether to bark or salivate depends on type of parameter passed
like cat or food. It is
known as compile time polymorphism.
Another example, if a new car is replacing some functionality from exising car
then, it will be
dynamic polymorphism where existing functionality will get replaced with new
functionality and
by default, new functionality will get accessed.
1. Class:
A class is the collection of data members and member functions. It is a blue print
from which
objects can be constructed. It is just a logical construct. A class can contain fields
and methods to
describe the state and behaviour of an object respectively. Methods are the
members of a class that
provide a service for an object or perform some business logic. Current states of
a class’s
Corresponding object are stored in the object’s instance variables. Methods
define the operations that can be performed in python programming. Python is
case-sensitive language. That is Python fields and member functions names are
case sensitive.
class Person:
'''constructor'''
def __init__(self,name,age):
self.name=name
self.age=age
'''instantiate the person class'''
person1=Person("John",30)
person2=Person("Neha",35)
Constructor: Constructor is a special type of method(function) which is used to
initialise the instance members of the class. In python the __init__() method is
called the constructor and is always called when object is created.
Syntax of constructor declaration.
def __init__(self):
#body of constructor
2. Object:
Object is known as instance of class. Objects actually have their own states and
behavour. For
example Rectangle objects have their own length, breadth, area and perimeter.
Hence the length and
breadth are known as instance variables and methods area and perimeter are
known as instance
methods. Classes are just a logical construct but Objects are actually loaded into
memory. Object
are physically present.
1)default constructor: The default constructor is simple constructor which
doesn't accept any arguments. Its definition has only one argument which is
reference to the instance being constructed. i.e self The self parameter is a
reference to the class itself, and is used to access variables that belongs to the
class.
It does not have to be named self , you can call it whatever you like, but it has to
be the first parameter of any function in the class.
Example of default constructor:
class Person:
'''default constructor'''
def __init__(self):
self.name="JOHN"
def show(self):
print("name of Person is {}".format(self.name))
p=Person()
p.show()
output:
name of Person is john
2)Parametrized constructor: constructor with parameters is known as
parametrized constructor. The parametrized constructor The parametrized
constructor .The parametrized constructor take its first argument as a reference
to the instance being constructed known as self and the rest of the arguments
are provided by programmer.
Example of parametrized constructor:
class Person:
'''parameterized constructor'''
def __init__(self,name,age):
self.name=name
self.age=age
def show(self):
print("name of Person is {} and age of person is {}".format(self.name,self.age))
p=Person("john","30")
p.show()
output:
name of Person is john and age of person is 30
class Employee:
'''static variable'''
count=0;
'''costructor is created'''
def __init__(self,id,name,salary):
self.id=id
self.name=name
self.salary=salary
Employee.count+=1
'''method is created'''
def display(self):
print("Name ",self.id," name ",self.name," Salary",self.salary)
def displayCount(self):
print("Count ",Employee.count)
emp=Employee(101,"Ramesh",10000);
emp.display()
emp.displayCount()
emp1=Employee(102,"somesh",12000);
emp1.display()
emp1.displayCount()
Notes:.The variable count is a class variable whose value is shared among all
instances of a this class. This can be accessed as Employee.count from inside the
class or outside the class.
 The first method __init__() is a special method, which is called class
constructor or initialization method that Python calls when you create a
new instance of this class.
The self Parameter
The self parameter is a reference to the class itself, and is used to access
variables that belongs to the class.
It does not have to be named self , you can call it whatever you like, but it has to
be the first parameter of any function in the class:
Constructor OverLoading
class Emp:
def __init__(self,id=0,name=None,salary=0,):
if id!=0:
print("id ",id)
if name!=None:
print("name ",name)
if salary!=0:
print("salary ",salary)
e=Emp(101);
e1=Emp(102,"g")
e2=Emp(0,"k")
e3=Emp(0,None,10000)
o/p
id 101
id 102
name g
name k
salary 10000
''' mthod verLoading'''
class Emp:
def my(self,name=None,num=0):
self.name=name;
self.num=num;
def disname(self):
print("Name ",self.name)
def disNum(self):
print("Number ",self.num)
e=Emp()
e.my("h")
e.disname()
e1=Emp()
e1.my(None,101)
e1.disNum()
o/p
Name h
Number 101
Chaptar 4:
python variables and Methods
Types of variables
1)Instance variables:The variable which we defined inside the method and
constructor using self keyword called as instance variable. We can access
variable by using instance of class. Scope of instance variable is throughout the
class.
2)static variables: The variable which is defined out of the methods and
constructor called as static variable and we can access static variable by using
class name.The scope of static variable throghout the class.
3)Local variables:-variable which in defined in method and scope of variable is
within the method.
4)Global Variable:-Variable which is defined out of the class is called global
variable OR by using global keyword within method/constructor.
Example for instance variable:
class Employee:
def __init__(self,name,salary,age):
'''instance variable'''
self.name=name
self.salary=salary
self.age=age
def show(self):
#defining instance variable inside method
self.bonus=1000
def display(self):
print("Employee Bonus :",self.bonus)
e=Employee("John",10000,24)
print("Employee Name:",e.name)
print("Employee Salary:",e.salary)
print("Employee age:",e.age)
#we are calling to initialise instance variable
e.show()
e.display()
Eg for Static variables:
class Institute:
instituteName="Coder" # static variable
def __init__(self,stdId,stdName):
'''instance variable'''
self.stdId=stdId
self.stdName=stdName
i=Institute(101,"Rahul")
print("Institute Name:",Institute.instituteName)#calling static variables
print("Id :",i.stdId)# calling instance variables
print("Student Name:",i.stdName)
eg changing static variables value:
class Institute:
instituteName="Coder" # static variable
def __init__(self):
Institute.instituteName="coder technology"
def display(self):
stdId=10;# Local variable
print("Id ",stdId)
print("institute name =",Institute.instituteName)
i=Institute()
print("after changing the name of institute")
print(" changed institute name=",Institute.instituteName)
i.display()
o/p
institute name = Coder
after changing the name of institute
changed institute name = coder technology
Id 10
e.g. for Global variables
location="India" # defining globel variables
class Institute:
def display(self):
global branch # declaring globel variables
branch="vashi" # defining globel variables
print("inatitute name squad")
print("Location ",location )
print("Branch ",branch)
i=Institute()
location="India"
class Institute_branch:
def display(self):
branch="Pune" #defining globel variables
print("inatitute name coder")
print("Location ",location )
print("Branch ",branch)
i=Institute()
i.display()
i1=Institute_branch();
i1.display()
print(“Loction ”,location)#we can access globel variables directly
Types of Methods:-
1)instance Method
2)class method
3)static method
instance method:
class InstanceMetodDemo:
#we have to give static method decorator to declare method as static
def add(self,x,y):
print("Price ",x+y)
def product(self,x,y):
print("The Product",x*y)
def average(self,x,y):
print("The Average value:",(x+y)/2)
S=InstanceMetodDemo()
S.add(10,20)
S.product(10,20)
S.average(10,20)
Static Method Eg:
class StaticMetodDemo:
#we have to give staticmethod decorator to declare method as static
@staticmethod
def add(x,y):
print("Price ",x+y)
@staticmethod
def product(x,y):
print("The Product",x*y)
@staticmethod
def average(x,y):
print("The Average value:",(x+y)/2)
StaticMetodDemo.add(10,20)
StaticMetodDemo.product(10,20)
StaticMetodDemo.average(10,20)
ClassMethod Eg:
class Test:
num=10;
def display(self):
print("inside instance method")
print(Test.num)
print(self.num)
@staticmethod
def displayStatic():
print("inside staticmethod")
print(Test.num)
@classmethod
def displayClassMethod(cls):
print("inside @classmethod")
print(Test.num)
print(cls.num)
t=Test()
t.display()
Test.displayStatic()
Test.displayClassMethod()
Chapter 5:
Getter setter method:
class Employee:
#private variables are define like this
__empId=0
__empName=""
__empAge=""
__empSalary=0.0
def setEmpId(self,empId):
self.__empId=empId #accessing private variables
def setEmpName(self,empName):
self.__empName=empName
def setEmpAge(self,empAge):
self.__empAge=empAge
def setEmpSalary(self,empSalary):
self.__empSalary=empSalary
def getEmpId(self):
return self.__empId
def getEmpName(self):
return self.__empName
def getEmpSalary(self):
return self.__empSalary
def getEmpAge(self):
return self.__empAge
def toGetAllData(self):
return "Name ",self.__empName,"Id ",self.__empId,"Salary ",self.__empSalary
e=Employee()
e.setEmpId(101)
e.setEmpName("abc")
e.setEmpAge(25)
e.setEmpSalary(1000class Employee:
__empId=0
__empName=""
__empAge=""
__empSalary=0.0
def setEmpId(self,empId):
self.__empId=empId
def setEmpName(self,empName):
self.__empName=empName
def setEmpAge(self,empAge):
self.__empAge=empAge
def setEmpSalary(self,empSalary):
self.__empSalary=empSalary
def getEmpId(self):
return self.__empId
def getEmpName(self):
return self.__empName
def getEmpSalary(self):
return self.__empSalary
def getEmpAge(self):
return self.__empAge
def toGetAllData(self):
return "Name ",self.__empName,"Id ",self.__empId,"Salary ",self.__empSalary
e=Employee()
e.setEmpId(101)
e.setEmpName("abc")
e.setEmpAge(25)
e.setEmpSalary(1000)
print("Id =",e.getEmpId(),"Name=",e.getEmpName(),"
salary=",e.getEmpSalary()," Age =",e.getEmpAge())
print(e.toGetAllData())
)
print("Id =",e.getEmpId(),"Name=",e.getEmpName(),"
salary=",e.getEmpSalary()," Age =",e.getEmpAge())
print(e.toGetAllData())
Mini project using list
class Book:
__bookId=0;
__bookName=""
__price=0.0
__aname=""
def __init__(self,bookId,bookName,price,aname):
self.__bookId=bookId
self.__bookName=bookName
self.__price=price
self.__aname=aname
def setBookId(self,bookId):
self.__bookId=bookId
def setBookName(self,bookName):
self.__bookName=bookName
def setPrice(self,price):
self.__price=price
def setAname(self,aname):
self.__aname=aname
def getBookId(self):
return self.__bookId
def getBookName(self):
return self.__bookName
def getPrice(self):
return self.__price
def getAname(self):
return self.__aname
def getAllData(self):
return "Id ",self.__bookId,"Name ",self.__bookName," Price
",self.__price,"Author name ",self.__aname
from basicprograms.book import Book
class BookProject:
blist=[]
def excute(self,count):
if count==1:
bookId=int(input("Enter the id ="));
bookName=input("Enter the Name =");
price=float(input("Enter the price ="))
aname=input("Enter the author name =");
b=Book(bookId,bookName,price,aname)
self.blist.append(b)
if count == 2:
print('Food are as Follows')
for i in range(int(self.blist.__len__())):
if self.blist[i] != 'null':
print(self.blist[i].getBookId(), end=' ')
print(self.blist[i].getBookName(), end=' ')
print(self.blist[i].getPrice(), end=' ')
print(self.blist[i].getAname(), end=' ')
print()
if c == 3:
n = int(input('Enter the book id which you want to update'));
for i in range(int(self.blist.__len__())):
if self.blist[i].getBookId() == n:
bname = input('Enter the new Bookname : ')
aname = input('Enter the new author name : ')
price = float(input('Enter the new price : '))
self.blist[i].setBookName(bname);
self.blist[i].setAname(aname);
self.blist[i].setPrice(price);
if c == 4:
n = int(input('Enter the book id which you want to delete'));
for i in range(int(self.blist.__len__())):
if self.blist[i].getBookId() == n:
self.blist[i]='null'
if c == 5:
n = int(input('Enter the book id which you want to search'));
for i in range(int(self.blist.__len__())):
if self.blist[i].getBookId() == n:
print(self.blist[i].getAllData())
while(True):
print('Enter your choice')
print('1.addFood')
print('2.displayFood')
print('3.updateFood')
print('4.deleteFood')
print('5.searchFood')
c = int(input('Enter the selected choice : '))
ff = BookProject()
ff.excute(c)
Chapter 6: Module
A module allows you to logically organize your Python code. Grouping related
code into a module makes the code easier to understand and use.
Simply, a module is a file consisting of Python code. A module can define
functions, classes and variables. A module can also include runnable code.
You can use any Python source file as a module by executing an import
statement in some other Python source file.
The import has the following syntax:
import module1[, module2[,... moduleN]
When the interpreter encounters an import statement, it imports the module if
the module is present in the search path. A search path is a list of directories that
the interpreter searches before importing a module. For example, to import the
module demo.py, you need to put the following command at the top of the script.
import demo
demo.hello()
A module is loaded only once, regardless of the number of times it is imported.
For example, to import the function helloworld from the module demo, use the
following statement
from demo import helloworld
helloworld()
The from...import * Statement
It is also possible to import all names from a module into the current namespace by using the
following import statement −
It is also possible to import all names from a module into the current namespace by using the
following import statement
from modname import *
This provides an easy way to import all the items from a module into the current
namespace; however, this statement should be used sparingly.
Locating Modules
When you import a module, the Python interpreter searches for the module in
the following sequences −
 The current directory.
 If the module isn't found, Python then searches each directory in the shell
variable PYTHONPATH.
 If all else fails, Python checks the default path. On UNIX, this default path is
normally /usr/local/lib/python/.
The module search path is stored in the system module sys as the sys.path
variable.
Chaptar 7: Inheritance
Inheritance is the capability of one class to derive or inherit the properties from
some another class. The benefits of inheritance are:
1. It represents real-world relationships well.
2. It provides reusability of a code. We don’t have to write the same code
again and again. Also, it allows us to add more features to a class without
modifying it.
3. It is transitive in nature, which means that if class B inherits from another
class A, then all the subclasses of B would automatically inherit from class
A.
In inheritance, the child class acquires the properties and can access all
the data members and functions defined in the parent class. A child class
can also provide its specific implementation to the functions of the parent
class
syntax:
class derived-class(base class):
#code
What is object class?
In Python object is root of all classes.
1)single inheritance:
When a child class inherits from only one parent class,
it is called as single inheritance.
Example:
class Person:
def __init__(self,name,age):
self.name=name
self.age=age
def show(self):
print("name of Person is {} and age of person is {}".format(self.name,self.age))
class Student(Person):
def __init__(self,marks,name,age):
self.marks=marks
self.name=name
self.age=age
def show(self):
print("Name of student is {} age of student is {} marks of student is
{}".format(self.name,self.age,self.marks))
s=Student(78,"john",21)
s.show()
output:
Name of student is john age of student is 21 marks of student is 78
2)Multiple inheritance:-When a child class inherits from multiple parent
classes, it is called as multiple inheritance. Python supports multiple inheritance.
We specify all parent classes as comma separated list in bracket.
Example:-
'''first base class'''
class Development():
'''constructor of Development '''
def __init__(self):
print("I am in Development")
def show(self):
print("Development")
'''second base class'''
class Testing():
'''constructor of Testing '''
def __init__(self):
print("I am in Testing")
def show(self):
print("Testing")
'''Multiple inheritance'''
class Project(Development,Testing):
'''constructor of Project'''
def __init__(self):
print("I am in project")
p=Project()
p.show()
Output:
I am in project
Development
'''first base class'''
class Development():
'''constructor of Development '''
def __init__(self):
print("I am in Development")
def show(self):
print("Development")
'''second base class'''
class Testing():
'''constructor of Testing '''
def __init__(self):
print("I am in Testing")
def show(self):
print("Testing")
'''Multiple inheritance'''
class Project(Development,Testing):
'''constructor of Project'''
def __init__(self):
print("I am in project")
'''super() lets you avoid referring to the base class explicitly'''
super().__init__()
p=Project()
p.show()
output:
I am in project
I am in Development
Development
Super:
super() lets you avoid referring to the base class explicitly. you can use super
to call base class method.
'''first base class'''
class Development():
'''constructor of Development '''
def __init__(self):
print("I am in Development")
def show(self):
print("Development")
'''second base class'''
class Testing():
'''constructor of Testing '''
def __init__(self):
print("I am in Testing")
def show(self):
print("Testing")
'''Multiple inheritance'''
class Project(Development,Testing):
'''constructor of Project'''
def __init__(self):
print("I am in project")
Development.__init__()
Testing.__init__()
Output:
I am in project
I am in Development
I am in Testing
Development
In above example we have created class Project which has two base classes
Development and Testing you want call __init__() method from
Development and __init__() method from Testing also then We have to give
Development.__init__()
Testing.__init__()
Multilevel Inheritance:
Multi-level inheritance is archived when a derived class inherits another derived
class.
Example:
class Person:
def __init__(self,name,age):
self.name=name
self.age=age
def show(self):
print("name of Person is {} and age of person is {}".format(self.name,self.age))
class Employee(Person):
def __init__(self,name,age,salary):
self.salary=salary
super().__init__(name, age)
def show(self):
print("Name of Employee is {} age of Employee is {} salary of Employee is
{}".format(self.name,self.age,self.salary))
class Manager(Employee):
def __init__(self,name,age,salary,bonus):
self.bonus=bonus
super().__init__(name,age,salary)
def show(self):
print("Name of Employee is {} age of Employee is {} salary of Employee is {}
Bonus is {}".format(self.name,self.age,self.salary,self.bonus))
s=Manager("John",28,20000,2000)
s.show()
Output:
Name of Employee is John age of Employee is 28 salary of Employee is
20000 Bonus is 2000
Hybrid Inheritance: This form combines more than one form of inheritance.
Basically, it is a blend of more than one type of inheritance
class Company():
def __init__(self,req):
print("I am in company")
def _show(self):
print("Company")
class Development(Company):
def __init__(self):
print("I am in Development")
def show(self):
print("Development")
class Testing(Company):
def __init__(self):
print("I am in Testing")
def show(self):
print("Testing")
class Project(Development,Testing):
def __init__(self):
print("I am in Project")
#To get the method resolution order
print(Project.__mro__)
Output:
(<class '__main__.Project'>, <class '__main__.Development'>, <class
'__main__.Testing'>, <class '__main__.Company'>, <class 'object'>)
To get the method resolution order of a class we can use either __mro__
attribute or mro() method. By using these methods we can display the
order in which methods are resolved.
class Company():
def __init__(self):
print("I am in company")
def _show(self):
print("Company")
class Development(Company):
def __init__(self):
print("I am in Development")
super().__init__()
def show(self):
print("Development")
class Testing(Company):
def __init__(self):
print("I am in Testing")
super().__init__()
def show(self):
print("Testing")
class Project(Development,Testing):
def __init__(self):
print("I am in Project")
super().__init__()
p=Project()
p.show()
#To get the method resolution order
print(Project.__mro__)
Method Overriding: Method overriding is concept of object oriented
programming that allows us to change the implementation of function in the
child class that is defined in the parent class.
Following conditions must be met for overriding a function:
1. Inheritance should be there. Function overriding cannot be done within a
class. We need to derive a child class from a parent class.
2. The function that is redefined in the child class should have the same
signature as in the parent class i.e. same number of parameters.
Example:
class Tv:
def show(self):
print("TV")
class Lcd_Tv:
def show(self):
print("LCD_TV")
tv=Lcd_Tv()
tv.show()
Output:
LCD_TV
Has-A-Relationship
class Engin:
def setEnginNo(self,engNo):
self.engNo=engNo
def setEnginModel(self,engModel):
self.engModel=engModel
def getEnginNo(self):
return self.engNo
def getEnginModel(self):
return self.engModel
class Car:
def setEngin(self,eng):
self.eng=eng
def setCarName(self,carName):
self.carName=carName
def setCarPrice(self,carPrice):
self.carPrice=carPrice
def getEngin(self):
return self.eng
def getCarName(self):
return self.carName
def getCarPrice(self):
return self.carPrice
e=Engin()
e.setEnginModel("#1234#")
e.setEnginNo("A12345g")
c=Car()
c.setCarName("Marythi")
c.setCarPrice(100000)
c.setEngin(e)
print("Car Name ",c.getCarName())
print("Car price ",c.getCarPrice())
print("Engin No",c.getEngin().getEnginNo())
print("Engin Model ",c.getEngin().getEnginModel())
Inner classes:
class College:
class Departmet:
def display(self):
print("Science department")
c=College()
d=c.Departmet()
d.display()
Core Python.doc
chapter 8
Python – Strings
In Python, Strings are arrays of bytes representing Unicode characters.
However, Python does not have a character data type, a single character is
simply a string with a length of 1. Square brackets can be used to access
elements of the string.
Creating a String
Strings in Python can be created using single quotes or double quotes or even
triple quotes.
String in single quotes cannot hold any other single quoted character in it
otherwise an error arises because the compiler won’t recognize where to start
and end the string. To overcome this error, use of double quotes is preferred,
because it helps in creation of Strings with single quotes in them. For strings
which contain Double quoted words in them, use of triple quotes is suggested.
Along with this, triple quotes also allow the creation of multiline strings.
# Python Program for
# Creation of String
# with single Quotes
str1 = 'Welcome to the Coder Technologies'
print("String with the use of Single Quotes: ")
print(str1)
# Creating a String
# with double Quotes
str2 = "I'm learning python"
print("nString with the use of Double Quotes: ")
print(str2)
# Creating a String
# with triple Quotes
str3 = '''I'm learning python. and I Love "Python Programming"'''
print("nString with the use of Triple Quotes: ")
print(str3)
# Creating String with triple
# Quotes allows multiple lines
str4 = '''hi
how are you?
I'm fine! '''
print("nCreating a multiline String: ")
print(str4)
Access characters in a string
We can access individual characters using indexing and a range of characters
using slicing. Index starts from 0. Trying to access a character out of index range
will raise an IndexError. The index must be an integer. We can't use float or
other types, this will result into TypeError.
Python allows negative indexing for its sequences.
The index of -1 refers to the last item, -2 to the second last item and so on. We
can access a range of items in a string by using the slicing operator (colon).
str = 'Coder Technologies'
print('str = ', str)
#first character
print('str[0] = ', str[0])
#last character
print('str[-1] = ', str[-1])
#slicing 2nd to 5th character
print('str[1:5] = ', str[1:5])
#slicing 6th to 2nd last character
print('str[5:-2] = ', str[5:-2])
Output:
str = Coder Technologies
str[0] = C
str[-1] = s
str[1:5] = oder
str[5:-2] = Technologi
String Operations
Concatenation of Two or More Strings
Joining of two or more strings into a single one is called concatenation.
The + operator does this in Python. Simply writing two string literals together
also concatenates them.
The * operator can be used to repeat the string for a given number of times.
str1 = 'Coder'
str2 ='Technologies'
# using +
print('str1 + str2 = ', str1 + str2)
# using *
print('str1 * 3 =', str1 * 3)
Output:
str1 + str2 = CoderTechnologies
str1 * 3 = CoderCoderCoder
Iterating Through String
Using for loop we can iterate through a string. Here is an example to count the
number of 'o' in a string.
count = 0
for letter in 'Coder Technologies':
if(letter == 'o'):
count += 1
print(count,'letters found')
Output:
3 letters found
Built-in functions to Work with Python
Various built-in functions that work with sequence, works with string as well.
Some of the commonly used ones are enumerate() and len().
The enumerate() function returns an enumerate object. It contains the index
and value of all the items in the string as pairs. This can be useful for iteration.
Similarly, len() returns the length (number of characters) of the string.
str = 'Coder Technologies'
# enumerate()
list_enumerate = list(enumerate(str))
print('list(enumerate(str) = ', list_enumerate)
#character count
print('len(str) = ', len(str))
Output:
list(enumerate(str) = [(0,'c'),(1,'o'),(2,'d'),(3,'e'),(4,'r')]
len(str) = 5
Formatting of Strings
Strings in Python can be formatted with the use of format() method which is
very versatile and powerful tool for formatting of Strings. Format method in
String contains curly braces {} as placeholders which can hold arguments
according to position or keyword to specify the order.
A string can be left(<), right(>) or center(^) justified with the use of format
specifiers, separated by colon(:). Integers such as Binary, hexadecimal, etc. and
floats can be rounded or displayed in the exponent form with the use of format
specifiers.
'''
Created on 14-May-2019
@author: trainerdemo
'''
#Python Program for
# Formatting of Strings
# Default order
String1 = "{} {} {} {}".format('Coder', 'Technologies',"At",'Andheri')
print("Print String in default order: ")
print(String1)
# Positional Formatting
String1 = "{2} {3} {0} {1}".format('Coder', 'Technologies',"At",'Andheri')
print("nPrint String in Positional order: ")
print(String1)
# Keyword Formatting
String1 = "{a} {b} {c}".format(a = 'The', b = 'Coder', c = 'Technologies')
print("nPrint String in order of Keywords: ")
print(String1)
# Formatting of Integers
String1 = "{0:b}".format(16)
print("nBinary representation of 16 is ")
print(String1)
# Formatting of Floats
String1 = "{0:e}".format(165.6458)
print("nExponent representation of 165.6458 is ")
print(String1)
# Rounding off Integers
String1 = "{0:.2f}".format(1/6)
print("none-sixth is : ")
print(String1)
# String alignment
String1 = "|{:<10}|{:^10}|{:>10}|".format('I','am ','learning python ')
print("nLeft, center and right alignment with Formatting: ")
print(String1)
Output:
Print String in default order:
Coder Technologies At Andheri
Print String in Positional order:
At Andheri Coder Technologies
Print String in order of Keywords:
The Coder Technologies
Binary representation of 16 is
10000
Exponent representation of 165.6458 is
1.656458e+02
one-sixth is :
0.00
Left, center and right alignment with Formatting:
|I | am |learning python |
Some Method of string with Example:
str = 'Coder Technologies'
# length of String
print("Length is ",len(str))
# convert string in lower case
print(" In lower case ",str.lower())
# Covert string in upper case
print(" In upper case ",str.upper())
#replace string by other string
print(" replace method ",str.replace("o", "O"))
#split string in sub string by space
print("split method ",str.split(" "))
Output:
In lower case coder technologies
In upper case CODER TECHNOLOGIES
replace method COder TechnOlOgies
split method ['Coder', 'Technologies']
String constants
Built-In
Function
Description
string.ascii_lett
ers
Concatenation of the ascii_lowercase and ascii_uppercase
constants.
string.ascii_low
ercase
Concatenation of lowercase letters
string.ascii_upp
ercase
Concatenation of uppercase letters
string.digits Digit in strings
string.hexdigits Hexadigit in strings
string.letters concatenation of the strings lowercase and uppercase
string.lowercas
e
A string must contain lowercase letters.
string.octdigits Octadigit in a string
string.punctuati
on
ASCII characters having punctuation characters.
string.printable String of characters which are printable
String.endswith
()
Returns True if a string ends with the given suffix
otherwise returns False
String.startswit
h()
Returns True if a string starts with the given prefix
otherwise returns False
String.isdigit()
Returns “True” if all characters in the string are digits,
Otherwise, It returns “False”.
String.isalpha()
Returns “True” if all characters in the string are alphabets,
Otherwise, It returns “False”.
string.isdecimal
()
Returns true if all characters in a string are decimal.
str.format()
one of the string formatting methods in Python3, which
allows multiple substitutions and value formatting.
String.index
Returns the position of the first occurrence of substring in
a string
string.uppercas
e
A string must contain uppercase letters.
string.whitespa
ce
A string containing all characters that are considered
whitespace.
string.swapcase
()
Method converts all uppercase characters to lowercase
and vice versa of the given string, and returns it
replace()
returns a copy of the string where all occurrences of a
substring is replaced with another substring
Chapter 9
Lambda Function:
In Python, anonymous function means that a function is without a name. we
already know that def keyword is used to define the normal functions and the
lambda keyword is used to create anonymous functions. It has the following
syntax:
lambda arguments: expression
 This function can have any number of arguments but only one expression,
which is evaluated and returned.
 One is free to use lambda functions wherever function objects are
required.
Let’s look at this example and try to understand the difference between a
normal def defined function and lambda function. This is a program that
returns the cube of a given value:
# Python code to illustrate cube of a number
# showing difference between def() and lambda().
def cube(y):
return y*y*y;
g = lambda x: x*x*x
print(g(7))
print(cube(5))
Without using Lambda : Here, both of them returns the cube of a given
number. But, while using def, we needed to define a function with a name cube
and needed to pass a value to it. After execution, we also needed to return the
result from where the function was called using the return keyword.
Using Lambda : Lambda definition does not include a “return” statement, it
always contains an expression which is returned. We can also put a lambda
definition anywhere a function is expected, and we don’t have to assign it to a
variable at all. This is the simplicity of lambda functions.
Need of Lambda function:
The power of lambda is better shown when you use them as an anonymous
function inside another function.
Say you have a function definition that takes one argument, and that argument
will be multiplied with an unknown number.
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
Lambda functions can be used along with built-in functions like filter(), map()
and reduce().
Filter:-The filter() function in Python takes a function and a list as arguments.it
returns new list.
Without using Lambdas
ages = [5,19,12,24,50,20]
def myFunc(x):
if x < 18:
return False
else:
return True
adults = filter(myFunc,ages)
for i in adults:
print(i)
# Python code to illustrate
# filter() with lambda()
li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]
final_list = list(filter(lambda x: (x%2 != 0) , li))
print(final_list)
Output:
[5, 7, 97, 77, 23, 73, 61]
map
The map() function in Python takes a function and a list as argument. The
function is called with a lambda function and a list and a new list is returned
which contains all the lambda modified items returned by that function for each
item. Example:
# Python code to illustrate
# map() with lambda()
# to get double of a list.
li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]
final_list = list(map(lambda x: x*2 , li))
print(final_list)
Output:
[10, 14, 44, 194, 108, 124, 154, 46, 146, 122]
reduce()
The reduce() function in Python takes a function and a list as argument. The
function is called with a lambda function and a list of new reduced result is
returned. This performs a repetitive operation over the pairs of the list.
# Python code to illustrate
# reduce() with lambda()
# to get sum of a list
from functools import reduce
li = [5, 8, 10, 20, 50, 100]
sum = reduce((lambda x, y: x + y), li)
print (sum)
Output:
193
List comprehesion
List comprehensions are used for creating new list from another iterables. As
list comprehension returns list, they consists of brackets containing the
expression which needs to be executed for each element along with the for loop
to iterate over each element.
Syntax
The list comprehension starts with a ’[’ and ’]’ to help you remember that the
result is going to be a list.
The base syntax is
[expression for item in list if conditional]
This is equivalent to:
for item in list:
if condition:
expression
Lets Break down and what it does
new_list=[expression(i) for i in old_list if filter(i)]
new_list
The new list(result)
expression(i)
Expression is based on the variable used for each element in the old_list.
For i in old_list:
it is nothing but iterate trugh list
if filter(i)
Apply a filter with an if -statement.
range
The range() function returns a sequence of numbers, starting from 0 by default,
and increments by 1 (by default), and ends at a specified number.
x = range(6)
for n in x:
print(n)
Syntax
range(start, stop, step)
star
t
Optional. An integer number specifying at which position to
start. Default is 0
sto
p
Optional. An integer number specifying at which
position to end.
ste
p
Optional. An integer number specifying the
incrementation. Default is 1
e.g:
x = range(3, 6)
for n in x:
print(n)
e.g:
x = range(3, 20, 2)
for n in x:
print(n)
output:
3
5
7
9
11
13
15
17
19
Chapter 10
Exception Handling
Python provides two very important features to handle any unexpected error in
your
Python programs and to add debugging capabilities in them
1)Exception Handling.
Standard Exception
Exception:Base class for all exceptions.
StopIteration:Raised when the next() method of an iterator does not point to
any object.
SystemExit:Raised by the sys.exit() function.
StandardError :Base class for all built-in exceptions except StopIteration and
SystemExit.
ArithmeticError: Base class for all errors that occur for numeric calculation.
OverflowError Raised when a calculation exceeds maximum limit for a
numeric
FloatingPointError:- Raised when a floating point calculation fails.
ZeroDivisonError:- Raised when division or modulo by zero takes place for all
numeric types.
AssertionError:- Raised in case of failure of the Assert statement.
AttributeError Raised in case of failure of attribute reference or assignment.
EOFError: Raised when there is no input from either the raw_input() or
input() function and the end of file is reached.
importError Raised when an import statement fails.
KeyboardInterrupt Raised when the user interrupts program execution,
usually by
pressing Ctrl+c.
LookupError Base class for all lookup errors.
IndexError Raised when an index is not found in a sequence.
KeyError Raised when the specified key is not found in the dictionary.
NameError Raised when an identifier is not found in the local or global
namespace.
UnboundLocalError Raised when trying to access a local variable in a function
or
method but no value has been assigned to it.
EnvironmentError Base class for all exceptions that occur outside the Python
environment.
IOError Raised when an input/ output operation fails, such as the print
statement or the open() function when trying to open a file that
does not exist.
OSError Raised for operating system-related errors.
SyntaxError Raised when there is an error in Python syntax.
IndentationError Raised when indentation is not specified properly.
SystemError Raised when the interpreter finds an internal problem, but when
this error is encountered the Python interpreter does not exit.
SystemExit Raised when Python interpreter is quit by using the sys.exit()
function. If not handled in the code, causes the interpreter to
exit.
Exception:
An exception is an event, which occurs during the execution of a program that
disrupts
the normal flow of the program's instructions.
If you have some suspicious code that may raise an exception, you can defend
your
program by placing the suspicious code in a try: block. After the try: block,
include
an except: statement, followed by a block of code which handles the problem as
elegantly
as possible.
Syntax:
try:
You do your operations here
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
e.g:
# Python program to handle simple runtime error
a = [1, 2, 3]
try:
print("Second element = %d" %(a[1]))
# Throws error since there are only 3 elements in array
print("Fourth element = %d" %(a[3]))
except IndexError:
print("An error occurred")
output:
Second element = 2
An error occurred
Here are few important points about the above-mentioned syntax-
1)A single try statement can have multiple except statements. This is useful
when
the try block contains statements that may throw different types of exceptions.
2)You can also provide a generic except clause, which handles any exception.
3)After the except clause(s), you can include an else-clause. The code in the
else-
block executes if the code in the try: block does not raise an exception.
4)The else-block is a good place for code that does not need the try: block's
protection.
The except Clause with No Exceptions
You can also use the except statement with no exceptions defined as
follows-
try:
You do your operations here
......................
except:
If there is any exception, then execute this block.
......................
else:
If there is no exception then execute this block.
This kind of a try-except statement catches all the exceptions that occur. Using
this kind
of try-except statement is not considered a good programming practice though,
because
it catches all exceptions but does not make the programmer identify the root
cause of the
problem that may occur.
Example:
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print ("Error: can't find file or read data")
else:
print ("Written content in the file successfully")
fh.close()
Output:-
Written content in the file successfully
Example:
try:
fh = open("testfile", "r")
fh.write("This is my test file for exception handling!!")
except IOError:
print ("Error: can't find file or read data")
else:
print ("Written content in the file successfully")
Output:
Error: can't find file or read data
The except Clause with Multiple Exceptions
You can also use the same except statement to handle multiple exceptions as
follows-
try:
You do your operations here
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list,
then execute this block.
......................
else:
If there is no exception then execute this block.
Example:
# Program to handle multiple errors with one except statement
try :
a = 3
if a < 4 :
# throws ZeroDivisionError for a = 3
b = a/(a-3)
# throws NameError if a >= 4
print("Value of b = ", b)
# note that braces () are necessary here for multiple exceptions
except(ZeroDivisionError, NameError):
print("nError Occurred and Handled")
Output:
Error Occurred and Handled
The try-finally Clause
You can use a finally: block along with a try: block. The finally: block is a place to
put
any code that must execute, whether the try-block raised an exception or not.
The syntax
of the try-finally statement is this-
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
Example:
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
finally:
print ("Error: can't find file or read data")
fh.close()
Output:
Error: can't find file or read data
Argument of an Exception
An exception can have an argument, which is a value that gives additional
information
about the problem. The contents of the argument vary by exception. You capture
an
exception's argument by supplying a variable in the except clause as follows-
try:
You do your operations here
......................
except ExceptionType as Argument:
You can print value of Argument here...
Example:
# Define a function here.
def temp_convert(var):
try:
return int(var)
except ValueError as Argument:
print ("The argument does not contain numbersn", Argument)
# Call above function here.
temp_convert("xyz")
Output:
The argument does not contain numbers
invalid literal for int() with base 10: 'xyz'
User defined exception:
Python also allows you to create your own exceptions by deriving classes from
the standard built-in exceptions.
Example:
class MyError(Exception):
# Constructor or Initializer
def __init__(self, value):
self.value = value
# __str__ is to print() the value
def __str__(self):
return(repr(self.value))
try:
raise(MyError(3*2))
# Value of Exception is stored in error
except MyError as error:
print('A New Exception occured: ',error.value)
Output:
A New Exception occured: 6
The raise statement allows the programmer to force a specific exception to
occur.
Chapter 11
Multithreading
1. Multithreading Concept:
Multithreading is a specialised form of multitasking. Multithreaded program
contains two or more parts are running concurrently. Each part is known as
thread.
2. Python Thread Model:
Process Thread
Program in execution Part of a process
Heavyweight Lightweight
Each process has its own address space Threads shares the address space
Multiprocessing: More overhead Multithreading: Less overhead
Interprocess communication is expensive Inter thread communication is less expensive
Context switching requires high cost Context switching requires low cost
Example: downloading files along with
listening
music
Example: in editor, character printing along
with formatting
3. Thread States:
1. New
A thread is said to be in new state when we created the thread instance, but we
have not yet called start() on the thread newly created thread instance. Even
though it is a live thread object, it is not a thread of execution. At this state,
thread is not active.
2. Runnable / Ready
In the Runnable state a thread is eligible to run, however the Thread Scheduler
not selects the thread to start its execution. A thread will get into Runnable state
after we call start() method. Also a thread can come back to Runnable state from
other states like sleeping, waiting or blocked states. The important point to
remember is that, once we call start() method on any thread instance, the thread
will move to Runnable state which makes the thread eligible to run. The Thread
Scheduler may ormay not have picked the thread to run.
3. Running
Once the Thread Scheduler selects a thread to run from the runnable thread
pool, the thread starts execution. This is the state we call a thread is in Running
state and thread becomes thread of execution.
4. Waiting
If any thread is waiting for any shared resource then it will call wait method. It
will come out of wait when either timer expires or it will get notification by
some other thread.
5. Sleeping
Thread can go to sleep state if its execution is paused for some period by calling
sleep method.
6. Blocked:
Thread will go to blocked state if is waiting for I/O. e.g. User Input. When I/O get
completed, it will come out of this state and goes to ready state.
7. Suspended
If thread is suspended for some period then it will go to suspended state. It will
come out of this state when it gets resumed or timer expires.
From all these states the thread becomes eligible to run again, however Thread
Scheduler ultimately decides which runnable thread becomes thread of
execution.
8. Dead
A thread is considered dead once its run() method completed execution.
Although a thread’s run() method completed execution it is still a Thread object,
but this Thread object is not a thread of execution. Once the thread completes its
run() method and dead, it cannot be brought back to thread of execution or even
to runnable state. Invoking start() method on a dead thread causes runtime
exception.
A thread is not eligible to run if it is in waiting, sleeping or blocked state. But the
thread is alive,and it is not in runnable state. A thread can transition back to
runnable state when particular event occurs.
Create the thread with out using any class
Methods
1)current_thread:− Returns the number of thread objects in the caller's thread
control.
2)setName() − The setName() method sets the name of a thread.
3)getName() − The getName() method returns the name of a thread.
4)start():-The start() method starts a thread by calling the run method.
5)run() − The run() method is the entry point for a thread.
6)join([time]) − The join() waits for threads to terminate.
7)sleep():-The method sleep() suspends execution for the given number of
seconds
1)Creating thread without class
from threading import *
def display():
print("child thread")
t=Thread(target=display)
t.start()
o/p
child thread
2)Current_thread
from threading import *
def display():
print("child thread")
print(current_thread().getName())#this mthoe is use to get current thread
information
t=Thread(target=display)
t.setName("abc")
t.start()
3)
from threading import *
import time
def display():
for i in range(5):
print("child thread")
print(current_thread().getName())#this mthoe is use to get current thread
information
time.sleep(1)
t=Thread(target=display)
t.setName("abc")
t.start()
Creating thread by extending Thread class
4)
from threading import *
import time
class Mythread(Thread):
def run(self):
for i in range(5):
print("child thread")
print(current_thread().getName())#this mthoe is use to get current thread
information
time.sleep(1)
m=Mythread()
m.setName("Ramesh")
m.start()
5)
class Mythread(Thread):
def run(self):
for i in range(5):
print("child thread")
print(current_thread().getName())#this mthoe is use to get current thread
information
time.sleep(1)
m=Mythread()
m.setName("Ramesh")
m.start()
m=Mythread()
m.setName("sameer")
m.start()
o/p
child thread
Ramesh
child thread
sameer
child thread
Ramesh
child thread
sameer
child thread
Ramesh
child thread
sameer
child thread
Ramesh
child thread
sameer
child thread
Ramesh
child thread
sameer
join Method eg:
6)
from threading import *
import time
class Mythread(Thread):
def run(self):
for i in range(5):
print("child thread")
print(current_thread().getName())#this mthoe is use to get current thread
information
time.sleep(1)
m=Mythread()
m.setName("Ramesh")
m.start()
m.join()
m=Mythread()
m.setName("sameer")
m.start()
m.join()
child thread
Ramesh
child thread
Ramesh
child thread
Ramesh
child thread
Ramesh
child thread
Ramesh
child thread
sameer
child thread
sameer
child thread
sameer
child thread
sameer
child thread
sameer
7)creating thread without extending thread class
class Mythread:
def m(self):
for i in range(5):
print("child thread")
print(current_thread().getName())#this mthoe is use to get current thread
information
time.sleep(1)
mythread=Mythread()
t=Thread(target=mythread.m)
t.setName("Ramesh")
t.start()
mythread1=Mythread()
t1=Thread(target=mythread1.m)
t1.setName("Ramesh")
t1.start()
o/p
child thread
Rameshaccording to Objects.equals(Object, Object).
child thread
Seetha
child thread
Ramesh
child thread
Seetha
child thread
Ramesh
child thread
Seetha
child thread
Ramesh
child thread
Seetha
child thread
Ramesh
child thread
Seetha
Chapter 12
File Handling
what is file?
Suppose you have stored data in dictionary
d={}
d[‘name’]=”python”
After execution of program data is lost means this is temporary storage suppose
you want to store data permanently Then use File.File is used to store small
amount of data permanently.
Their are two types of file:
1)Text file
2)Binary File
1)Text file:-Text file is used to store character data.e.g abc.txt
2)Binary file:- To store binary data.e.g.Images, videos,audio ,zip files clips these
are Binary File.
Need of File :-file handling and allows users to handle files i.e., to read and write
files, along with many other file handling options, to operate on files.
open()-Open is inbuilt function used to open file
syntax:
open(filepath,file_mode)
e.g
open(“file.txt”,’r’)
The allowed values of mode for text file are:
r:-Opens a file for reading only. The file pointer is placed at the beginning of the
file. This is the default mode.
W:-Opens a file for writing only. Overwrites the file if the file exists. If the file
does not exist, creates a new file for writing.
a:-Opens a file for appending. The file pointer is at the end of the file if the file
exists. That is, the file is in the append mode. If the file does not exist, it creates a
new file for writing.
r+: -Opens a file for both reading and writing. The file pointer placed at the
beginning of the file.
w+-Opens a file for both writing and reading. Overwrites the existing file if the
file exists. If the file does not exist, creates a new file for reading and writing.
a+:-Opens a file for both appending and reading. The file pointer is at the end of
the file if the file exists. The file opens in the append mode. If the file does not
exist, it creates a new file for reading and writing.
The allowed values of mode for binary file are:
rb:-Opens a file for reading only in binary format. The file pointer is placed at the
beginning of the file. This is the default mode
wb:-Opens a file for writing only in binary format. Overwrites the file if the file
exists. If the file does not exist, creates a new file for writing.
rb+:-Opens a file for both reading and writing in binary format. The file pointer
placed at the beginning of the file.
Wb+:-Opens a file for both writing and reading in binary format. Overwrites the
existing file if the file exists. If the file does not exist, creates a new file for
reading and writing.
ab:-Opens a file for appending in binary format. The file pointer is at the end of
the file if the file exists. That is, the file is in the append mode. If the file does not
exist, it creates a new file for writing.
ab+:-Opens a file for both appending and reading in binary format. The file
pointer is at the end of the file if the file exists. The file opens in the append
mode. If the file does not exist, it creates a new file for reading and writing.
File Atribute:
Once a file is opened and you have one file object, you can get various
information related to that file.
Here is a list of all attributes related to file object −
1)file.closed
Returns true if file is closed, false otherwise.
2)file.mode
Returns access mode with which file was opened.
3)file.name
Returns name of the file.
Example:
fo = open("foo.txt", "wb")
print("Name of the file: ",fo.name)
print("Closed or not : ", fo.closed)
print("Opening mode : ", fo.mode)
Output:
Name of the file: foo.txt
Closed or not : False
Opening mode : wb
Name of the file: foo.txt
Closed or not : False
Opening mode : wb
Close:-
The close() method of a file object flushes any unwritten information and
closes the file object, after which no more writing can be done.
Python automatically closes a file when the reference object of a file is
reassigned to another file. It is a good practice to use the close() method to close
a file.
1)r -read mode example
Example:
f=open("file.txt","r")
data=f.read()
print(data)
f.close()fo = open("foo.txt", "r+")
data = fo.read(10);
print("Read String is : ", data)
# Close opend file
fo.close()
Output:
hello world
File handling
2)w-write mode example
f=open("file.txt","w")
data=f.write("line1")
3)r+:-
fo = open("file.txt", "r+")
data = fo.read(11);
print("Read String is : ", data)
# Close opend file
fo.close()
output:-
Read String is : hello world
4)w+:-
fo = open("file.txt", "w+")
data = fo.read(11);
print("Read String is : ", data)
# Close opend file
fo.close()
Output:-
Read String is :
5)a:-append mode
fo = open("file.txt", "a")
fo.write("welcome")
# Close opend file
fo.close()
6)a+:-
fo = open("file.txt", "a+")
fo.write("welcome")
data=fo.read(30)
print(data)
# Close opend file
fo.close()
f.readline()-The method readline()reads one entire line from the file.
Example:-
fo = open("file.txt", "r+")
data=fo.readline()
print(data)
data=fo.readline()
print(data)
data=fo.readline()
print(data)
data=fo.readline()
print(data)
data=fo.readline()
print(data)
# Close opend file
fo.close()
Output:-
line1
line2
line3
line4
line5
f.readlines()-The method readlines() reads until EOF using readline() and
returns a list containing the lines. .
fo = open("file.txt", "r+")
data=fo.readlines()
print(data)
# Close opend file
fo.close()
Output:-
['line1n', 'line2n', 'line3n', 'line4n', 'line5n']
File Positions:
The tell() method tells you the current position within the file; in other words,
the next read or write will occur at that many bytes from the beginning of the
file.
The seek(offset[, from]) method changes the current file position. The offset
argument indicates the number of bytes to be moved. The from argument
specifies the reference position from where the bytes are to be moved.
If from is set to 0, it means use the beginning of the file as the reference position
and 1 means use the current position as the reference position and if it is set to 2
then the end of the file would be taken as the reference position.
Example:
fo = open("foo.txt", "r+")
st = fo.read(10);
print("Read String is : ", st)
# Check current position
position = fo.tell();
print("Current file position : ", position)
# Reposition pointer at the beginning once again
position = fo.seek(0, 0);
st = fo.read(10);
print("Again read String is : ", st)
# Close opend file
fo.close()
Output:
Read String is : python is
Current file position : 9
Again read String is : python is
Finding file path , directory name
import os
print(“File Name ”, __file__)
print(“Absolute Path ”, os.path.abspath(__file__))
print(“Dir Name ” , os.path.dirname(os.path.abspath(__file__)))
BASE_DIR=os.path.dirname(os.path.abspath(__file__))
print(BASE_DIR)
TEMPLATE_DIR=os.path.join(BASE_DIR,’templates’)
Chapter 13 : SQL(Structured Query
Language)
Database:
1.1 Introduction to SQL:
SQL is a language which is used to operate your database. SQL is the basic language
used for all the databases. There are minor syntax changes amongst different databases, but
the basic SQL syntax remains largely the same. SQL is a short abbreviation
of Structured Query Language. According to ANSI (American National Standards Institute),
SQL is the standard language to operate a relational database management system.
SQL is used in the accessing, updating, and manipulation of data in a database. Its
design allows for the management of data in an RDBMS, such as MYSQL. SQL language also
used for controlling data access and for creation and modification of Database schemas.
1.2 What is MYSQL?
Developed in the mid-90s., MySQL was one of the first open-source database available
in the market. Today there are many alternatives variants of MySQL,. However, the differences
between the variants are not significant as they use the same syntax, and basic functionality
also remains same.
MySQL is an RDBMS that allows keeping the data that exists in a database organized. MySQL is
pronounced as "My S-Q-L," but it is also called "My Sequel." It is named after co-founder
Michael Widenius' daughter. MySQL provides a multi-user access to databases. This RDBMS
system is used with the combination of PHP and Apache Web Server, on top of a Linux
distribution. MySQL uses the SQL language to query the database.
1.3 MySQL Data Types:
1. Numeric Types:
Numeric Datatypes allow both signed and unsigned integers. MySQL supports the
following numeric data types.
Data Type Description
TINYINT(size)
Allows signed integers -128 to 127 and 0 to 255 unsigned
integers.
SMALLINT(size)
Allows signed integers from -32768 to 32767 and 0 to 65535
unsigned integers.
MEDIUMINT(size)
Allows signed integers from -8388608 to 8388607 and 0 to
16777215 unsigned integers.
INT(size)
Allows signed integers from -2147483638 to 214747483637
and 0 to 4294967925 unsigned integers.
BIGINT(size)
Allows signed integers from -9223372036854775808
to 9223372036854775807 and 0 to 18446744073709551615
unsigned integers.
FLOAT(size,d)
Allows small numbers with floating decimal point. The
size parameter is used to specify the maximum number of
digits, and the d parameter is used to specify the maximum
number of digits to the right of the decimal.
2. String data types:
Data type Description
CHAR(size)
A FIXED length string (can contain letters, numbers, and
special characters). The size parameter specifies the column
length in characters - can be from 0 to 255. Default is 1
VARCHAR(size)
A VARIABLE length string (can contain letters, numbers, and
special characters). The size parameter specifies the maximum
column length in characters - can be from 0 to 65535
BINARY(size)
Equal to CHAR(), but stores binary byte strings.
The size parameter specifies the column length in bytes.
Default is 1
VARBINARY(size)
Equal to VARCHAR(), but stores binary byte strings.
The size parameter specifies the maximum column length in
bytes.
TINYBLOB For BLOBs (Binary Large OBjects). Max length: 255 bytes
TINYTEXT Holds a string with a maximum length of 255 characters
TEXT(size) Holds a string with a maximum length of 65,535 bytes
BLOB(size)
For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of
data
MEDIUMTEXT
Holds a string with a maximum length of 16,777,215
characters
MEDIUMBLOB
For BLOBs (Binary Large OBjects). Holds up to 16,777,215
bytes of data
LONGTEXT
Holds a string with a maximum length of 4,294,967,295
characters
LONGBLOB
For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295
bytes of data
ENUM(val1, val2, val3,
...)
A string object that can have only one value, chosen from a list
of possible values. You can list up to 65535 values in an ENUM
list. If a value is inserted that is not in the list, a blank value will
be inserted. The values are sorted in the order you enter them
SET(val1, val2, val3, ...)
A string object that can have 0 or more values, chosen from a
list of possible values. You can list up to 64 values in a SET list
3. Date and Time data types:
Data type Description
DATE
A date. Format: YYYY-MM-DD. The supported range is from '1000-
01-01' to '9999-12-31'
DATETIME(fsp)
A date and time combination. Format: YYYY-MM-DD hh:mm:ss. The
supported range is from '1000-01-01 00:00:00' to '9999-12-31
23:59:59'. Adding DEFAULT and ON UPDATE in the column
definition to get automatic initialization and updating to the current
date and time
TIMESTAMP(fsp)
A timestamp. TIMESTAMP values are stored as the number of
seconds since the Unix epoch ('1970-01-01 00:00:00' UTC). Format:
YYYY-MM-DD hh:mm:ss. The supported range is from '1970-01-01
00:00:01' UTC to '2038-01-09 03:14:07' UTC. Automatic
initialization and updating to the current date and time can be
specified using DEFAULT CURRENT_TIMESTAMP and ON UPDATE
CURRENT_TIMESTAMP in the column definition
TIME(fsp)
A time. Format: hh:mm:ss. The supported range is from '-838:59:59'
to '838:59:59'
YEAR
A year in four-digit format. Values allowed in four-digit format: 1901
to 2155, and 0000.
MySQL 8.0 does not support year in two-digit format.
1.4 Type of SQL Commands:
1. DDL (Data Definition Language): Command Statements are used in this are Create Alter,
Rename, Truncate, Drop.
2. DML (Data Manipulation Language): Command Statements are used in this are Insert,
Update, Delete.
3. DQL (Data Query Language): Command Statements are used in this are Select.
4. TCL (Transaction Control Language): -Command Statements are used in this are Commit,
Rollback, Savepoint.
5. DCL (Data Control Language): Command Statements are used in this are Grant, Revoke.
1.5 Important SQL Commands
Let’s see in details Most Important SQL Commands used in Database Management System to
perform multiple Operations
Create Database Statement
Create database statement is used to Create New Database.
CREATE DATABASE database_name;
Example:
CREATE DATABASE testdb;
Create Table Statement
Create Table statement is used to Create New Table in Database before create any table or
performing any Operation we should select database using USE Command.
USE database_name;
CREATE TABLE table_name (
column_name1 data_type (size), column_name2 data_type (size),
column_name3 data_type (size),
....
);
The column_name parameters specify the names of the columns of the table. The
data_type parameter specifies what type of data the column can hold (e.g. varchar,
integer, decimal, date, etc.).
The size parameter specifies the maximum length of the column of the table.
Example:
CREATE TABLE suppliers (
supplier_id int(10), supplier_name varchar(50) ,
contact_name varchar(50)
);
Alter Table Statement
Alter table statement is used to alter (modify) table structure by add, delete, modify
Column and change Column name Also.
Syntax to ADD New Columns:
ALTER TABLE table_name
ADD (column_name1 datatype, column_name2 datatype);
Example:
ALTER TABLE suppliers
ADD (city varchar(30), state varchar(30));
Syntax to MODIFY Exiting Column:
ALTER TABLE table_name
MODIFY column_name new_datatype(new size) [Constraint Names];
Example:
ALTER TABLE suppliers
MODIFY supplier_name varchar(100) NOT NULL
Syntax to DROP Exiting Column:
ALTER TABLE table_name
DROP column_name;
Example:
ALTER TABLE suppliers
DROP state;
Syntax to CHANGE Exiting Column Name:
ALTER TABLE table_name
CHANGE old_column_name new_column_name datatype(size) [Constraint Names];
Example:
ALTER TABLE suppliers
CHANGE contact_name contact_number varchar(50) NOT NULL;
Rename Table Statement
Syntax to CHANGE Exiting Table Name
RENAME TABLE old_tbl_name TO new_tbl_name;
Example:
RENAME TABLE suppliers TO suppliersdetails;
Truncate Table Statement
Syntax to Truncate Table Name
TRUNCATE TABLE table_name;
Example:
TRUNCATE TABLE suppliersdetails;
Drop Table Statement
Syntax to Drop Table Name
DROP TABLE table_name;
Example:
DROP TABLE suppliersdetails;
The SQL INSERT INTO Statement
The INSERT INTO statement is used to insert new records in a table.
It is possible to write the INSERT INTO statement in two forms.
The first form does not specify the column names where the data will be inserted, only
their values:
SQL INSERT INTO Syntax
INSERT INTO table_name (column name list)
VALUES (value1, value2, value3...);
Example:
INSERT INTO suppliers (supplier_id, supplier_name)
VALUES (24553, 'IBM');
The SQL SELECT Statement
The SELECT statement is used to select data from a database.
The result is stored in a result table, called the result-set.
SQL SELECT Syntax
SELECT column_name,column_name
FROM table_name;
And
SELECT * FROM table_name;
Example:
SELECT supplier_name, city, state
FROM suppliers
The SQL WHERE Clause
The WHERE clause is used to extract only those records that fulfill a specified criterion.
SQL WHERE Syntax
SELECT column_name,column_name
FROM table_name
WHERE column_name operator value;
Operators in The WHERE Clause
The following operators can be used in the WHERE clause:
Name Description
= Equal operator
!=, <> Not equal operator
> Greater than operator
>= Greater than or equal operator
< Less than operator
<= Less than or equal operator
LIKE Simple pattern matching
NOT LIKE Negation of simple pattern matching
RLIKE Whether string matches regular expression
BETWEEN ... AND ... Check whether a value is within a range of values
NOT BETWEEN ...
AND ...
Check whether a value is not within a range of values
IS Test a value against a boolean
IS NOT Test a value against a boolean
IS NOT NULL NOT NULL value test
IS NULL NULL value test
NOT, ! Negates value
AND && Logical AND
OR, || Logical OR
The SQL AND & OR Operators
The AND operator displays a record if both the first condition AND the second
condition are true.
The OR operator displays a record if either the first condition OR the second condition
is true.
SELECT ID, NAME, SALARY
FROM CUSTOMERS
WHERE SALARY > 2000 AND age < 25;
Following is an example, which would fetch ID, Name and Salary fields from the CUSTOMERS
table where salary is greater than 2000 AND age is less tan 25 years.
SELECT ID, NAME, SALARY
FROM CUSTOMERS
WHERE SALARY > 2000 OR age < 25;
Following is an example, which would fetch ID, Name and Salary fields from the CUSTOMERS
table
where salary is greater than 2000 OR age is less tan 25 years.
SQL LIKE Operator:
The LIKE operator is used in a WHERE clause to search for a specified pattern in a
column.
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern;
Wildcard’s Used In Like Operator:
SQL Wildcard Characters
In SQL, wildcard characters are used with the SQL LIKE operator.
SQL wildcards are used to search for data within a table.
With SQL, the wildcards are:
Wildcar
d
Explanation
% Allows you to match any string of any length (including zero
length)
_ Allows you to match on a single character
SELECT employeeNumber, lastName, firstName
FROM employees
WHERE firstName LIKE 'a%';
MySQL scans the whole employees table to find employee whose first name starts with
character a and
followed by any number of characters.
To search for employee whose last name ends with on e.g., Patterson, Thompson, you can use
the %
wildcard at the beginning of the pattern as the following query:
SELECT employeeNumber, lastName, firstName
FROM employees
WHERE lastName LIKE '%on';
To find all employees whose last names contain on string, you use the following query with
pattern %on%
SELECT employeeNumber, lastName, firstName
FROM employees
WHERE lastname LIKE '%on%';
SQL LIKE with underscore( _ ) wildcard
To find employee whose first name starts with T, ends with m and contains any single
character between e.g., Tom , Tim, you use the underscore wildcard to construct the pattern
as follows:
SELECT employeeNumber, lastName, firstName
FROM employees
WHERE firstname LIKE 'T_m';
The [charlist] WILDCARDS are used to represent any single character within a charlist.
To get all rows from the table 'agents' with following condition -
the 'agent_name' must begin with the letter 'a' or 'b' or 'i' the following sql statement can be
used :
SELECT*
FROM agents
WHERE agent_name RLIKE '^[abi]';
The [charlist] WILDCARDS are used to represent any single character within a charlist.
To get all rows from the table 'agents' with following condition -
the 'agent_name' must end with the letter 'a' or 'b' or 'i' the following sql statement can be
used :
SELECT*
FROM agents
WHERE agent_name RLIKE '[abi]$';
The [charlist] WILDCARDS are used to represent any single character within a charlist.
To get all rows from the table 'agents' with following condition -
the 'agent_name' containing with the letter 'a' or 'b' or 'i' the following sql statement can be
used :
SELECT*
FROM agents
WHERE agent_name RLIKE '[abi]';
SQL Aliases:
SQL aliases are used to temporarily rename a table or a column heading.
SELECT column_name AS
alias_name FROM table_name;
Example:
SELECT CustomerName AS Customer, ContactName AS [Contact
Person] FROM Customers;
SELECT CustomerName, Address+', '+City+', '+PostalCode+', '+Country AS
Address FROM Customers;
SELECT CustomerName, CONCAT(Address,', ',City,', ',PostalCode,', ',Country) AS
Address FROM Customers;
Aliases can be useful when:
 There are more than one table involved in a query
 Functions are used in the query
 Column names are big or not very readable
 Two or more columns are combined together
Alias Example for Tables
The following SQL statement selects all the orders from the customer with CustomerID=4
(Around the Horn). We use the "Customers" and "Orders" tables, and give them the table
aliases of "c" and "o" respectively (Here we have used aliases to make the SQL shorter):
Example:
SELECT o.OrderID, o.OrderDate,
c.CustomerName FROM Customers AS c,
Orders AS o
WHERE c.CustomerName="Around the Horn" AND c.CustomerID=o.CustomerID;
5.SQL Joins:
SQL joins are used to combine rows from two or more tables,based on a common field
between them.
SQL INNER JOIN (simple join).
An SQL INNER JOIN return all rows from multiple tables where the join condition is met.
Syntax:
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name=table2.column_name;
Example:
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers
ON Orders.CustomerID=Customers.CustomerID;
SQL LEFT JOIN Keyword
The LEFT JOIN keyword returns all rows from the left table (table1), with the matching rows
in the right table (table2). The result is NULL in the right side when there is no match.
SQL LEFT JOIN Syntax
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name=table2.column_name;
Example:
SELECT OrderNumber, TotalAmount, FirstName, LastName, City, Country FROM Customer C
LEFT JOIN [Order] O ON O.CustomerId = C.Id
SQL RIGHT JOIN :
The RIGHT JOIN keyword returns all rows from the right table (table2), with the matching
rows in the left table (table1). The result is NULL in the left side when there is no match.
SQL RIGHT JOIN Syntax
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name=table2.column_name;
Example:
SELECT OrderNumber, TotalAmount, FirstName, LastName, City, Country FROM Customer C
RIGHT JOIN [Order] O ON O.CustomerId = C.Id;
SQL FULL OUTER JOIN Keyword
The FULL OUTER JOIN keyword returns all rows from the left table (table1) and from the
right table (table2).The FULL OUTER JOIN keyword combines the result of both LEFT and
RIGHT joins.
Syntax:
SELECT
column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name=table2.column_name;
Example:
SELECT OrderNumber, TotalAmount, FirstName, LastName, City, Country FROM Customer C
FULL OUTER JOIN [Order] O ON O.CustomerId = C.Id;
SELF JOIN:
It is used to join a table to itself as if the table were two tables, temporarily renaming at least
one table in the SQL statement.Self-joins are used to compare values in a column with other
values in the same column in the same table.
Example:
In the
EMPLOYEE table displayed above, emp_id is the primary key. emp_supv is the foreign key
(this is the supervisor’s employee id).
If we want a list of employees and the names of their supervisors, we’ll have to JOIN the
EMPLOYEE
table to itself to get this list.
Unary relationship to employee
How the employees are related to themselves :
 An employee may report to another employee (supervisor).
 An employee may supervise himself (i.e. zero) to many employee (subordinates).
We have the following data into the table EMPLOYEE.
The above
data shows :
 Unnath Nayar's supervisor is Vijes Setthi
 Anant Kumar and Vinod Rathor can also report to Vijes Setthi.
 Rakesh Patel and Mukesh Singh are under supervison of Unnith Nayar.
In the following example we will use the table EMPLOYEE twice and in order to do this
we will use the alias of the table.
To get the list of employees and their supervisor the following sql statement has used :
SELECT a.emp_id AS "Emp_ID",a.emp_name AS "Employee
Name", b.emp_id AS "Supervisor ID",b.emp_name AS
"Supervisor Name" FROM employee a, employee b
WHERE a.emp_supv = b.emp_id;
Output:
CARTESIAN (CROSS)JOIN:
 Returns the Cartesian product of the sets of records from the two or more joined
tables.
 The size of a Cartesian product result set is the number of rows in the first table
multiplied by the number of rows in the second table.
Example:
Table 1: GameScores
PlayerName DepartmentId Scores
Jason 1 3000
Irene 1 1500
Jane 2 1000
David 2 2500
Paul 3 2000
James 3 2000
Table 2: Departments
DepartmentId DepartmentName
1 IT
2 Marketing
3 HR
SELECT* FROM GameScores CROSS JOIN Departments;
Result:
PlayerNam
e
DepartmentI
d Scores
DepartmentI
d
DepartmentNam
e
Jason 1 3000 1 IT
Irene 1 1500 1 IT
Jane 2 1000 1 IT
David 2 2500 1 IT
Paul 3 2000 1 IT
James 3 2000 1 IT
Jason 1 3000 2 Marketing
Irene 1 1500 2 Marketing
Jane 2 1000 2 Marketing
David 2 2500 2 Marketing
Paul 3 2000 2 Marketing
James 3 3000 2 Marketing
Jason 1 3000 3 HR
Irene 1 1500 3 HR
Core Python.doc
Jane 2 1000 3 HR
David 2 2500 3 HR
Paul 3 2000 3 HR
James 3 3000 3 HR
6.SQL Constraints:
SQL constraints are used to specify rules for the data in a table.
Constraints can be specified when the table is created (inside the CREATE TABLE statement)
or after the table is created (inside the ALTER TABLE statement).
SQL CREATE TABLE + CONSTRAINT Syntax
CREATE TABLE table_name
(
column_name1 data_type(size)
constraint_name, column_name2
data_type(size) constraint_name,
column_name3 data_type(size)
constraint_name,
....
);
Constraints in SQL:
Constraints are rules and restrictions applied on a column of a table so that invalid data can't
be inserted into tables. Its ensures the accuracy and reliability of the data in the database.
Constraints can be specified in two ways-
when the table is created with CREATE TABLE statement
after the table is created with the ALTER TABLE statement
Different types of constraints :
1) NOT NULL
2) UNIQUE
3) PRIMARY KEY
4) DEFAULT
5) CHECK
6) FOREIGN KEY
In SQL, we have the following constraints:
SQL NOT NULL Constraint:
The NOT NULL constraint enforces a column to NOT accept NULL values.
The NOT NULL constraint enforces a field to always contain a value. This means that you
cannot insert a new record, or update a record without adding a value to this field.
Example:
SELECT LastName,FirstName,Address FROM
Persons WHERE Address IS NOT NULL.
SQL UNIQUE Constraint
 The UNIQUE constraint uniquely identifies each record in a database table.
 The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness
for a column or set of columns.
 A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it.
 Note that you can have many UNIQUE constraints per table, but only one PRIMARY
KEY constraint per table.
Example:
CREATE TABLE supplier
( supplier_id numeric(10) NOT NULL,
supplier_name varchar2(50) NOT
NULL, contact_name varchar2(50),
CONSTRAINT supplier_unique UNIQUE (supplier_id)
);
SQL PRIMARY KEY Constraint
 The PRIMARY KEY constraint uniquely identifies each record in a database table.
 Primary keys must contain UNIQUE values.
 A primary key column cannot contain NULL values.
 Most tables should have a primary key, and each table can have only ONE primary
key.
Example:
CREATE TABLE employees
( employee_id INT PRIMARY KEY,
last_name VARCHAR(50) NOT NULL,
first_name VARCHAR(50) NOT NULL,
salary MONEY
);
SQL FOREIGN KEY Constraint
A FOREIGN KEY in one table points to a PRIMARY KEY in another table.
Example:
CREATE TABLE products
product_id numeric(10) not
null, supplier_id numeric(10)
not null, CONSTRAINT
fk_supplier FOREIGN KEY
(supplier_id)
REFERENCES
supplier(supplier_id) );
SQL CHECK Constraint
 The CHECK constraint is used to limit the value range that can be placed in a
column.
 If you define a CHECK constraint on a single column it allows only certain values for this
column.
 If you define a CHECK constraint on a table it can limit the values in certain columns based
on values in other columns in the row.
 Example:
CREATE TABLE employees
employee_id INT NOT NULL, last_name
VARCHAR(50) NOT NULL,
first_name VARCHAR(50),
salary MONEY,
CONSTRAINT check_salary
CHECK (salary > 0)
);
SQL DEFAULT Constraint
The DEFAULT constraint is used to insert a default value into a column.
The default value will be added to all new records, if no other value is specified.
Example:
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT
NULL, FirstName varchar(255),
Address varchar(255),
City varchar(255) DEFAULT 'Sandnes'
)
SQL UNION Operator
1. The SQL UNION operator combines the result of two or more SELECT statements.
2. Notice that each SELECT statement within the UNION must have the same number of
columns.
3. The columns must also have similar data types. Also, the columns in each SELECT
statement must be in the same order.
4. Example:
SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
1. To allow duplicate values, use the ALL keyword with UNION.
SELECT City FROM Customers
UNION ALL
SELECT City FROM Suppliers
SQL ORDER BY Keyword
 The ORDER BY keyword is used to sort the result-set.
 The ORDER BY keyword sorts the records in ascending order by default. To sort the
records in a descending order, you can use the DESC keyword.
Example:
SELECT supplier_city
FROM suppliers
WHERE supplier_name = 'IBM'
ORDER BY supplier_city;
SQL Functions:
SQL Aggregate Functions
SQL aggregate functions return a single value, calculated from values in a
column. Useful aggregate functions:
 AVG() - Returns the average value
 COUNT()- Returns the number of rows
 FIRST() - Returns the first value
 LAST() - Returns the last value
 MAX() - Returns the largest value
 MIN() - Returns the smallest value
 SUM() - Returns the sum
SQL Scalar functions
SQL scalar functions return a single value, based on the input value.
Useful scalar functions:
UCASE() - Converts a field to upper case
LCASE() - Converts a field to lower case
MID() - Extract characters from a text field
LENGTH() - Returns the length of a text field
ROUND() - Rounds a numeric field to the number of decimals specified
NOW() - Returns the current system date and time
FORMAT() - Formats how a field is to be displayed
SQL GROUP BY Statement
The GROUP BY statement is used in conjunction with the aggregate functions to group the result-
set by one or more columns.
Example:
SELECT department, SUM(sales) AS "Total
sales" FROM order_details
GROUP BY department;
The HAVING Clause
The HAVING clause was added to SQL because the WHERE keyword could not be used with
aggregate functions.
SELECT department, SUM(sales) AS "Total sales"
FROM order_details
GROUP BY department
HAVING SUM(sales) > 1000;
SQL Procedure
procedure or in simple a proc is a named PL/SQL block which performs one or more specific
task. This is similar to a procedure in other programming languages.
procedure has a header and a body. The header consists of the name of the procedure and the
parameters or variables passed to the procedure. The body consists or declaration section,
execution section and exception section similar to a general PL/SQL Block.
procedure is similar to an anonymous PL/SQL Block but it is named for repeated usage.
Procedures: Passing Parameters
We can pass parameters to procedures in three ways.
IN-parameters
OUT-parameters
IN OUT-parameters
A procedure may or may not return any value.
General Syntax to create a procedure is:
CREATE PROCEDURE proc_name ( list of parameters)
BEGIN
[ DECLARE VARIABLENAME DATATYPE ]
Execution section
END;
How to execute a Procedure?
TO Execute procedure
call Procedure_name( list of value if any);
Example:
defining procedure
DELIMITER $
CREATE PROCEDURE insertIntoStudent(studid int ,studname varchar(20), studage int)
BEGIN
INSERT INTO student (studid,studname,studage) values (studid,studname,studage);
END;
$
calling procedure
CALL insertIntoStudent(10,’Raj’,21);
SQL Functions
Functions in MySQL always return a value. Thus defining a return type and
returning a value is must for functions
CREATE Function function_name ( list of parameters)
RETURNS datatype
BEGIN
[ DECLARE VARIABLENAME DATATYPE ]
Execution section
RETURN value;
END;
calling a function:
select function_name(parameters);
Example:
defining a function
DELIMITER $
Create Function square(num int)
returns int
declare sqr int;
set sqr=num*num;
return sqr;
END;
$
calling a functiona
select square(5);
SQL Triggers:
A trigger is a pl/sql block structure which is fired when a DML statements like Insert,
Delete, Update is executed on a database table. A trigger is triggered automatically when
an associated DML statement is executed.
Delimiter $
CREATE TRIGGER trigger_name
{BEFORE | AFTER }
{INSERT | UPDATE | DELETE}
ON table_name
[FOR EACH ROW]
BEGIN
sql query
END;
$
EXAMPLE:
CREATE TRIGGER addEmp
after insert on EMPLOYEE
for each row
begin
insert into EmpBackup values(new.empid,new.empname,new.deptName);
end;
$
QUERY to be executed:
insert into EMPLOYEE values(101,’Amit’,’IT’);
Chapter 14 : Python Database Connectivity
What is MySQLdb?
MySQLdb is an interface for connecting to a MySQL database server from Python
There are the following steps to connect a python application to our database.
• Import pymysql
• Create the connection object.
• Create the cursor object
• Execute the query
Creating the connection
To create a connection between the MySQL database and the python application, the connect() method of
pymsql.connect module is used.
Pass the database details like HostName, username, and the database password in the method call. The method
returns the connection object.
The syntax to use the connect() is given below.
Connection-Object=pymysql.connector.connect(host=<host-name>,user=<username>,passwd=<password>)
Performing CRUD operations on Employee table
Chapter 15
Tkinter
Python offers multiple options for developing GUI (Graphical User Interface). Out of
all the GUI methods, tkinter is most commonly used method. It is a standard Python
interface to the Tk GUI toolkit shipped with Python. Python with tkinter outputs the
fastest and easiest way to create the GUI applications. Creating a GUI using tkinter is
an easy task.
To create a tkinter:
Importing the module – tkinter
Create the main window (container)
Add any number of widgets to the main window
Apply the event Trigger on the widgets
*Importing tkinter is same as importing any other module in the python code.
import tkinter
There are two main methods used you the user need to remember while creating
the Python application with GUI.
1.Tk(screenName=None, baseName=None, className=’Tk’, useTk=1): To
create a main window, tkinter offers a method ‘Tk(screenName=None,
baseName=None, className=’Tk’, useTk=1)’. To change the name of the window,
you can change the className to the desired one. The basic code used to create the
main window of the application is:
2.mainloop(): There is a method known by the name mainloop() is used when you
are ready for the application to run. mainloop() is an infinite loop used to run the
application, wait for an event to occur and process the event till the window is not
closed.
Example:
#import tkinter module
import tkinter
#create parent window or main window of application
m = tkinter.Tk()
'''
widgets are added here
'''
#mainloop method that runs your application
m.mainloop()
There are number of widgets which you can put in your tkinter application.
1.Button:To add button in your application the general syntax is:
w=Button(master,option=value)
master is the parameter used to represent the parent window
There are number of options which are used to change the format of the
buttons.Number of options can be passed as parameters separated by comma.
1.activebackground:to set the background color when button is under the cursor.
2.activeforeground:to set foreground color when button is under the cursor
3.bg:-to set the background color
4.coomand:-to call function
5.font:-To set the font on the button label
6.image:-set image on button
7.fg:-to set font color of button
8.width:-To set width of button
9.height:-to set height of button
10.text:-set title/text of button
Example
import tkinter as tk
#to create frame/window
r=t.Tk()
#set the title of frame/window
r.title(‘Counting seconds’)
#create Button
button=tk.Button(r,text=’stop’,width=25,command=r.destroy)
#Placing button in parent window
Button.pack()
r.mainloop()
2.canvas:
It is used to draw pictures and other complex layout like graphics, text and widgets.
Syntax:
w=canvas(master,option=value)
there are number of options are used to change the format of the widgets.Number
of options can be passed as parameters separated by comma.
1.bd:-to set the border width in pixels
2.bg:-to set the normal background colour
3.cursor:to set the cursor used in canvas.
4.highlightcolor:-to set the color shown in the focus highlight.
5.width:-to set width of the widget
6.height:-to set height of the widget
Example:
from tkinter import *
master=Tk()
w=Canvas(master,width=40,height=60)
w.pack()
canvas_height=20
canvas_width=200
y=int(canvas_height/2)
w.create_line(0,y,canvas_width,y)
master.mainloop()
6.Label:
IIt refers to the display box where you can put any text or image which can be
updated any time as per the code.
The general syntax is:
w=Label(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget.
Number of options can be passed as parameters separated by commas. Some of
them are listed below.
bg: to set he normal background color.
bg to set he normal background color.
command: to call a function.
font: to set the font on the button label.
image: to set the image on the button.
width: to set the width of the button.
height” to set the height of the button.
Example:-
from tkinter import *
root = Tk()
w = Label(root, text='GeeksForGeeks.org!')
w.pack()
root.mainloop()
4)checkButton:-To select any number of options by displaying number of options
by displaying number of option to user as toggle buttons.The general syntax is:
w=checkbutton(master,option=value)
Options are:
1.Title:to set title of widget
2.activebackground:to set the background color when widget is under the cursor
2.activeforeground:to set the foreground color when widget is under cursor
3.bg:-to set the normal bqackground color
4.command:to call function
5.font:to set font on button label
6.To set image on the widget
from tkinter import *
master=Tk()
var1=IntVar()
checkbutton(master,text=’male’,variable=var1).grid(row=0,sticky=W)
var2=IntVar()
checkbutton(master,text=’female’,variable=var2).grid(row=1,sticky=W)
master.mainloop()
5.)Entry:It is used to input the single line text entry from user.for multiline text
input,text widget is used.The syntax is:
w=Entry(master,option=value)
master represents the parent window.
Options are
1.bd:-to set the border width in pixels
2.bg:-to set the normal background colour
3.cursor:to set the cursor used.
4.command:-to call function
5.highlightcolor:-to set the color shown in the focus highlight.
6.width:-to set width of the widget
7.height:-to set height of the widget
Example:
from tkinter import *
master=TK()
Label(master,text=”First Name”).grid(row=0)
Label(master,text=”Last Name”).grid(row=1)
e1=Entry(master)
e2=Entry(master)
e1.grid(row=0,column=1)
e1.grid(row=1,column=1)
master.mainloop()
6.Frame:It acts as a container to hold the widgets.It is used for grouping and
organizing the widgets.
Their are number of options are used to change the format of widget. Number of
options can be passed as parameters separated by comma.some of them are listed.
1.bd:-to set the border width in pixels
2.bg:-to set the normal background colour
3.cursor:to set the cursor used.
4.command:-to call function
5.highlightcolor:-to set the color shown in the focus highlight.
6.width:-to set width of the widget
7.height:-to set height of the widget
Example:
from tkinter import *
root = Tk()
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )
redbutton = Button(frame, text = 'Red', fg ='red')
redbutton.pack( side = LEFT)
greenbutton = Button(frame, text = 'Brown', fg='brown')
greenbutton.pack( side = LEFT )
bluebutton = Button(frame, text ='Blue', fg ='blue')
bluebutton.pack( side = LEFT )
blackbutton = Button(bottomframe, text ='Black', fg ='black')
blackbutton.pack( side = BOTTOM)
root.mainloop()
7. Listbox: It offers a list to the user from which the user can accept any number of
options.
The general syntax is:
w = Listbox(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget.
Number of options can be passed as parameters separated by commas. Some of
them are listed below.
 highlightcolor: To set the color of the focus highlight when widget has to be
focused.
 bg: to set he normal background color.
 bd: to set the border width in pixels.
 font: to set the font on the button label.
 image: to set the image on the widget.
 width: to set the width of the widget.
 height: to set the height of the widget.
Example
from tkinter import *
top = Tk()
Lb = Listbox(top)
Lb.insert(1, 'Python')
Lb.insert(2, 'Java')
Lb.insert(3, 'C++')
Lb.insert(4, 'Any other')
Lb.pack()
top.mainloop()
8. MenuButton: It is a part of top-down menu which stays on the window all the
time. Every menubutton has its own functionality. The general syntax is:
w = MenuButton(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget.
Number of options can be can be passed as parameters separated by commas. Some
of them are listed below.
 activebackground: To set the background when mouse is over the widget.
 activeforeground: To set the foreground when mouse is over the widget.
 bg: to set he normal background color.
 bd: to set the size of border around the indicator.
 cursor: To appear the cursor when the mouse over the menubutton.
 image: to set the image on the widget.
 width: to set the width of the widget.
 height: to set the height of the widget.
 highlightcolor: To set the color of the focus highlight when widget has to be
focused.
top = Tk()
mb = Menubutton ( top, text = "condiments", relief = RAISED )
mb.grid()
mb.menu = Menu ( mb, tearoff = 0 )
mb["menu"] = mb.menu
mayoVar = IntVar()
ketchVar = IntVar()
mb.menu.add_checkbutton ( label = "mayo",
variable = mayoVar )
mb.menu.add_checkbutton ( label = "ketchup",
variable = ketchVar )
mb.pack()
top.mainloop()
9. Menu: It is used to create all kinds of menus used by the application.
The general syntax is:
w = Menu(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of this widget.
Number of options can be passed as parameters separated by commas. Some of
them are listed below.
 title: To set the title of the widget.
 activebackground: to set the background color when widget is under the
cursor.
 activeforeground: to set the foreground color when widget is under the
cursor.
 bg: to set he normal background color.
 command: to call a function.
 font: to set the font on the button label.
 image: to set the image on the widget.
from tkinter import *
root = Tk()
menu = Menu(root)
root.config(menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label='File', menu=filemenu)
filemenu.add_command(label='New')
filemenu.add_command(label='Open...')
filemenu.add_separator()
filemenu.add_command(label='Exit', command=root.quit)
helpmenu = Menu(menu)
menu.add_cascade(label='Help', menu=helpmenu)
helpmenu.add_command(label='About')
mainloop()
Message: It refers to the multi-line and non-editable text. It works same as that of
Label.
The general syntax is:
w = Message(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget.
Number of options can be passed as parameters separated by commas. Some of
them are listed below.
 bd: to set the border around the indicator.
 bg: to set he normal background color.
 font: to set the font on the button label.
 image: to set the image on the widget.
 width: to set the width of the widget.
 height: to set the height of the widget.
from tkinter import *
main = Tk()
ourMessage ='This is our Message'
messageVar = Message(main, text = ourMessage)
messageVar.config(bg='lightgreen')
messageVar.pack( )
main.mainloop( )
10. RadioButton: It is used to offer multi-choice option to the user. It offers several
options to the user and the user has to choose one option.
The general syntax is:
w = RadioButton(master, option=value)
There are number of options which are used to change the format of this widget.
Number of options can be passed as parameters separated by commas. Some of
them are listed below.
 activebackground: to set the background color when widget is under the
cursor.
 activeforeground: to set the foreground color when widget is under the
cursor.
 bg: to set he normal background color.
 command: to call a function.
 font: to set the font on the button label.
 image: to set the image on the widget.
 width: to set the width of the label in characters.
 height: to set the height of the label in characters.
from tkinter import *
root = Tk()
v = IntVar()
Radiobutton(root, text='GfG', variable=v, value=1).pack(anchor=W)
Radiobutton(root, text='MIT', variable=v, value=2).pack(anchor=W)
mainloop()
Scale: It is used to provide a graphical slider that allows to select any value from
that scale. The general syntax is:
w = Scale(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget.
Number of options can be passed as parameters separated by commas. Some of
them are listed below.
 cursor: To change the cursor pattern when the mouse is over the widget.
 activebackground: To set the background of the widget when mouse is over
the widget.
 bg: to set he normal background color.
 orient: Set it to HORIZONTAL or VERTICAL according to the requirement.
 from_: To set the value of one end of the scale range.
 to: To set the value of the other end of the scale range.
 image: to set the image on the widget.
 width: to set the width of the widget.
from tkinter import *
master = Tk()
w = Scale(master, from_=0, to=42)
w.pack()
w = Scale(master, from_=0, to=200, orient=HORIZONTAL)
w.pack()
mainloop()
11. Scrollbar: It refers to the slide controller which will be used to implement
listed widgets.
The general syntax is:
w = Scrollbar(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget.
Number of options can be passed as parameters separated by commas. Some of
them are listed below.
 width: to set the width of the widget. width: to set the width of the widget.
 activebackground: To set the background when mouse is over the widget.
 bg: to set he normal background color.
 bd: to set the size of border around the indicator.
 cursor: To appear the cursor when the mouse over the menubutton.
 activebackground: To set the background when mouse is over the widget.
from tkinter import *
root = Tk()
scrollbar = Scrollbar(root)
scrollbar.pack( side = RIGHT, fill = Y )
mylist = Listbox(root, yscrollcommand = scrollbar.set )
for line in range(100):
mylist.insert(END, 'This is line number' + str(line))
mylist.pack( side = LEFT, fill = BOTH )
scrollbar.config( command = mylist.yview )
mainloop()
Text: To edit a multi-line text and format the way it has to be displayed.
The general syntax is:
w =Text(master, option=value)
There are number of options which are used to change the format of the text.
Number of options can be passed as parameters separated by commas. Some of
them are listed below.
 highlightcolor: To set the color of the focus highlight when widget has to be
focused.
 insertbackground: To set the background of the widget.
 bg: to set he normal background color.
 font: to set the font on the button label.
 image: to set the image on the widget.
 width: to set the width of the widget.
 height: to set the height of the widget.
from tkinter import *
root = Tk()
T = Text(root, height=2, width=30)
T.pack()
T.insert(END, 'GeeksforGeeksnBEST WEBSITEn')
mainloop()
12)TopLevel: This widget is directly controlled by the window manager. It don’t
need any parent window to work on.The general syntax is:
w = TopLevel(master, option=value)
There are number of options which are used to change the format of the widget.
Number of options can be passed as parameters separated by commas. Some of
them are listed below.
 bg: to set he normal background color.
 bd: to set the size of border around the indicator.
 cursor: To appear the cursor when the mouse over the menubutton.
 width: to set the width of the widget.
 height: to set the height of the widget.
from tkinter import *
root = Tk()
root.title('GfG')
top = Toplevel()
top.title('Python')
top.mainloop()
13.SpinBox: It is an entry of ‘Entry’ widget. Here, value can be input by selecting a
fixed value of numbers.The general syntax is:
w = SpinBox(master, option=value)
There are number of options which are used to change the format of the widget.
Number of options can be passed as parameters separated by commas. Some of
them are listed below.
 bg: to set he normal background color.
 bd: to set the size of border around the indicator.
 cursor: To appear the cursor when the mouse over the menubutton.
 command: To call a function.
 width: to set the width of the widget.
 activebackground: To set the background when mouse is over the widget.
 disabledbackground: To disable the background when mouse is over the
widget.
 from_: To set the value of one end of the range.
 to: To set the value of the other end of the range.
from tkinter import *
master = Tk()
w = Spinbox(master, from_ = 0, to = 10)
w.pack()
mainloop()
14. PannedWindow:It is a container widget which is used to handle number of
panes arranged in it. The general syntax is:
w = PannedWindow(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget.
Number of options can be passed as parameters separated by commas. Some of
them are listed below.
 bg: to set he normal background color.
 bd: to set the size of border around the indicator.
 cursor: To appear the cursor when the mouse over the menubutton.
 width: to set the width of the widget.
 height: to set the height of the widget.
from tkinter import *
m1 = PanedWindow()
m1.pack(fill = BOTH, expand = 1)
left = Entry(m1, bd = 5)
m1.add(left)
m2 = PanedWindow(m1, orient = VERTICAL)
m1.add(m2)
top = Scale( m2, orient = HORIZONTAL)
m2.add(top)
mainloop()
Core Python.doc

More Related Content

PDF
Python programming
PPTX
python ppt | Python Course In Ghaziabad | Scode Network Institute
PPTX
Python final presentation kirti ppt1
PPTX
Python Programming-1.pptx of python by computer
PDF
PDF
python-online&offline-training-in-kphb-hyderabad (1) (1).pdf
PDF
Introduction Python Programming Concepts for Beginers
PPTX
UNIT 1 PYTHON introduction and basic level
Python programming
python ppt | Python Course In Ghaziabad | Scode Network Institute
Python final presentation kirti ppt1
Python Programming-1.pptx of python by computer
python-online&offline-training-in-kphb-hyderabad (1) (1).pdf
Introduction Python Programming Concepts for Beginers
UNIT 1 PYTHON introduction and basic level

Similar to Core Python.doc (20)

PPTX
Python Tutorials.pptx
PDF
AI in FinTech Introduction chapter AI(MBA)
PDF
python course ppt pdf
PPTX
PYTHON FEATURES.pptx
PPTX
Chapter - 1.pptx
PPTX
Python Programming
PPTX
unit (1)INTRODUCTION TO PYTHON course.pptx
PDF
Summer Training Project.pdf
PDF
durga python full.pdf
PDF
Python Notes.pdf
PPT
Python for students step by step guidance
PPTX
Python Programming Draft PPT.pptx
PPT
1-ppt-python.ppt
PPTX
python introduction initial lecture unit1.pptx
PDF
python-handbook.pdf
PDF
kecs105.pdf
PDF
How To Tame Python
PPT
python-ppt.ppt
PPT
python-ppt.ppt
PPTX
Python Tutorial | Python Programming Language
Python Tutorials.pptx
AI in FinTech Introduction chapter AI(MBA)
python course ppt pdf
PYTHON FEATURES.pptx
Chapter - 1.pptx
Python Programming
unit (1)INTRODUCTION TO PYTHON course.pptx
Summer Training Project.pdf
durga python full.pdf
Python Notes.pdf
Python for students step by step guidance
Python Programming Draft PPT.pptx
1-ppt-python.ppt
python introduction initial lecture unit1.pptx
python-handbook.pdf
kecs105.pdf
How To Tame Python
python-ppt.ppt
python-ppt.ppt
Python Tutorial | Python Programming Language
Ad

Recently uploaded (20)

PPTX
UV-Visible spectroscopy..pptx UV-Visible Spectroscopy – Electronic Transition...
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
Complications of Minimal Access Surgery at WLH
PPTX
CHAPTER IV. MAN AND BIOSPHERE AND ITS TOTALITY.pptx
PDF
Classroom Observation Tools for Teachers
PDF
Practical Manual AGRO-233 Principles and Practices of Natural Farming
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PPTX
Unit 4 Skeletal System.ppt.pptxopresentatiom
PDF
Weekly quiz Compilation Jan -July 25.pdf
PDF
What if we spent less time fighting change, and more time building what’s rig...
PDF
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PPTX
Lesson notes of climatology university.
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
Onco Emergencies - Spinal cord compression Superior vena cava syndrome Febr...
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PPTX
Chinmaya Tiranga Azadi Quiz (Class 7-8 )
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PPTX
UNIT III MENTAL HEALTH NURSING ASSESSMENT
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
UV-Visible spectroscopy..pptx UV-Visible Spectroscopy – Electronic Transition...
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Complications of Minimal Access Surgery at WLH
CHAPTER IV. MAN AND BIOSPHERE AND ITS TOTALITY.pptx
Classroom Observation Tools for Teachers
Practical Manual AGRO-233 Principles and Practices of Natural Farming
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
Unit 4 Skeletal System.ppt.pptxopresentatiom
Weekly quiz Compilation Jan -July 25.pdf
What if we spent less time fighting change, and more time building what’s rig...
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
Lesson notes of climatology university.
Final Presentation General Medicine 03-08-2024.pptx
Onco Emergencies - Spinal cord compression Superior vena cava syndrome Febr...
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
Chinmaya Tiranga Azadi Quiz (Class 7-8 )
Chinmaya Tiranga quiz Grand Finale.pdf
UNIT III MENTAL HEALTH NURSING ASSESSMENT
202450812 BayCHI UCSC-SV 20250812 v17.pptx
Ad

Core Python.doc

  • 1. PYTHON Chapter 1 : Introduction Python is general purpose high level programming language. It was invented by Guido Van Rossam .The development of python started from 1989 and it launched in Feb 20th 1991. The idea of python started from yearly 1980’s and real implementation started from year 1989 and finally published in year 27th Feb 1991. Professionally first version in 1994. The Guido developed python while working in national research institute of Netherlands. Birth date of Guido was 31st Jan 1956 in Netherland. He has completed his master degree in 1982 in mathematics and computer science. Computer Science in Amstredam University. After completing Master Degree he has worked in Netherland Organisation of Research Center. Python developed Centrum Wiskunda and informatica research center in the field of mathematics and computers. Ancestor of Python SETL Language is a very high level programming language based on mathematics and theory off sets. SETL appeared in 1969, developed in NewYork University. ABC language came from this language. ABC is an interpreter language. And ABC developed in CWI. The Guido worked long time in this language and learned interpreter and designing of language through this language. After working few year in ABC Guido came to know that there are many limitation in ABC, because it is extensible(it means we cannot add any features in this language). So whatever Guido wanted to make changes in ABC, it became impossible. Guido worked in Modula2+ and it takes information about Modula3 from developer. In Modula3, he found out the exception handling concept ,which is not available in ABC. And also worked in Ameabo Operating System, it is a distributed Operating System and he find out drawback in this system also. And it is very difficult to find the error in this operating system. Reason behind python is to release the drawback of Abc for eg. Exception Handling. And this happened in year 1999 in December Christmas holiday.
  • 2. How Python name came into the picture? Monty Python Client Circus was the name of comedy series and Guido was fan of this series , so he was inspired by the name, and named it as Python. python program is a combination of : 1.Functional programming Language from c 2.oops concept from c++. 3.Scripting language from perl and shell script 4.Modular programming language from Modula-3. Syntax from c and ABC Language. Features of python 1.Simple and easy to learn: Python is easy to learn and use. It is developer-friendly and high level programming language. Python has few keywords, simple structure, and a clearly defined syntax. This allows the student to pick up the language quickly. 2.Open Source: Python language is freely available at offical web address.The source-code is also available. Therefore it is open source 3.High Level Programming Language: 4:Platform Independent: Python can run equally on different platforms such as Windows, Linux, Unix and Macintosh etc. So, we can say that Python is a portable language. 5:Portability: Python can run on a wide variety of hardware platforms and has the same interface on all platforms. 6.Dynamicall30,40]y Typed: No need to defined data type for the variable 7.Both Procedure Orented and Object Oriented:
  • 3. Python supports object oriented language and concepts of classes and objects come into existence and also we can create the programs without using class 8.Interpreted Language: Python is an interpreted language i.e. interpreter executes the code line by line at a time. This makes debugging easy and thus suitable for beginners. 9.Extensible: It implies that other languages such as C/C++ can be used to compile the code and thus it can be used further in our python code. 10.A broad standard library: Python's bulk of the library is very portable and cross-platform compatible on UNIX, Windows, and Macintosh. 11.Databases: Python provides interfaces to all major commercial databases Python version: python 1.0 introduced in Jan 1994 python 2.0 introduced in October 2000 python 3.0 introduced in Dec 2008 Python is not backward compatible. Flavour of Python 1. Cpython, can be used to work with C language application. 2. Jpython or jython, it is for java applications. 3. Ironpython ,this python is used to work with C++ and .Net Applications. 4. Pypython, inside python it contain Virtual Machine with JIT Compiler so it’s performance is relatively improved. If you want high performance go for this python. 5. Ruby Python, used to work with ruby. 6. Anaconda Python, it is used to work with Big Data Python . 7. Stackless Python, for concretely multithreaded concept. Where we can use python 1.Desktop application 2.Web applications 3.Database Application 4.For Networking applications
  • 4. 5.Games 6.Data analysis 7.Machin Language 8.AI 9.For IOT Appplication The company using python 1.Google 2.YouTube 3.Dropbox 4.NASA Reserve key words: There are 33 key words. ['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'] Rules of identifer 1. A-Z and a-z and 0-9 this are only allowed in symbol. 2. It should not start with digit. 3. Case Sensitive. 4. Keyword is not allowed. 5. No long limit. 6. $ symbol is not allowed for identifer. Data types: 1.int 2.float 3.complex 4.bool 5.str 6.bytes 7.bytearray 8.range
  • 5. 9.list 10.tuple 11.set 12.frozenset 13.dict 14.None Long Datatype used only in python-2 but not in python-3 and double,character is not allowed in python. In python every thing implemented as a object and all objects are immutable we cannot modifies the original object. In python 0 to 256 objects are created when you interpreted the programs In python when we create object for int ,bool,str it can be reused for ex if we define one object: x=10 y=10 z=10 now only one object created and three reference refer the same object for eg: x=10 y=10 z=10 print("Id of x ",id(x)) print("Id of y ",id(y)) print("Id of z ",id(z)) print(x is y) o/p Id of x 10919712 Id of y 10919712 Id of z 10919712
  • 6. True name="coder" name1="coder" print("Id of name ",id(name)) print("Id of name1 ",id(name1)) print(name is name1) o/p Id of name 140530020957576 Id of name1 140530020957576 True b=True b1=True print("Id of b ",id(b)) print("Id of b1 ",id(b1)) print(b is b1) Id of b 10744160 Id of b1 10744160 True the reusing of object in int is possible from 0 to 256 python accept: 1.Decimal form 2.Binary form a=0B1111 print(a) o/p 15 a=-0B1111 print(a) o/p -15
  • 7. 3.octal form a=0o1111 print(a) o/p 585 4.Hexa Decimal. a=0XFace print(a) o/p 64206 For Type cast we need this method 1)int() 2)float() 3)bool() 4)str() print(int(123.33)) #converting float to int print(int(True)) #converting bool to int print(int("10")) #converting String to int #(int("123.33")) #converting String to int it give type cast error we can applicable only base vakue in s String print(float(12)) print(float(True)) print(float(False)) print(float("10"))
  • 8. print(float("10.2")) print#(float("sad")) give error print(bool(0)) print(bool(1)) print(bool(10)) print(bool(0.0)) print(bool(0.1)) print(bool("coder")) #o/p true print(bool(""))# o/p false print(bool(" "))#o/p True print(str(10)) print(str(10.0)) print(str(True)) print(str(10)) ''' Slice''' name="Coder technology" print(name) print(name[2]) print(name[1:3]) print(name[2:7]) print(name[-1]) print(name[-2]) print(name[-5]) print(name[-5:-1]) print("-5 :-8 ",name[-5:-8])#this is not possible print("-8 :-5 ",name[-8:-5]) print("-8 :-2 ",name[-8:-2]) o/p Coder technology d
  • 9. od der t y g o olog -5 :-8 -8 :-5 chn -8 :-2 chnolo
  • 10. Chaptar 2: Basic Programs Variable = it is used to store the value; data type = in python no need to give data type it change its data type according to the value for eg num=10 // no need to give datatype print(type(num)) print method is used to print in console it is inbuilt method type method is use to find the data type o/p 10 <class 'int'> st="coder" print(type(st)) print("Name is =",st) ''' , is used for concatination''' o/p <class 'str'> Name is = coder Addition num=10 num1=20 result=num+num1
  • 11. 30,40] print("Addition of two number is =",result) o/p Addition of two number is = 30 Taking input from the user ''' input method is used to take input from the user and its return type is by default String so we want convert it according to our input by casting ''' num=int(input("enter the first number= ")) num1=int(input("enter the second number= ")) result=num+num1 print("Addition =",result) o/p enter the first number= 10 enter the second number= 20 Addition = 30 Division num=int(input("enter the first number =")) num1=int(input("enter the second number =")) result=num/num1 print("Division =",result) o/p enter the first number =5 enter the second number =3 Division = 1.6666666666666667 Control Statements 1)if..else Syntax: if condition: #code else:
  • 12. #code '''if else Even or odd ''' num=int(input("Enter the number to check =")) if num%2 is 0: print("even number") else: print("odd number") ''' for if else no need to give the bracket jest we want to give ":" ''' Nested if else syntax: if condition: #code if condition: #code else: #code else: #code ''' nested if else ''' percentage=int(input("Enter the percentage =")) if percentage >= 90: exp=int(input("Enter the number to experience = ")) if exp >= 2: print("eligible for job") else: print("not eligible for job") else:
  • 13. print("not qualified") '’'Ladder if else''' mark1=int(input("Enter the mark one =")) mark2=int(input("Enter the mark two =")) mark3=int(input("Enter the mark three =")) total=mark1+mark2+mark3 print("Total mark is = ",total) per=total/300*100 print("Percentage is =",per) if per >= 90: print("A grade") elif per >=70 and per<90: print("B grade") elif per >=50 and per<70: print("c grade") else: print("fail") '''Areat of the triangle''' base = float(input('Enter the value of base : ')) height = float(input('Enter the value of height : ' )) area = 0.6* base * height; print('Area of Triangle is ',area) num=10; print("number is"+str(num))#we cannot use + operators for concatination of other datatype #we can concat only string so if we use + operators then we have cast it in String Loops num=1 while num<10: print(num) num+= 1 num=int(input("enter the number")) num1=1; while num1<=num:
  • 14. if num1%2==0: print(num1) num1+=1 for i in range(1,5): '''by default it increment by 1''' print(i) o/p 1 2 3 4 for i in range(5,0,-1): # ''' for decrement we want to use -1''' print(i) o/p 5 4 3 2 1 for i in range(1,5): print(i,end=" ") ''' bydefault print go to next line so for continuing in one line we use end=”” '' o/p 1 2 3 4 Prime number num=int(input("enter the number to check ")) for i in range(2,num): if (num%i)==0: print(num,"is not a prime number")
  • 15. break; else: print(" is a prime number") Pattern 1: for i in range(1,6): for j in range(1,6): print(i,end=" ") print() 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 Patterns 2: for i in range(1,6): for j in range(1,i+1): print(j,end=" ") print() 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 Pattern 3: for i in range(6,0,-1): for j in range(5,i-1,-1): print(j,end=" ") print() 5 5 4 5 4 3 5 4 3 2
  • 16. 5 4 3 2 1 Patterns 4: for i in range(1,6): for j in range(5,i-1,-1): print(j,end=" ") print() 5 4 3 2 1 5 4 3 2 5 4 3 5 4 5 for i in range(1,6): for space in range(5,i,-1): print(" ",end="") for j in range(1,i): print("* ",end="") print() * * * * * * * * * * Pattern 5: for i in range(1,6): for space in range(5,i,-1): print(" ",end="") for j in range(1,i): print("* ",end="") print() for i in range(1,5):
  • 17. for space in range(0,i,): print(" ",end="") for j in range(4,i,-1): print("* ",end="") print() * * * * * * * * * * * * * * * * pattern 6: for i in range(1,6): for space in range(5,i,-1): print(" ",end="") for j in range(1,i): print(j," ",end="") print() for i in range(1,5): for space in range(0,i,): print(" ",end="") for j in range(4,i,-1): print(j," ",end="") print() 1 1 2 1 2 3 1 2 3 4 4 3 2 4 3 4 pattern 7:
  • 18. for i in range(1,6): for j in range(1,6): if i==1 and j==1 or i==1 and j==5 or i==5 and j==1 or i==5 and j==5: print("*" ,end="") else: print(" ",end="") print() * * * * Python Collections (Arrays) There are four collection data types in the Python programming language:  List is a collection which is ordered and changeable. Allows duplicate members.  Tuple is a collection which is ordered and unchangeable. Allows duplicate members.  Set is a collection which is unordered and unindexed. No duplicate members.  Dictionary is a collection which is unordered, changeable and indexed. No duplicate members. 1)cars = ["maruthi", "suzuki", "BMW"] print(cars) 2)x = cars[0] print(x) 3)cars[0] = "Toyota" print(cars) 4)for x in cars: print(x)
  • 19. ''' Add one more element to the cars array:''' 5)cars.append("Honda") print(cars) ''' Delete the second element of the cars array:''' 6)cars.pop(1) print(cars) 7)cars.remove("BMW") print(cars) 8)a = [1, 2, 3, 4] print(len(a)) print(a[0]) for i in range(len(a), 0, -1): print(i, end=' ') '''it just acts like for loop in range paass arguemnts like u pass in for loop first aregument in range is from where do u want to start second is until where it should go and thirs is the amount it should be increased or decreased ''' print() for i in range(5): for j in range(5, i, -1): print('*', end=' ') print() 9)size=int(input("enter the size")) arr=[] print("enter %d"%size+"value:") for i in range(size): n=int(input("enter %d =" %(i+1)+ "value:")) arr.append(n) for i in range(len(arr)): print(arr[i],end=" ") print() arr1=[] print("enter the second array")
  • 20. for i in range(size): n=int(input("enter %d =" %(i+1)+ "value:")) arr1.append(n) for i in range(len(arr)): print(arr1[i],end=" ") print() addition=[] for i in range(size): addition.append((int)(arr[i]+arr1[i])) for i in range(len(addition)): print(addition[i],end=' ') ------------------------------------------------- find put largest number in array size=int(input("enter the size")) arr=[] for i in range(size): n=int(input("enter the "+str((i+1))+" value:")) arr.append(n) largest=arr[0] for i in range(size): if arr[i]>largest: largest=arr[i] print("largest",largest) 1) l=["apple","banana","mango"] print(l) 2) l=[1,12,123.0,"hello"] print(l) 3)l.append("world") ''' we can modify the list''' print(l) 4)for i in l:
  • 21. print(i) ''' this work like a enhansed for loop''' 5)for i in range(0,len(l)): print(l[i]) 6)l1=[] a=int(input("Enter the size")) ''' take size from the user ''' for k in range(0,a): b=input("inter the value"); l1.append(b); print(l1) print(len(l1)) 7)if "12" in l1: print("yes") else: print("no") 8)l=[10,4,15,24,85,9] for i in l: print (i); 9)print("set the value at position one") l.insert(1,55) for i in l: print (i); 10)l.remove(15) print ("after removing") for i in l: print (i); 11)l.pop() print ("after pop it remoove the last elements") for i in l: print (i); 12)del l[1] print("after del :") for i in l:
  • 22. print (i); 13)print("To clear the list") l.clear() print(l) 14)del l print(l) 2-Dimentional array: A two dimensional array is usually represented in Python by a list of lists. However, the initialization of such a value is not as easy as the initialization of a one- dimensional list. Here is an example that illustrates the most common technique. Example: row=int(input("Enter number of rows for matrix:")) column=int(input("Enter number of columns for matrix")) first_matrix=[] second_matrix=[] result_matrix=[] print("Enter {} * {} Matrix".format(row,column)) print("Enter first Matrix:") for r1 in range(row): rows=[] for c1 in range(column): ele=int(input("Enter element:")) rows.append(ele) first_matrix.append(rows) #print("first matrix is: ".format(first_matrix)) print("Enter second Matrix:") for r1 in range(row): rows=[] for c1 in range(column): ele=int(input("Enter element:")) rows.append(ele) second_matrix.append(rows) #print(second_matrix) for r1 in range(row): rows=[] for c1 in range(column): row=int(first_matrix[r1][c1])+int(second_matrix[r1][c1])
  • 23. #print(row) rows.append(row) result_matrix.append(rows) print("Addition of {}+{}={}".format(first_matrix,second_matrix,result_matrix)) Output Enter number of rows for matrix:2 Enter number of columns for matrix2 Enter 2 * 2 Matrix Enter first Matrix: Enter element:1 Enter element:1 Enter element:2 Enter element:2 Enter second Matrix: Enter element:1 Enter element:3 Enter element:4 Enter element:5 Addition of [[1, 1], [2, 2]]+[[1, 3], [4, 5]]=[[2, 4], [6, 7]] Tuple A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets. t = ("apple", "banana", "cherry") print(t) t = ("apple", "banana", "cherry") print(t[1]) t = ("apple", "banana", "cherry") t[1] = "blackcurrant" # The values will remain the same: print(t) Set A set is a collection which is unordered and unindexed. In Python sets are written with curly brackets.
  • 24. s = {"geetha", "ramesh", "cherry"} print(s) o/p {'ramesh', 'geetha', 'cherry'} Access Items You cannot access items in a set by referring to an index, since sets are unordered the items has no index. But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword. 1)thisset = {"apple", "banana", "cherry"} for x in thisset: print(x) 2)thisset = {"apple", "banana", "cherry"} print("banana" in thisset) //to check the content Add Items To add one item to a set use the add() method. To add more than one item to a set use the update() method. 3)s1 = {"pineApple", "mango", "cherry"} s1.add("orange") print(s1) 4)s2 = {"pineApple", "mango", "cherry"}
  • 25. s2.update(["orange","graps","watermilon"]) print(s2) 5)s3 = {"apple", "banana", "cherry"} s3.remove("banana") print(s3) 6)s4 = {"apple", "banana", "cherry"} s4.discard("banana") print(s4) 7) = {"apple", "banana", "cherry"} x = s5.pop() print(x) print(s5) Dictionary A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values. 1)dis={ "empName":"Ramesh", "id":105, "salary":1000, "designation":"Acc" }
  • 26. print(dis)//to print the dictionary 2)s=dis["id"]// to fetch the value print(s) 3)''' Get the value of the "model" key:''' n=dis.get("empName") print(n) ''' to change the value''' 4)dis["salary"]=5000; print(dis) 5)for x in dis: print(x) 6)for x in dis: print(dis[x]) ''' You can also use the values() function to return values of a dictionary:''' 6)for x in dis.values(): print(x) '''Loop through both keys and values, by using the items() function:''' 7)for x, y in dis.items(): print(x,y) 8)if "empName" in dis: print("Yes, 'model' is one of the keys in the thisdict dictionary") The popitem() method removes the last inserted item (in versions before 3.7, a random item is removed instead): '''while loop''' 1)i = 1 while i < 6:
  • 27. print(i) i += 1 '''while loop with break''' 2)i = 1 while i < 6: print(i) if i == 3: break i += 1 '''Build in function''' x=abs(12.30) print(x) x=abs(120.3000) print(x) x=abs(-12.3000) print(x) o/p 12.3 120.3 12.3 The all() function returns True if all items in an iterable are true, otherwise it returns False. list=[True,True,True] x=all(list) print(x) list=[True,False,True] x=all(list) print(x)
  • 28. list=[0,10,10] x=all(list) print(x) list=[10,10,10] x=all(list) print(x) o/p True False False True Definition and Usage The any() function returns True if any item in an iterable are true, otherwise it returns False. If the iterable object is empty, the any() function will return False. mylist = [False, True, False] x = any(mylist) print(x) mylist = [0, 10, 20] x = any(mylist) print(x) o/p True True print(math.sqrt(49)) print (pow(3,4)) o/p 9 The bin() function returns the binary version of a specified integer. The result will always start with the prefix 0b. x = bin(36)
  • 29. print(x) o/p 0b100100 x = chr(97) print(x) o/p a The frozenset() function returns an unchangeable frozenset object (which is like a set object, only unchangeable). mylist = ['apple', 'banana', 'cherry'] x = frozenset(mylist) x[1] = "strawberry" print(x) o/p Traceback (most recent call last): File "/home/ctuser01/Desktop/Backup/new Python/BsicProject/basicprograms/ClassAndConstructor.py", line 120, in <module> x[1] = "strawberry" TypeError: 'frozenset' object does not support item assignment 5) import calendar print(calendar.month(1995,5)) bytes operator b=[12,25,255] x=bytes(b) print(x[1]) print(x[2]) print(x[0]) o/p 25 255 12 b=[12,25,258]
  • 30. x=bytes(b) print(x[1]) print(x[2])it will give error because we can add in byte elements from 1 to 256 o/p Traceback (most recent call last): File "/home/ctuser01/Desktop/Backup/new Python/BsicProject/basicprograms/Array.py", line 15, in <module> x=bytes(b) ValueError: bytes must be in range(0, 256) bytes are immutable we cannot modifies the elements for ex: b=[12,25,250] x=bytes(b) print(x[1]) print(x[2]) x[2]=90 print(x[2]) o/p Traceback (most recent call last): File "/home/ctuser01/Desktop/Backup/new Python/BsicProject/basicprograms/Array.py", line 18, in <module> x[2]=90 TypeError: 'bytes' object does not support item assignment bytearray is as same as byte but bytearray is mutable b=[12,25,250] x=bytearray(b) print(x[1]) print(x[2]) x[2]=90 print(x[2])
  • 31. Chapter 3: Class and Constructor 3. Python Concepts: . Object - Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors -wagging, barking, eating. An object is an instance of a class. • Class - A class can be defined as a template/ blue print that describes the behaviors/states that object of its type support. It is a logical costruct. • Methods - A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed. • Instance Variables - Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables. OOPs concepts 1. Inheritance: It is a mechanism where one class can acquire the properties of another class. Using inheritance, a class can inherit the general properties from its parent class and it has to define only its unique properties. This mechanism achieves code reusability. For example, The company manufactures different versions of car but the car is extended from its
  • 32. previous version, so that new features will get added with original features remain same. In technical, java also has several classes which can be extended to add the new functionality and accesssing existing functionality. 2. Polymorphism: Polymorphism means many forms where different actions are performed though one interface. In java polymorphism is achieved through overloading and overriding. For example, If a dog smells cat it will bark and if a dog smells food, it salivates. Here 'smelling' is behaviour but whether to bark or salivate depends on type of parameter passed like cat or food. It is known as compile time polymorphism. Another example, if a new car is replacing some functionality from exising car then, it will be dynamic polymorphism where existing functionality will get replaced with new functionality and by default, new functionality will get accessed. 1. Class: A class is the collection of data members and member functions. It is a blue print from which objects can be constructed. It is just a logical construct. A class can contain fields and methods to describe the state and behaviour of an object respectively. Methods are the members of a class that provide a service for an object or perform some business logic. Current states of a class’s Corresponding object are stored in the object’s instance variables. Methods define the operations that can be performed in python programming. Python is case-sensitive language. That is Python fields and member functions names are case sensitive. class Person: '''constructor''' def __init__(self,name,age): self.name=name self.age=age '''instantiate the person class'''
  • 33. person1=Person("John",30) person2=Person("Neha",35) Constructor: Constructor is a special type of method(function) which is used to initialise the instance members of the class. In python the __init__() method is called the constructor and is always called when object is created. Syntax of constructor declaration. def __init__(self): #body of constructor 2. Object: Object is known as instance of class. Objects actually have their own states and behavour. For example Rectangle objects have their own length, breadth, area and perimeter. Hence the length and breadth are known as instance variables and methods area and perimeter are known as instance methods. Classes are just a logical construct but Objects are actually loaded into memory. Object are physically present. 1)default constructor: The default constructor is simple constructor which doesn't accept any arguments. Its definition has only one argument which is reference to the instance being constructed. i.e self The self parameter is a reference to the class itself, and is used to access variables that belongs to the class. It does not have to be named self , you can call it whatever you like, but it has to be the first parameter of any function in the class. Example of default constructor: class Person: '''default constructor''' def __init__(self): self.name="JOHN" def show(self):
  • 34. print("name of Person is {}".format(self.name)) p=Person() p.show() output: name of Person is john 2)Parametrized constructor: constructor with parameters is known as parametrized constructor. The parametrized constructor The parametrized constructor .The parametrized constructor take its first argument as a reference to the instance being constructed known as self and the rest of the arguments are provided by programmer. Example of parametrized constructor: class Person: '''parameterized constructor''' def __init__(self,name,age): self.name=name self.age=age def show(self): print("name of Person is {} and age of person is {}".format(self.name,self.age)) p=Person("john","30") p.show() output: name of Person is john and age of person is 30 class Employee: '''static variable''' count=0; '''costructor is created''' def __init__(self,id,name,salary): self.id=id self.name=name
  • 35. self.salary=salary Employee.count+=1 '''method is created''' def display(self): print("Name ",self.id," name ",self.name," Salary",self.salary) def displayCount(self): print("Count ",Employee.count) emp=Employee(101,"Ramesh",10000); emp.display() emp.displayCount() emp1=Employee(102,"somesh",12000); emp1.display() emp1.displayCount() Notes:.The variable count is a class variable whose value is shared among all instances of a this class. This can be accessed as Employee.count from inside the class or outside the class.  The first method __init__() is a special method, which is called class constructor or initialization method that Python calls when you create a new instance of this class. The self Parameter The self parameter is a reference to the class itself, and is used to access variables that belongs to the class. It does not have to be named self , you can call it whatever you like, but it has to be the first parameter of any function in the class: Constructor OverLoading class Emp: def __init__(self,id=0,name=None,salary=0,): if id!=0:
  • 36. print("id ",id) if name!=None: print("name ",name) if salary!=0: print("salary ",salary) e=Emp(101); e1=Emp(102,"g") e2=Emp(0,"k") e3=Emp(0,None,10000) o/p id 101 id 102 name g name k salary 10000 ''' mthod verLoading''' class Emp: def my(self,name=None,num=0): self.name=name; self.num=num; def disname(self): print("Name ",self.name) def disNum(self): print("Number ",self.num) e=Emp() e.my("h") e.disname() e1=Emp() e1.my(None,101) e1.disNum()
  • 37. o/p Name h Number 101 Chaptar 4: python variables and Methods Types of variables 1)Instance variables:The variable which we defined inside the method and constructor using self keyword called as instance variable. We can access variable by using instance of class. Scope of instance variable is throughout the class. 2)static variables: The variable which is defined out of the methods and constructor called as static variable and we can access static variable by using class name.The scope of static variable throghout the class. 3)Local variables:-variable which in defined in method and scope of variable is within the method. 4)Global Variable:-Variable which is defined out of the class is called global variable OR by using global keyword within method/constructor. Example for instance variable: class Employee: def __init__(self,name,salary,age): '''instance variable''' self.name=name
  • 38. self.salary=salary self.age=age def show(self): #defining instance variable inside method self.bonus=1000 def display(self): print("Employee Bonus :",self.bonus) e=Employee("John",10000,24) print("Employee Name:",e.name) print("Employee Salary:",e.salary) print("Employee age:",e.age) #we are calling to initialise instance variable e.show() e.display() Eg for Static variables: class Institute: instituteName="Coder" # static variable def __init__(self,stdId,stdName): '''instance variable''' self.stdId=stdId self.stdName=stdName i=Institute(101,"Rahul") print("Institute Name:",Institute.instituteName)#calling static variables print("Id :",i.stdId)# calling instance variables print("Student Name:",i.stdName) eg changing static variables value: class Institute: instituteName="Coder" # static variable def __init__(self): Institute.instituteName="coder technology" def display(self): stdId=10;# Local variable print("Id ",stdId)
  • 39. print("institute name =",Institute.instituteName) i=Institute() print("after changing the name of institute") print(" changed institute name=",Institute.instituteName) i.display() o/p institute name = Coder after changing the name of institute changed institute name = coder technology Id 10 e.g. for Global variables location="India" # defining globel variables class Institute: def display(self): global branch # declaring globel variables branch="vashi" # defining globel variables print("inatitute name squad") print("Location ",location ) print("Branch ",branch) i=Institute() location="India" class Institute_branch: def display(self): branch="Pune" #defining globel variables print("inatitute name coder") print("Location ",location ) print("Branch ",branch) i=Institute() i.display() i1=Institute_branch(); i1.display() print(“Loction ”,location)#we can access globel variables directly Types of Methods:-
  • 40. 1)instance Method 2)class method 3)static method instance method: class InstanceMetodDemo: #we have to give static method decorator to declare method as static def add(self,x,y): print("Price ",x+y) def product(self,x,y): print("The Product",x*y) def average(self,x,y): print("The Average value:",(x+y)/2) S=InstanceMetodDemo() S.add(10,20) S.product(10,20) S.average(10,20) Static Method Eg: class StaticMetodDemo: #we have to give staticmethod decorator to declare method as static @staticmethod def add(x,y): print("Price ",x+y) @staticmethod def product(x,y): print("The Product",x*y) @staticmethod def average(x,y): print("The Average value:",(x+y)/2) StaticMetodDemo.add(10,20) StaticMetodDemo.product(10,20) StaticMetodDemo.average(10,20) ClassMethod Eg:
  • 41. class Test: num=10; def display(self): print("inside instance method") print(Test.num) print(self.num) @staticmethod def displayStatic(): print("inside staticmethod") print(Test.num) @classmethod def displayClassMethod(cls): print("inside @classmethod") print(Test.num) print(cls.num) t=Test() t.display() Test.displayStatic() Test.displayClassMethod()
  • 42. Chapter 5: Getter setter method: class Employee: #private variables are define like this __empId=0 __empName="" __empAge="" __empSalary=0.0 def setEmpId(self,empId): self.__empId=empId #accessing private variables def setEmpName(self,empName): self.__empName=empName def setEmpAge(self,empAge): self.__empAge=empAge def setEmpSalary(self,empSalary): self.__empSalary=empSalary def getEmpId(self): return self.__empId def getEmpName(self): return self.__empName def getEmpSalary(self): return self.__empSalary
  • 43. def getEmpAge(self): return self.__empAge def toGetAllData(self): return "Name ",self.__empName,"Id ",self.__empId,"Salary ",self.__empSalary e=Employee() e.setEmpId(101) e.setEmpName("abc") e.setEmpAge(25) e.setEmpSalary(1000class Employee: __empId=0 __empName="" __empAge="" __empSalary=0.0 def setEmpId(self,empId): self.__empId=empId def setEmpName(self,empName): self.__empName=empName def setEmpAge(self,empAge): self.__empAge=empAge def setEmpSalary(self,empSalary): self.__empSalary=empSalary def getEmpId(self): return self.__empId def getEmpName(self): return self.__empName def getEmpSalary(self): return self.__empSalary def getEmpAge(self): return self.__empAge def toGetAllData(self): return "Name ",self.__empName,"Id ",self.__empId,"Salary ",self.__empSalary
  • 44. e=Employee() e.setEmpId(101) e.setEmpName("abc") e.setEmpAge(25) e.setEmpSalary(1000) print("Id =",e.getEmpId(),"Name=",e.getEmpName()," salary=",e.getEmpSalary()," Age =",e.getEmpAge()) print(e.toGetAllData()) ) print("Id =",e.getEmpId(),"Name=",e.getEmpName()," salary=",e.getEmpSalary()," Age =",e.getEmpAge()) print(e.toGetAllData()) Mini project using list class Book: __bookId=0; __bookName="" __price=0.0 __aname="" def __init__(self,bookId,bookName,price,aname): self.__bookId=bookId self.__bookName=bookName self.__price=price self.__aname=aname def setBookId(self,bookId): self.__bookId=bookId def setBookName(self,bookName): self.__bookName=bookName def setPrice(self,price): self.__price=price def setAname(self,aname): self.__aname=aname
  • 45. def getBookId(self): return self.__bookId def getBookName(self): return self.__bookName def getPrice(self): return self.__price def getAname(self): return self.__aname def getAllData(self): return "Id ",self.__bookId,"Name ",self.__bookName," Price ",self.__price,"Author name ",self.__aname from basicprograms.book import Book class BookProject: blist=[] def excute(self,count): if count==1: bookId=int(input("Enter the id =")); bookName=input("Enter the Name ="); price=float(input("Enter the price =")) aname=input("Enter the author name ="); b=Book(bookId,bookName,price,aname) self.blist.append(b) if count == 2: print('Food are as Follows') for i in range(int(self.blist.__len__())): if self.blist[i] != 'null': print(self.blist[i].getBookId(), end=' ') print(self.blist[i].getBookName(), end=' ') print(self.blist[i].getPrice(), end=' ') print(self.blist[i].getAname(), end=' ') print() if c == 3:
  • 46. n = int(input('Enter the book id which you want to update')); for i in range(int(self.blist.__len__())): if self.blist[i].getBookId() == n: bname = input('Enter the new Bookname : ') aname = input('Enter the new author name : ') price = float(input('Enter the new price : ')) self.blist[i].setBookName(bname); self.blist[i].setAname(aname); self.blist[i].setPrice(price); if c == 4: n = int(input('Enter the book id which you want to delete')); for i in range(int(self.blist.__len__())): if self.blist[i].getBookId() == n: self.blist[i]='null' if c == 5: n = int(input('Enter the book id which you want to search')); for i in range(int(self.blist.__len__())): if self.blist[i].getBookId() == n: print(self.blist[i].getAllData()) while(True): print('Enter your choice') print('1.addFood') print('2.displayFood') print('3.updateFood') print('4.deleteFood') print('5.searchFood') c = int(input('Enter the selected choice : ')) ff = BookProject() ff.excute(c) Chapter 6: Module A module allows you to logically organize your Python code. Grouping related code into a module makes the code easier to understand and use. Simply, a module is a file consisting of Python code. A module can define functions, classes and variables. A module can also include runnable code. You can use any Python source file as a module by executing an import
  • 47. statement in some other Python source file. The import has the following syntax: import module1[, module2[,... moduleN] When the interpreter encounters an import statement, it imports the module if the module is present in the search path. A search path is a list of directories that the interpreter searches before importing a module. For example, to import the module demo.py, you need to put the following command at the top of the script. import demo demo.hello() A module is loaded only once, regardless of the number of times it is imported. For example, to import the function helloworld from the module demo, use the following statement from demo import helloworld helloworld() The from...import * Statement It is also possible to import all names from a module into the current namespace by using the following import statement − It is also possible to import all names from a module into the current namespace by using the following import statement from modname import * This provides an easy way to import all the items from a module into the current namespace; however, this statement should be used sparingly. Locating Modules When you import a module, the Python interpreter searches for the module in the following sequences −  The current directory.  If the module isn't found, Python then searches each directory in the shell variable PYTHONPATH.  If all else fails, Python checks the default path. On UNIX, this default path is normally /usr/local/lib/python/. The module search path is stored in the system module sys as the sys.path variable.
  • 48. Chaptar 7: Inheritance Inheritance is the capability of one class to derive or inherit the properties from some another class. The benefits of inheritance are:
  • 49. 1. It represents real-world relationships well. 2. It provides reusability of a code. We don’t have to write the same code again and again. Also, it allows us to add more features to a class without modifying it. 3. It is transitive in nature, which means that if class B inherits from another class A, then all the subclasses of B would automatically inherit from class A. In inheritance, the child class acquires the properties and can access all the data members and functions defined in the parent class. A child class can also provide its specific implementation to the functions of the parent class syntax: class derived-class(base class): #code What is object class? In Python object is root of all classes. 1)single inheritance: When a child class inherits from only one parent class, it is called as single inheritance. Example: class Person: def __init__(self,name,age): self.name=name self.age=age
  • 50. def show(self): print("name of Person is {} and age of person is {}".format(self.name,self.age)) class Student(Person): def __init__(self,marks,name,age): self.marks=marks self.name=name self.age=age def show(self): print("Name of student is {} age of student is {} marks of student is {}".format(self.name,self.age,self.marks)) s=Student(78,"john",21) s.show() output: Name of student is john age of student is 21 marks of student is 78 2)Multiple inheritance:-When a child class inherits from multiple parent classes, it is called as multiple inheritance. Python supports multiple inheritance. We specify all parent classes as comma separated list in bracket. Example:- '''first base class''' class Development(): '''constructor of Development ''' def __init__(self): print("I am in Development") def show(self): print("Development") '''second base class''' class Testing(): '''constructor of Testing '''
  • 51. def __init__(self): print("I am in Testing") def show(self): print("Testing") '''Multiple inheritance''' class Project(Development,Testing): '''constructor of Project''' def __init__(self): print("I am in project") p=Project() p.show() Output: I am in project Development '''first base class''' class Development(): '''constructor of Development ''' def __init__(self): print("I am in Development") def show(self): print("Development") '''second base class''' class Testing(): '''constructor of Testing ''' def __init__(self): print("I am in Testing") def show(self): print("Testing") '''Multiple inheritance'''
  • 52. class Project(Development,Testing): '''constructor of Project''' def __init__(self): print("I am in project") '''super() lets you avoid referring to the base class explicitly''' super().__init__() p=Project() p.show() output: I am in project I am in Development Development Super: super() lets you avoid referring to the base class explicitly. you can use super to call base class method. '''first base class''' class Development(): '''constructor of Development ''' def __init__(self): print("I am in Development") def show(self): print("Development") '''second base class''' class Testing(): '''constructor of Testing ''' def __init__(self): print("I am in Testing") def show(self): print("Testing") '''Multiple inheritance''' class Project(Development,Testing): '''constructor of Project''' def __init__(self):
  • 53. print("I am in project") Development.__init__() Testing.__init__() Output: I am in project I am in Development I am in Testing Development In above example we have created class Project which has two base classes Development and Testing you want call __init__() method from Development and __init__() method from Testing also then We have to give Development.__init__() Testing.__init__() Multilevel Inheritance: Multi-level inheritance is archived when a derived class inherits another derived class. Example: class Person:
  • 54. def __init__(self,name,age): self.name=name self.age=age def show(self): print("name of Person is {} and age of person is {}".format(self.name,self.age)) class Employee(Person): def __init__(self,name,age,salary): self.salary=salary super().__init__(name, age) def show(self): print("Name of Employee is {} age of Employee is {} salary of Employee is {}".format(self.name,self.age,self.salary)) class Manager(Employee): def __init__(self,name,age,salary,bonus): self.bonus=bonus super().__init__(name,age,salary) def show(self): print("Name of Employee is {} age of Employee is {} salary of Employee is {} Bonus is {}".format(self.name,self.age,self.salary,self.bonus)) s=Manager("John",28,20000,2000) s.show() Output: Name of Employee is John age of Employee is 28 salary of Employee is 20000 Bonus is 2000 Hybrid Inheritance: This form combines more than one form of inheritance. Basically, it is a blend of more than one type of inheritance
  • 55. class Company(): def __init__(self,req): print("I am in company") def _show(self): print("Company") class Development(Company): def __init__(self): print("I am in Development") def show(self): print("Development") class Testing(Company): def __init__(self): print("I am in Testing") def show(self): print("Testing") class Project(Development,Testing): def __init__(self): print("I am in Project") #To get the method resolution order print(Project.__mro__) Output: (<class '__main__.Project'>, <class '__main__.Development'>, <class '__main__.Testing'>, <class '__main__.Company'>, <class 'object'>)
  • 56. To get the method resolution order of a class we can use either __mro__ attribute or mro() method. By using these methods we can display the order in which methods are resolved. class Company(): def __init__(self): print("I am in company") def _show(self): print("Company") class Development(Company): def __init__(self): print("I am in Development") super().__init__() def show(self): print("Development") class Testing(Company): def __init__(self): print("I am in Testing") super().__init__() def show(self): print("Testing") class Project(Development,Testing): def __init__(self): print("I am in Project") super().__init__() p=Project() p.show() #To get the method resolution order print(Project.__mro__) Method Overriding: Method overriding is concept of object oriented programming that allows us to change the implementation of function in the child class that is defined in the parent class.
  • 57. Following conditions must be met for overriding a function: 1. Inheritance should be there. Function overriding cannot be done within a class. We need to derive a child class from a parent class. 2. The function that is redefined in the child class should have the same signature as in the parent class i.e. same number of parameters. Example: class Tv: def show(self): print("TV") class Lcd_Tv: def show(self): print("LCD_TV") tv=Lcd_Tv() tv.show() Output: LCD_TV Has-A-Relationship class Engin: def setEnginNo(self,engNo): self.engNo=engNo def setEnginModel(self,engModel): self.engModel=engModel def getEnginNo(self): return self.engNo def getEnginModel(self): return self.engModel class Car: def setEngin(self,eng): self.eng=eng def setCarName(self,carName): self.carName=carName
  • 58. def setCarPrice(self,carPrice): self.carPrice=carPrice def getEngin(self): return self.eng def getCarName(self): return self.carName def getCarPrice(self): return self.carPrice e=Engin() e.setEnginModel("#1234#") e.setEnginNo("A12345g") c=Car() c.setCarName("Marythi") c.setCarPrice(100000) c.setEngin(e) print("Car Name ",c.getCarName()) print("Car price ",c.getCarPrice()) print("Engin No",c.getEngin().getEnginNo()) print("Engin Model ",c.getEngin().getEnginModel()) Inner classes: class College: class Departmet: def display(self): print("Science department") c=College() d=c.Departmet() d.display()
  • 60. chapter 8 Python – Strings In Python, Strings are arrays of bytes representing Unicode characters. However, Python does not have a character data type, a single character is simply a string with a length of 1. Square brackets can be used to access elements of the string. Creating a String Strings in Python can be created using single quotes or double quotes or even triple quotes. String in single quotes cannot hold any other single quoted character in it otherwise an error arises because the compiler won’t recognize where to start and end the string. To overcome this error, use of double quotes is preferred, because it helps in creation of Strings with single quotes in them. For strings which contain Double quoted words in them, use of triple quotes is suggested. Along with this, triple quotes also allow the creation of multiline strings. # Python Program for # Creation of String # with single Quotes str1 = 'Welcome to the Coder Technologies' print("String with the use of Single Quotes: ") print(str1) # Creating a String # with double Quotes str2 = "I'm learning python" print("nString with the use of Double Quotes: ") print(str2) # Creating a String # with triple Quotes str3 = '''I'm learning python. and I Love "Python Programming"''' print("nString with the use of Triple Quotes: ") print(str3) # Creating String with triple # Quotes allows multiple lines str4 = '''hi how are you? I'm fine! '''
  • 61. print("nCreating a multiline String: ") print(str4) Access characters in a string We can access individual characters using indexing and a range of characters using slicing. Index starts from 0. Trying to access a character out of index range will raise an IndexError. The index must be an integer. We can't use float or other types, this will result into TypeError. Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on. We can access a range of items in a string by using the slicing operator (colon). str = 'Coder Technologies' print('str = ', str) #first character print('str[0] = ', str[0]) #last character print('str[-1] = ', str[-1]) #slicing 2nd to 5th character print('str[1:5] = ', str[1:5]) #slicing 6th to 2nd last character print('str[5:-2] = ', str[5:-2]) Output: str = Coder Technologies str[0] = C str[-1] = s str[1:5] = oder str[5:-2] = Technologi
  • 62. String Operations Concatenation of Two or More Strings Joining of two or more strings into a single one is called concatenation. The + operator does this in Python. Simply writing two string literals together also concatenates them. The * operator can be used to repeat the string for a given number of times. str1 = 'Coder' str2 ='Technologies' # using + print('str1 + str2 = ', str1 + str2) # using * print('str1 * 3 =', str1 * 3) Output: str1 + str2 = CoderTechnologies str1 * 3 = CoderCoderCoder Iterating Through String Using for loop we can iterate through a string. Here is an example to count the number of 'o' in a string. count = 0 for letter in 'Coder Technologies': if(letter == 'o'): count += 1 print(count,'letters found') Output: 3 letters found
  • 63. Built-in functions to Work with Python Various built-in functions that work with sequence, works with string as well. Some of the commonly used ones are enumerate() and len(). The enumerate() function returns an enumerate object. It contains the index and value of all the items in the string as pairs. This can be useful for iteration. Similarly, len() returns the length (number of characters) of the string. str = 'Coder Technologies' # enumerate() list_enumerate = list(enumerate(str)) print('list(enumerate(str) = ', list_enumerate) #character count print('len(str) = ', len(str)) Output: list(enumerate(str) = [(0,'c'),(1,'o'),(2,'d'),(3,'e'),(4,'r')] len(str) = 5 Formatting of Strings Strings in Python can be formatted with the use of format() method which is very versatile and powerful tool for formatting of Strings. Format method in String contains curly braces {} as placeholders which can hold arguments according to position or keyword to specify the order. A string can be left(<), right(>) or center(^) justified with the use of format specifiers, separated by colon(:). Integers such as Binary, hexadecimal, etc. and floats can be rounded or displayed in the exponent form with the use of format specifiers. ''' Created on 14-May-2019 @author: trainerdemo ''' #Python Program for # Formatting of Strings
  • 64. # Default order String1 = "{} {} {} {}".format('Coder', 'Technologies',"At",'Andheri') print("Print String in default order: ") print(String1) # Positional Formatting String1 = "{2} {3} {0} {1}".format('Coder', 'Technologies',"At",'Andheri') print("nPrint String in Positional order: ") print(String1) # Keyword Formatting String1 = "{a} {b} {c}".format(a = 'The', b = 'Coder', c = 'Technologies') print("nPrint String in order of Keywords: ") print(String1) # Formatting of Integers String1 = "{0:b}".format(16) print("nBinary representation of 16 is ") print(String1) # Formatting of Floats String1 = "{0:e}".format(165.6458) print("nExponent representation of 165.6458 is ") print(String1) # Rounding off Integers String1 = "{0:.2f}".format(1/6) print("none-sixth is : ") print(String1) # String alignment String1 = "|{:<10}|{:^10}|{:>10}|".format('I','am ','learning python ') print("nLeft, center and right alignment with Formatting: ") print(String1) Output: Print String in default order: Coder Technologies At Andheri Print String in Positional order:
  • 65. At Andheri Coder Technologies Print String in order of Keywords: The Coder Technologies Binary representation of 16 is 10000 Exponent representation of 165.6458 is 1.656458e+02 one-sixth is : 0.00 Left, center and right alignment with Formatting: |I | am |learning python | Some Method of string with Example: str = 'Coder Technologies' # length of String print("Length is ",len(str)) # convert string in lower case print(" In lower case ",str.lower()) # Covert string in upper case print(" In upper case ",str.upper()) #replace string by other string print(" replace method ",str.replace("o", "O")) #split string in sub string by space print("split method ",str.split(" ")) Output: In lower case coder technologies
  • 66. In upper case CODER TECHNOLOGIES replace method COder TechnOlOgies split method ['Coder', 'Technologies'] String constants Built-In Function Description string.ascii_lett ers Concatenation of the ascii_lowercase and ascii_uppercase constants. string.ascii_low ercase Concatenation of lowercase letters string.ascii_upp ercase Concatenation of uppercase letters string.digits Digit in strings string.hexdigits Hexadigit in strings string.letters concatenation of the strings lowercase and uppercase string.lowercas e A string must contain lowercase letters. string.octdigits Octadigit in a string string.punctuati on ASCII characters having punctuation characters. string.printable String of characters which are printable String.endswith () Returns True if a string ends with the given suffix otherwise returns False String.startswit h() Returns True if a string starts with the given prefix otherwise returns False String.isdigit() Returns “True” if all characters in the string are digits, Otherwise, It returns “False”. String.isalpha() Returns “True” if all characters in the string are alphabets, Otherwise, It returns “False”. string.isdecimal () Returns true if all characters in a string are decimal.
  • 67. str.format() one of the string formatting methods in Python3, which allows multiple substitutions and value formatting. String.index Returns the position of the first occurrence of substring in a string string.uppercas e A string must contain uppercase letters. string.whitespa ce A string containing all characters that are considered whitespace. string.swapcase () Method converts all uppercase characters to lowercase and vice versa of the given string, and returns it replace() returns a copy of the string where all occurrences of a substring is replaced with another substring Chapter 9 Lambda Function: In Python, anonymous function means that a function is without a name. we already know that def keyword is used to define the normal functions and the lambda keyword is used to create anonymous functions. It has the following syntax:
  • 68. lambda arguments: expression  This function can have any number of arguments but only one expression, which is evaluated and returned.  One is free to use lambda functions wherever function objects are required. Let’s look at this example and try to understand the difference between a normal def defined function and lambda function. This is a program that returns the cube of a given value: # Python code to illustrate cube of a number # showing difference between def() and lambda(). def cube(y): return y*y*y; g = lambda x: x*x*x print(g(7)) print(cube(5)) Without using Lambda : Here, both of them returns the cube of a given number. But, while using def, we needed to define a function with a name cube and needed to pass a value to it. After execution, we also needed to return the result from where the function was called using the return keyword. Using Lambda : Lambda definition does not include a “return” statement, it always contains an expression which is returned. We can also put a lambda definition anywhere a function is expected, and we don’t have to assign it to a variable at all. This is the simplicity of lambda functions. Need of Lambda function: The power of lambda is better shown when you use them as an anonymous function inside another function.
  • 69. Say you have a function definition that takes one argument, and that argument will be multiplied with an unknown number. def myfunc(n): return lambda a : a * n mydoubler = myfunc(2) print(mydoubler(11)) Lambda functions can be used along with built-in functions like filter(), map() and reduce(). Filter:-The filter() function in Python takes a function and a list as arguments.it returns new list. Without using Lambdas ages = [5,19,12,24,50,20] def myFunc(x): if x < 18: return False else: return True adults = filter(myFunc,ages) for i in adults: print(i) # Python code to illustrate # filter() with lambda() li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61] final_list = list(filter(lambda x: (x%2 != 0) , li)) print(final_list)
  • 70. Output: [5, 7, 97, 77, 23, 73, 61] map The map() function in Python takes a function and a list as argument. The function is called with a lambda function and a list and a new list is returned which contains all the lambda modified items returned by that function for each item. Example: # Python code to illustrate # map() with lambda() # to get double of a list. li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61] final_list = list(map(lambda x: x*2 , li)) print(final_list) Output: [10, 14, 44, 194, 108, 124, 154, 46, 146, 122] reduce() The reduce() function in Python takes a function and a list as argument. The function is called with a lambda function and a list of new reduced result is returned. This performs a repetitive operation over the pairs of the list. # Python code to illustrate # reduce() with lambda() # to get sum of a list from functools import reduce li = [5, 8, 10, 20, 50, 100] sum = reduce((lambda x, y: x + y), li) print (sum) Output: 193
  • 71. List comprehesion List comprehensions are used for creating new list from another iterables. As list comprehension returns list, they consists of brackets containing the expression which needs to be executed for each element along with the for loop to iterate over each element. Syntax The list comprehension starts with a ’[’ and ’]’ to help you remember that the result is going to be a list. The base syntax is [expression for item in list if conditional] This is equivalent to: for item in list: if condition: expression Lets Break down and what it does new_list=[expression(i) for i in old_list if filter(i)] new_list The new list(result) expression(i) Expression is based on the variable used for each element in the old_list. For i in old_list: it is nothing but iterate trugh list if filter(i) Apply a filter with an if -statement. range The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number. x = range(6) for n in x: print(n) Syntax range(start, stop, step)
  • 72. star t Optional. An integer number specifying at which position to start. Default is 0 sto p Optional. An integer number specifying at which position to end. ste p Optional. An integer number specifying the incrementation. Default is 1 e.g: x = range(3, 6) for n in x: print(n) e.g: x = range(3, 20, 2) for n in x: print(n) output: 3 5 7 9 11 13 15 17 19
  • 73. Chapter 10 Exception Handling Python provides two very important features to handle any unexpected error in your Python programs and to add debugging capabilities in them 1)Exception Handling. Standard Exception Exception:Base class for all exceptions. StopIteration:Raised when the next() method of an iterator does not point to any object. SystemExit:Raised by the sys.exit() function. StandardError :Base class for all built-in exceptions except StopIteration and SystemExit. ArithmeticError: Base class for all errors that occur for numeric calculation. OverflowError Raised when a calculation exceeds maximum limit for a numeric FloatingPointError:- Raised when a floating point calculation fails. ZeroDivisonError:- Raised when division or modulo by zero takes place for all numeric types. AssertionError:- Raised in case of failure of the Assert statement. AttributeError Raised in case of failure of attribute reference or assignment. EOFError: Raised when there is no input from either the raw_input() or input() function and the end of file is reached. importError Raised when an import statement fails. KeyboardInterrupt Raised when the user interrupts program execution, usually by pressing Ctrl+c. LookupError Base class for all lookup errors. IndexError Raised when an index is not found in a sequence. KeyError Raised when the specified key is not found in the dictionary. NameError Raised when an identifier is not found in the local or global namespace. UnboundLocalError Raised when trying to access a local variable in a function or method but no value has been assigned to it. EnvironmentError Base class for all exceptions that occur outside the Python environment. IOError Raised when an input/ output operation fails, such as the print
  • 74. statement or the open() function when trying to open a file that does not exist. OSError Raised for operating system-related errors. SyntaxError Raised when there is an error in Python syntax. IndentationError Raised when indentation is not specified properly. SystemError Raised when the interpreter finds an internal problem, but when this error is encountered the Python interpreter does not exit. SystemExit Raised when Python interpreter is quit by using the sys.exit() function. If not handled in the code, causes the interpreter to exit. Exception: An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions. If you have some suspicious code that may raise an exception, you can defend your program by placing the suspicious code in a try: block. After the try: block, include an except: statement, followed by a block of code which handles the problem as elegantly as possible. Syntax: try: You do your operations here except ExceptionI: If there is ExceptionI, then execute this block. except ExceptionII: If there is ExceptionII, then execute this block. ...................... else: If there is no exception then execute this block. e.g: # Python program to handle simple runtime error a = [1, 2, 3]
  • 75. try: print("Second element = %d" %(a[1])) # Throws error since there are only 3 elements in array print("Fourth element = %d" %(a[3])) except IndexError: print("An error occurred") output: Second element = 2 An error occurred Here are few important points about the above-mentioned syntax- 1)A single try statement can have multiple except statements. This is useful when the try block contains statements that may throw different types of exceptions. 2)You can also provide a generic except clause, which handles any exception. 3)After the except clause(s), you can include an else-clause. The code in the else- block executes if the code in the try: block does not raise an exception. 4)The else-block is a good place for code that does not need the try: block's protection. The except Clause with No Exceptions You can also use the except statement with no exceptions defined as follows- try: You do your operations here ...................... except: If there is any exception, then execute this block. ...................... else: If there is no exception then execute this block. This kind of a try-except statement catches all the exceptions that occur. Using this kind of try-except statement is not considered a good programming practice though, because it catches all exceptions but does not make the programmer identify the root cause of the problem that may occur. Example:
  • 76. try: fh = open("testfile", "w") fh.write("This is my test file for exception handling!!") except IOError: print ("Error: can't find file or read data") else: print ("Written content in the file successfully") fh.close() Output:- Written content in the file successfully Example: try: fh = open("testfile", "r") fh.write("This is my test file for exception handling!!") except IOError: print ("Error: can't find file or read data") else: print ("Written content in the file successfully") Output: Error: can't find file or read data The except Clause with Multiple Exceptions You can also use the same except statement to handle multiple exceptions as follows- try: You do your operations here ...................... except(Exception1[, Exception2[,...ExceptionN]]]): If there is any exception from the given exception list, then execute this block. ...................... else: If there is no exception then execute this block.
  • 77. Example: # Program to handle multiple errors with one except statement try : a = 3 if a < 4 : # throws ZeroDivisionError for a = 3 b = a/(a-3) # throws NameError if a >= 4 print("Value of b = ", b) # note that braces () are necessary here for multiple exceptions except(ZeroDivisionError, NameError): print("nError Occurred and Handled") Output: Error Occurred and Handled The try-finally Clause You can use a finally: block along with a try: block. The finally: block is a place to put any code that must execute, whether the try-block raised an exception or not. The syntax of the try-finally statement is this- try: You do your operations here; ...................... Due to any exception, this may be skipped. finally: This would always be executed. Example: try: fh = open("testfile", "w") fh.write("This is my test file for exception handling!!") finally: print ("Error: can't find file or read data") fh.close() Output:
  • 78. Error: can't find file or read data Argument of an Exception An exception can have an argument, which is a value that gives additional information about the problem. The contents of the argument vary by exception. You capture an exception's argument by supplying a variable in the except clause as follows- try: You do your operations here ...................... except ExceptionType as Argument: You can print value of Argument here... Example: # Define a function here. def temp_convert(var): try: return int(var) except ValueError as Argument: print ("The argument does not contain numbersn", Argument) # Call above function here. temp_convert("xyz") Output: The argument does not contain numbers invalid literal for int() with base 10: 'xyz' User defined exception: Python also allows you to create your own exceptions by deriving classes from the standard built-in exceptions. Example: class MyError(Exception): # Constructor or Initializer def __init__(self, value): self.value = value
  • 79. # __str__ is to print() the value def __str__(self): return(repr(self.value)) try: raise(MyError(3*2)) # Value of Exception is stored in error except MyError as error: print('A New Exception occured: ',error.value) Output: A New Exception occured: 6 The raise statement allows the programmer to force a specific exception to occur.
  • 80. Chapter 11 Multithreading 1. Multithreading Concept: Multithreading is a specialised form of multitasking. Multithreaded program contains two or more parts are running concurrently. Each part is known as thread. 2. Python Thread Model: Process Thread Program in execution Part of a process Heavyweight Lightweight Each process has its own address space Threads shares the address space Multiprocessing: More overhead Multithreading: Less overhead Interprocess communication is expensive Inter thread communication is less expensive Context switching requires high cost Context switching requires low cost Example: downloading files along with listening music Example: in editor, character printing along with formatting 3. Thread States: 1. New A thread is said to be in new state when we created the thread instance, but we have not yet called start() on the thread newly created thread instance. Even though it is a live thread object, it is not a thread of execution. At this state, thread is not active. 2. Runnable / Ready In the Runnable state a thread is eligible to run, however the Thread Scheduler not selects the thread to start its execution. A thread will get into Runnable state after we call start() method. Also a thread can come back to Runnable state from other states like sleeping, waiting or blocked states. The important point to remember is that, once we call start() method on any thread instance, the thread will move to Runnable state which makes the thread eligible to run. The Thread
  • 81. Scheduler may ormay not have picked the thread to run. 3. Running Once the Thread Scheduler selects a thread to run from the runnable thread pool, the thread starts execution. This is the state we call a thread is in Running state and thread becomes thread of execution. 4. Waiting If any thread is waiting for any shared resource then it will call wait method. It will come out of wait when either timer expires or it will get notification by some other thread. 5. Sleeping Thread can go to sleep state if its execution is paused for some period by calling sleep method. 6. Blocked: Thread will go to blocked state if is waiting for I/O. e.g. User Input. When I/O get completed, it will come out of this state and goes to ready state. 7. Suspended If thread is suspended for some period then it will go to suspended state. It will come out of this state when it gets resumed or timer expires. From all these states the thread becomes eligible to run again, however Thread Scheduler ultimately decides which runnable thread becomes thread of execution.
  • 82. 8. Dead A thread is considered dead once its run() method completed execution. Although a thread’s run() method completed execution it is still a Thread object, but this Thread object is not a thread of execution. Once the thread completes its run() method and dead, it cannot be brought back to thread of execution or even to runnable state. Invoking start() method on a dead thread causes runtime exception. A thread is not eligible to run if it is in waiting, sleeping or blocked state. But the thread is alive,and it is not in runnable state. A thread can transition back to runnable state when particular event occurs. Create the thread with out using any class Methods 1)current_thread:− Returns the number of thread objects in the caller's thread control. 2)setName() − The setName() method sets the name of a thread. 3)getName() − The getName() method returns the name of a thread. 4)start():-The start() method starts a thread by calling the run method. 5)run() − The run() method is the entry point for a thread. 6)join([time]) − The join() waits for threads to terminate. 7)sleep():-The method sleep() suspends execution for the given number of seconds 1)Creating thread without class from threading import * def display(): print("child thread") t=Thread(target=display) t.start() o/p child thread
  • 83. 2)Current_thread from threading import * def display(): print("child thread") print(current_thread().getName())#this mthoe is use to get current thread information t=Thread(target=display) t.setName("abc") t.start() 3) from threading import * import time def display(): for i in range(5): print("child thread") print(current_thread().getName())#this mthoe is use to get current thread information time.sleep(1) t=Thread(target=display) t.setName("abc") t.start() Creating thread by extending Thread class 4) from threading import * import time class Mythread(Thread): def run(self): for i in range(5): print("child thread") print(current_thread().getName())#this mthoe is use to get current thread information time.sleep(1)
  • 84. m=Mythread() m.setName("Ramesh") m.start() 5) class Mythread(Thread): def run(self): for i in range(5): print("child thread") print(current_thread().getName())#this mthoe is use to get current thread information time.sleep(1) m=Mythread() m.setName("Ramesh") m.start() m=Mythread() m.setName("sameer") m.start() o/p child thread Ramesh child thread sameer child thread Ramesh child thread sameer child thread Ramesh child thread sameer child thread Ramesh child thread sameer child thread Ramesh child thread sameer
  • 85. join Method eg: 6) from threading import * import time class Mythread(Thread): def run(self): for i in range(5): print("child thread") print(current_thread().getName())#this mthoe is use to get current thread information time.sleep(1) m=Mythread() m.setName("Ramesh") m.start() m.join() m=Mythread() m.setName("sameer") m.start() m.join() child thread Ramesh child thread Ramesh child thread Ramesh child thread Ramesh child thread Ramesh child thread sameer child thread sameer child thread sameer child thread sameer
  • 86. child thread sameer 7)creating thread without extending thread class class Mythread: def m(self): for i in range(5): print("child thread") print(current_thread().getName())#this mthoe is use to get current thread information time.sleep(1) mythread=Mythread() t=Thread(target=mythread.m) t.setName("Ramesh") t.start() mythread1=Mythread() t1=Thread(target=mythread1.m) t1.setName("Ramesh") t1.start() o/p child thread Rameshaccording to Objects.equals(Object, Object). child thread Seetha child thread Ramesh child thread Seetha child thread Ramesh child thread Seetha child thread Ramesh child thread Seetha child thread Ramesh
  • 87. child thread Seetha Chapter 12 File Handling what is file? Suppose you have stored data in dictionary d={} d[‘name’]=”python” After execution of program data is lost means this is temporary storage suppose you want to store data permanently Then use File.File is used to store small amount of data permanently. Their are two types of file: 1)Text file 2)Binary File 1)Text file:-Text file is used to store character data.e.g abc.txt 2)Binary file:- To store binary data.e.g.Images, videos,audio ,zip files clips these are Binary File. Need of File :-file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files. open()-Open is inbuilt function used to open file syntax: open(filepath,file_mode) e.g open(“file.txt”,’r’) The allowed values of mode for text file are: r:-Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.
  • 88. W:-Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing. a:-Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing. r+: -Opens a file for both reading and writing. The file pointer placed at the beginning of the file. w+-Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing. a+:-Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing. The allowed values of mode for binary file are: rb:-Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode wb:-Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing. rb+:-Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of the file. Wb+:-Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing. ab:-Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing. ab+:-Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing. File Atribute: Once a file is opened and you have one file object, you can get various information related to that file. Here is a list of all attributes related to file object − 1)file.closed Returns true if file is closed, false otherwise. 2)file.mode
  • 89. Returns access mode with which file was opened. 3)file.name Returns name of the file. Example: fo = open("foo.txt", "wb") print("Name of the file: ",fo.name) print("Closed or not : ", fo.closed) print("Opening mode : ", fo.mode) Output: Name of the file: foo.txt Closed or not : False Opening mode : wb Name of the file: foo.txt Closed or not : False Opening mode : wb Close:- The close() method of a file object flushes any unwritten information and closes the file object, after which no more writing can be done. Python automatically closes a file when the reference object of a file is reassigned to another file. It is a good practice to use the close() method to close a file. 1)r -read mode example Example: f=open("file.txt","r") data=f.read() print(data) f.close()fo = open("foo.txt", "r+") data = fo.read(10); print("Read String is : ", data) # Close opend file fo.close() Output: hello world File handling
  • 90. 2)w-write mode example f=open("file.txt","w") data=f.write("line1") 3)r+:- fo = open("file.txt", "r+") data = fo.read(11); print("Read String is : ", data) # Close opend file fo.close() output:- Read String is : hello world 4)w+:- fo = open("file.txt", "w+") data = fo.read(11); print("Read String is : ", data) # Close opend file fo.close() Output:- Read String is : 5)a:-append mode fo = open("file.txt", "a") fo.write("welcome") # Close opend file fo.close() 6)a+:- fo = open("file.txt", "a+") fo.write("welcome") data=fo.read(30) print(data) # Close opend file fo.close() f.readline()-The method readline()reads one entire line from the file. Example:- fo = open("file.txt", "r+") data=fo.readline() print(data) data=fo.readline() print(data)
  • 91. data=fo.readline() print(data) data=fo.readline() print(data) data=fo.readline() print(data) # Close opend file fo.close() Output:- line1 line2 line3 line4 line5 f.readlines()-The method readlines() reads until EOF using readline() and returns a list containing the lines. . fo = open("file.txt", "r+") data=fo.readlines() print(data) # Close opend file fo.close() Output:- ['line1n', 'line2n', 'line3n', 'line4n', 'line5n'] File Positions: The tell() method tells you the current position within the file; in other words, the next read or write will occur at that many bytes from the beginning of the file. The seek(offset[, from]) method changes the current file position. The offset argument indicates the number of bytes to be moved. The from argument specifies the reference position from where the bytes are to be moved. If from is set to 0, it means use the beginning of the file as the reference position
  • 92. and 1 means use the current position as the reference position and if it is set to 2 then the end of the file would be taken as the reference position. Example: fo = open("foo.txt", "r+") st = fo.read(10); print("Read String is : ", st) # Check current position position = fo.tell(); print("Current file position : ", position) # Reposition pointer at the beginning once again position = fo.seek(0, 0); st = fo.read(10); print("Again read String is : ", st) # Close opend file fo.close() Output: Read String is : python is Current file position : 9 Again read String is : python is Finding file path , directory name import os print(“File Name ”, __file__) print(“Absolute Path ”, os.path.abspath(__file__)) print(“Dir Name ” , os.path.dirname(os.path.abspath(__file__))) BASE_DIR=os.path.dirname(os.path.abspath(__file__)) print(BASE_DIR) TEMPLATE_DIR=os.path.join(BASE_DIR,’templates’)
  • 93. Chapter 13 : SQL(Structured Query Language) Database: 1.1 Introduction to SQL: SQL is a language which is used to operate your database. SQL is the basic language used for all the databases. There are minor syntax changes amongst different databases, but the basic SQL syntax remains largely the same. SQL is a short abbreviation of Structured Query Language. According to ANSI (American National Standards Institute), SQL is the standard language to operate a relational database management system. SQL is used in the accessing, updating, and manipulation of data in a database. Its design allows for the management of data in an RDBMS, such as MYSQL. SQL language also used for controlling data access and for creation and modification of Database schemas. 1.2 What is MYSQL? Developed in the mid-90s., MySQL was one of the first open-source database available in the market. Today there are many alternatives variants of MySQL,. However, the differences between the variants are not significant as they use the same syntax, and basic functionality also remains same. MySQL is an RDBMS that allows keeping the data that exists in a database organized. MySQL is pronounced as "My S-Q-L," but it is also called "My Sequel." It is named after co-founder Michael Widenius' daughter. MySQL provides a multi-user access to databases. This RDBMS system is used with the combination of PHP and Apache Web Server, on top of a Linux distribution. MySQL uses the SQL language to query the database. 1.3 MySQL Data Types: 1. Numeric Types: Numeric Datatypes allow both signed and unsigned integers. MySQL supports the following numeric data types. Data Type Description TINYINT(size) Allows signed integers -128 to 127 and 0 to 255 unsigned integers.
  • 94. SMALLINT(size) Allows signed integers from -32768 to 32767 and 0 to 65535 unsigned integers. MEDIUMINT(size) Allows signed integers from -8388608 to 8388607 and 0 to 16777215 unsigned integers. INT(size) Allows signed integers from -2147483638 to 214747483637 and 0 to 4294967925 unsigned integers. BIGINT(size) Allows signed integers from -9223372036854775808 to 9223372036854775807 and 0 to 18446744073709551615 unsigned integers. FLOAT(size,d) Allows small numbers with floating decimal point. The size parameter is used to specify the maximum number of digits, and the d parameter is used to specify the maximum number of digits to the right of the decimal. 2. String data types: Data type Description CHAR(size) A FIXED length string (can contain letters, numbers, and special characters). The size parameter specifies the column length in characters - can be from 0 to 255. Default is 1 VARCHAR(size) A VARIABLE length string (can contain letters, numbers, and special characters). The size parameter specifies the maximum column length in characters - can be from 0 to 65535 BINARY(size) Equal to CHAR(), but stores binary byte strings. The size parameter specifies the column length in bytes. Default is 1 VARBINARY(size) Equal to VARCHAR(), but stores binary byte strings. The size parameter specifies the maximum column length in bytes. TINYBLOB For BLOBs (Binary Large OBjects). Max length: 255 bytes TINYTEXT Holds a string with a maximum length of 255 characters TEXT(size) Holds a string with a maximum length of 65,535 bytes BLOB(size) For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data MEDIUMTEXT Holds a string with a maximum length of 16,777,215 characters MEDIUMBLOB For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of data LONGTEXT Holds a string with a maximum length of 4,294,967,295 characters LONGBLOB For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295 bytes of data ENUM(val1, val2, val3, ...) A string object that can have only one value, chosen from a list of possible values. You can list up to 65535 values in an ENUM list. If a value is inserted that is not in the list, a blank value will be inserted. The values are sorted in the order you enter them SET(val1, val2, val3, ...) A string object that can have 0 or more values, chosen from a list of possible values. You can list up to 64 values in a SET list
  • 95. 3. Date and Time data types: Data type Description DATE A date. Format: YYYY-MM-DD. The supported range is from '1000- 01-01' to '9999-12-31' DATETIME(fsp) A date and time combination. Format: YYYY-MM-DD hh:mm:ss. The supported range is from '1000-01-01 00:00:00' to '9999-12-31 23:59:59'. Adding DEFAULT and ON UPDATE in the column definition to get automatic initialization and updating to the current date and time TIMESTAMP(fsp) A timestamp. TIMESTAMP values are stored as the number of seconds since the Unix epoch ('1970-01-01 00:00:00' UTC). Format: YYYY-MM-DD hh:mm:ss. The supported range is from '1970-01-01 00:00:01' UTC to '2038-01-09 03:14:07' UTC. Automatic initialization and updating to the current date and time can be specified using DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP in the column definition TIME(fsp) A time. Format: hh:mm:ss. The supported range is from '-838:59:59' to '838:59:59' YEAR A year in four-digit format. Values allowed in four-digit format: 1901 to 2155, and 0000. MySQL 8.0 does not support year in two-digit format. 1.4 Type of SQL Commands: 1. DDL (Data Definition Language): Command Statements are used in this are Create Alter, Rename, Truncate, Drop. 2. DML (Data Manipulation Language): Command Statements are used in this are Insert, Update, Delete. 3. DQL (Data Query Language): Command Statements are used in this are Select. 4. TCL (Transaction Control Language): -Command Statements are used in this are Commit, Rollback, Savepoint. 5. DCL (Data Control Language): Command Statements are used in this are Grant, Revoke.
  • 96. 1.5 Important SQL Commands Let’s see in details Most Important SQL Commands used in Database Management System to perform multiple Operations Create Database Statement Create database statement is used to Create New Database. CREATE DATABASE database_name; Example: CREATE DATABASE testdb; Create Table Statement Create Table statement is used to Create New Table in Database before create any table or performing any Operation we should select database using USE Command. USE database_name; CREATE TABLE table_name ( column_name1 data_type (size), column_name2 data_type (size), column_name3 data_type (size), .... ); The column_name parameters specify the names of the columns of the table. The data_type parameter specifies what type of data the column can hold (e.g. varchar, integer, decimal, date, etc.). The size parameter specifies the maximum length of the column of the table. Example: CREATE TABLE suppliers ( supplier_id int(10), supplier_name varchar(50) , contact_name varchar(50) ); Alter Table Statement Alter table statement is used to alter (modify) table structure by add, delete, modify Column and change Column name Also. Syntax to ADD New Columns: ALTER TABLE table_name ADD (column_name1 datatype, column_name2 datatype); Example: ALTER TABLE suppliers ADD (city varchar(30), state varchar(30));
  • 97. Syntax to MODIFY Exiting Column: ALTER TABLE table_name MODIFY column_name new_datatype(new size) [Constraint Names]; Example: ALTER TABLE suppliers MODIFY supplier_name varchar(100) NOT NULL Syntax to DROP Exiting Column: ALTER TABLE table_name DROP column_name; Example: ALTER TABLE suppliers DROP state; Syntax to CHANGE Exiting Column Name: ALTER TABLE table_name CHANGE old_column_name new_column_name datatype(size) [Constraint Names]; Example: ALTER TABLE suppliers CHANGE contact_name contact_number varchar(50) NOT NULL; Rename Table Statement Syntax to CHANGE Exiting Table Name RENAME TABLE old_tbl_name TO new_tbl_name; Example: RENAME TABLE suppliers TO suppliersdetails; Truncate Table Statement Syntax to Truncate Table Name TRUNCATE TABLE table_name; Example: TRUNCATE TABLE suppliersdetails;
  • 98. Drop Table Statement Syntax to Drop Table Name DROP TABLE table_name; Example: DROP TABLE suppliersdetails; The SQL INSERT INTO Statement The INSERT INTO statement is used to insert new records in a table. It is possible to write the INSERT INTO statement in two forms. The first form does not specify the column names where the data will be inserted, only their values: SQL INSERT INTO Syntax INSERT INTO table_name (column name list) VALUES (value1, value2, value3...); Example: INSERT INTO suppliers (supplier_id, supplier_name) VALUES (24553, 'IBM'); The SQL SELECT Statement The SELECT statement is used to select data from a database. The result is stored in a result table, called the result-set. SQL SELECT Syntax SELECT column_name,column_name FROM table_name; And SELECT * FROM table_name; Example: SELECT supplier_name, city, state FROM suppliers The SQL WHERE Clause The WHERE clause is used to extract only those records that fulfill a specified criterion. SQL WHERE Syntax SELECT column_name,column_name FROM table_name WHERE column_name operator value; Operators in The WHERE Clause
  • 99. The following operators can be used in the WHERE clause: Name Description = Equal operator !=, <> Not equal operator > Greater than operator >= Greater than or equal operator < Less than operator <= Less than or equal operator LIKE Simple pattern matching NOT LIKE Negation of simple pattern matching RLIKE Whether string matches regular expression BETWEEN ... AND ... Check whether a value is within a range of values NOT BETWEEN ... AND ... Check whether a value is not within a range of values IS Test a value against a boolean IS NOT Test a value against a boolean IS NOT NULL NOT NULL value test IS NULL NULL value test NOT, ! Negates value AND && Logical AND OR, || Logical OR The SQL AND & OR Operators The AND operator displays a record if both the first condition AND the second condition are true. The OR operator displays a record if either the first condition OR the second condition is true. SELECT ID, NAME, SALARY FROM CUSTOMERS WHERE SALARY > 2000 AND age < 25; Following is an example, which would fetch ID, Name and Salary fields from the CUSTOMERS table where salary is greater than 2000 AND age is less tan 25 years. SELECT ID, NAME, SALARY FROM CUSTOMERS WHERE SALARY > 2000 OR age < 25; Following is an example, which would fetch ID, Name and Salary fields from the CUSTOMERS table where salary is greater than 2000 OR age is less tan 25 years. SQL LIKE Operator: The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.
  • 100. SELECT column_name(s) FROM table_name WHERE column_name LIKE pattern; Wildcard’s Used In Like Operator: SQL Wildcard Characters In SQL, wildcard characters are used with the SQL LIKE operator. SQL wildcards are used to search for data within a table. With SQL, the wildcards are: Wildcar d Explanation % Allows you to match any string of any length (including zero length) _ Allows you to match on a single character SELECT employeeNumber, lastName, firstName FROM employees WHERE firstName LIKE 'a%'; MySQL scans the whole employees table to find employee whose first name starts with character a and followed by any number of characters. To search for employee whose last name ends with on e.g., Patterson, Thompson, you can use the % wildcard at the beginning of the pattern as the following query: SELECT employeeNumber, lastName, firstName FROM employees WHERE lastName LIKE '%on'; To find all employees whose last names contain on string, you use the following query with pattern %on% SELECT employeeNumber, lastName, firstName FROM employees WHERE lastname LIKE '%on%'; SQL LIKE with underscore( _ ) wildcard To find employee whose first name starts with T, ends with m and contains any single character between e.g., Tom , Tim, you use the underscore wildcard to construct the pattern as follows: SELECT employeeNumber, lastName, firstName FROM employees WHERE firstname LIKE 'T_m'; The [charlist] WILDCARDS are used to represent any single character within a charlist. To get all rows from the table 'agents' with following condition - the 'agent_name' must begin with the letter 'a' or 'b' or 'i' the following sql statement can be
  • 101. used : SELECT* FROM agents WHERE agent_name RLIKE '^[abi]'; The [charlist] WILDCARDS are used to represent any single character within a charlist. To get all rows from the table 'agents' with following condition - the 'agent_name' must end with the letter 'a' or 'b' or 'i' the following sql statement can be used : SELECT* FROM agents WHERE agent_name RLIKE '[abi]$'; The [charlist] WILDCARDS are used to represent any single character within a charlist. To get all rows from the table 'agents' with following condition - the 'agent_name' containing with the letter 'a' or 'b' or 'i' the following sql statement can be used : SELECT* FROM agents WHERE agent_name RLIKE '[abi]'; SQL Aliases: SQL aliases are used to temporarily rename a table or a column heading. SELECT column_name AS alias_name FROM table_name;
  • 102. Example: SELECT CustomerName AS Customer, ContactName AS [Contact Person] FROM Customers; SELECT CustomerName, Address+', '+City+', '+PostalCode+', '+Country AS Address FROM Customers; SELECT CustomerName, CONCAT(Address,', ',City,', ',PostalCode,', ',Country) AS Address FROM Customers; Aliases can be useful when:  There are more than one table involved in a query  Functions are used in the query  Column names are big or not very readable  Two or more columns are combined together Alias Example for Tables The following SQL statement selects all the orders from the customer with CustomerID=4 (Around the Horn). We use the "Customers" and "Orders" tables, and give them the table aliases of "c" and "o" respectively (Here we have used aliases to make the SQL shorter): Example: SELECT o.OrderID, o.OrderDate, c.CustomerName FROM Customers AS c, Orders AS o WHERE c.CustomerName="Around the Horn" AND c.CustomerID=o.CustomerID; 5.SQL Joins: SQL joins are used to combine rows from two or more tables,based on a common field between them. SQL INNER JOIN (simple join). An SQL INNER JOIN return all rows from multiple tables where the join condition is met. Syntax:
  • 103. SELECT column_name(s) FROM table1 INNER JOIN table2 ON table1.column_name=table2.column_name; Example: SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate FROM Orders INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID; SQL LEFT JOIN Keyword The LEFT JOIN keyword returns all rows from the left table (table1), with the matching rows in the right table (table2). The result is NULL in the right side when there is no match. SQL LEFT JOIN Syntax SELECT column_name(s) FROM table1 LEFT JOIN table2 ON table1.column_name=table2.column_name; Example: SELECT OrderNumber, TotalAmount, FirstName, LastName, City, Country FROM Customer C LEFT JOIN [Order] O ON O.CustomerId = C.Id SQL RIGHT JOIN : The RIGHT JOIN keyword returns all rows from the right table (table2), with the matching rows in the left table (table1). The result is NULL in the left side when there is no match. SQL RIGHT JOIN Syntax SELECT column_name(s) FROM table1 RIGHT JOIN table2 ON table1.column_name=table2.column_name;
  • 104. Example: SELECT OrderNumber, TotalAmount, FirstName, LastName, City, Country FROM Customer C RIGHT JOIN [Order] O ON O.CustomerId = C.Id; SQL FULL OUTER JOIN Keyword The FULL OUTER JOIN keyword returns all rows from the left table (table1) and from the right table (table2).The FULL OUTER JOIN keyword combines the result of both LEFT and RIGHT joins. Syntax: SELECT column_name(s) FROM table1 FULL OUTER JOIN table2 ON table1.column_name=table2.column_name; Example: SELECT OrderNumber, TotalAmount, FirstName, LastName, City, Country FROM Customer C FULL OUTER JOIN [Order] O ON O.CustomerId = C.Id; SELF JOIN: It is used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the SQL statement.Self-joins are used to compare values in a column with other values in the same column in the same table. Example:
  • 105. In the EMPLOYEE table displayed above, emp_id is the primary key. emp_supv is the foreign key (this is the supervisor’s employee id). If we want a list of employees and the names of their supervisors, we’ll have to JOIN the EMPLOYEE table to itself to get this list. Unary relationship to employee How the employees are related to themselves :  An employee may report to another employee (supervisor).  An employee may supervise himself (i.e. zero) to many employee (subordinates). We have the following data into the table EMPLOYEE. The above
  • 106. data shows :  Unnath Nayar's supervisor is Vijes Setthi  Anant Kumar and Vinod Rathor can also report to Vijes Setthi.  Rakesh Patel and Mukesh Singh are under supervison of Unnith Nayar. In the following example we will use the table EMPLOYEE twice and in order to do this we will use the alias of the table. To get the list of employees and their supervisor the following sql statement has used : SELECT a.emp_id AS "Emp_ID",a.emp_name AS "Employee Name", b.emp_id AS "Supervisor ID",b.emp_name AS "Supervisor Name" FROM employee a, employee b WHERE a.emp_supv = b.emp_id; Output: CARTESIAN (CROSS)JOIN:  Returns the Cartesian product of the sets of records from the two or more joined tables.  The size of a Cartesian product result set is the number of rows in the first table multiplied by the number of rows in the second table. Example: Table 1: GameScores PlayerName DepartmentId Scores Jason 1 3000 Irene 1 1500 Jane 2 1000 David 2 2500 Paul 3 2000 James 3 2000 Table 2: Departments DepartmentId DepartmentName 1 IT 2 Marketing 3 HR SELECT* FROM GameScores CROSS JOIN Departments;
  • 107. Result: PlayerNam e DepartmentI d Scores DepartmentI d DepartmentNam e Jason 1 3000 1 IT Irene 1 1500 1 IT Jane 2 1000 1 IT David 2 2500 1 IT Paul 3 2000 1 IT James 3 2000 1 IT Jason 1 3000 2 Marketing Irene 1 1500 2 Marketing Jane 2 1000 2 Marketing David 2 2500 2 Marketing Paul 3 2000 2 Marketing James 3 3000 2 Marketing Jason 1 3000 3 HR Irene 1 1500 3 HR
  • 109. Jane 2 1000 3 HR David 2 2500 3 HR Paul 3 2000 3 HR James 3 3000 3 HR 6.SQL Constraints: SQL constraints are used to specify rules for the data in a table. Constraints can be specified when the table is created (inside the CREATE TABLE statement) or after the table is created (inside the ALTER TABLE statement). SQL CREATE TABLE + CONSTRAINT Syntax CREATE TABLE table_name ( column_name1 data_type(size) constraint_name, column_name2 data_type(size) constraint_name, column_name3 data_type(size) constraint_name, .... ); Constraints in SQL: Constraints are rules and restrictions applied on a column of a table so that invalid data can't be inserted into tables. Its ensures the accuracy and reliability of the data in the database. Constraints can be specified in two ways- when the table is created with CREATE TABLE statement after the table is created with the ALTER TABLE statement Different types of constraints : 1) NOT NULL 2) UNIQUE 3) PRIMARY KEY 4) DEFAULT 5) CHECK 6) FOREIGN KEY In SQL, we have the following constraints: SQL NOT NULL Constraint: The NOT NULL constraint enforces a column to NOT accept NULL values. The NOT NULL constraint enforces a field to always contain a value. This means that you cannot insert a new record, or update a record without adding a value to this field.
  • 110. Example: SELECT LastName,FirstName,Address FROM Persons WHERE Address IS NOT NULL. SQL UNIQUE Constraint  The UNIQUE constraint uniquely identifies each record in a database table.  The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a column or set of columns.  A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it.  Note that you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.
  • 111. Example: CREATE TABLE supplier ( supplier_id numeric(10) NOT NULL, supplier_name varchar2(50) NOT NULL, contact_name varchar2(50), CONSTRAINT supplier_unique UNIQUE (supplier_id) ); SQL PRIMARY KEY Constraint  The PRIMARY KEY constraint uniquely identifies each record in a database table.  Primary keys must contain UNIQUE values.  A primary key column cannot contain NULL values.  Most tables should have a primary key, and each table can have only ONE primary key. Example: CREATE TABLE employees ( employee_id INT PRIMARY KEY, last_name VARCHAR(50) NOT NULL, first_name VARCHAR(50) NOT NULL, salary MONEY ); SQL FOREIGN KEY Constraint A FOREIGN KEY in one table points to a PRIMARY KEY in another table. Example: CREATE TABLE products product_id numeric(10) not null, supplier_id numeric(10) not null, CONSTRAINT fk_supplier FOREIGN KEY (supplier_id) REFERENCES supplier(supplier_id) ); SQL CHECK Constraint
  • 112.  The CHECK constraint is used to limit the value range that can be placed in a column.
  • 113.  If you define a CHECK constraint on a single column it allows only certain values for this column.  If you define a CHECK constraint on a table it can limit the values in certain columns based on values in other columns in the row.  Example: CREATE TABLE employees employee_id INT NOT NULL, last_name VARCHAR(50) NOT NULL, first_name VARCHAR(50), salary MONEY, CONSTRAINT check_salary CHECK (salary > 0) ); SQL DEFAULT Constraint The DEFAULT constraint is used to insert a default value into a column. The default value will be added to all new records, if no other value is specified. Example: CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) DEFAULT 'Sandnes' ) SQL UNION Operator 1. The SQL UNION operator combines the result of two or more SELECT statements. 2. Notice that each SELECT statement within the UNION must have the same number of columns. 3. The columns must also have similar data types. Also, the columns in each SELECT statement must be in the same order. 4. Example: SELECT City FROM Customers UNION
  • 114. SELECT City FROM Suppliers 1. To allow duplicate values, use the ALL keyword with UNION. SELECT City FROM Customers UNION ALL SELECT City FROM Suppliers SQL ORDER BY Keyword  The ORDER BY keyword is used to sort the result-set.  The ORDER BY keyword sorts the records in ascending order by default. To sort the records in a descending order, you can use the DESC keyword. Example: SELECT supplier_city FROM suppliers WHERE supplier_name = 'IBM' ORDER BY supplier_city; SQL Functions: SQL Aggregate Functions SQL aggregate functions return a single value, calculated from values in a column. Useful aggregate functions:  AVG() - Returns the average value  COUNT()- Returns the number of rows  FIRST() - Returns the first value  LAST() - Returns the last value  MAX() - Returns the largest value  MIN() - Returns the smallest value  SUM() - Returns the sum SQL Scalar functions SQL scalar functions return a single value, based on the input value. Useful scalar functions:
  • 115. UCASE() - Converts a field to upper case LCASE() - Converts a field to lower case MID() - Extract characters from a text field LENGTH() - Returns the length of a text field ROUND() - Rounds a numeric field to the number of decimals specified NOW() - Returns the current system date and time FORMAT() - Formats how a field is to be displayed SQL GROUP BY Statement The GROUP BY statement is used in conjunction with the aggregate functions to group the result- set by one or more columns. Example: SELECT department, SUM(sales) AS "Total sales" FROM order_details GROUP BY department; The HAVING Clause The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate functions. SELECT department, SUM(sales) AS "Total sales" FROM order_details GROUP BY department HAVING SUM(sales) > 1000; SQL Procedure procedure or in simple a proc is a named PL/SQL block which performs one or more specific task. This is similar to a procedure in other programming languages. procedure has a header and a body. The header consists of the name of the procedure and the parameters or variables passed to the procedure. The body consists or declaration section, execution section and exception section similar to a general PL/SQL Block. procedure is similar to an anonymous PL/SQL Block but it is named for repeated usage. Procedures: Passing Parameters We can pass parameters to procedures in three ways. IN-parameters OUT-parameters IN OUT-parameters A procedure may or may not return any value.
  • 116. General Syntax to create a procedure is: CREATE PROCEDURE proc_name ( list of parameters) BEGIN [ DECLARE VARIABLENAME DATATYPE ] Execution section END; How to execute a Procedure? TO Execute procedure call Procedure_name( list of value if any); Example: defining procedure DELIMITER $ CREATE PROCEDURE insertIntoStudent(studid int ,studname varchar(20), studage int) BEGIN INSERT INTO student (studid,studname,studage) values (studid,studname,studage); END; $ calling procedure CALL insertIntoStudent(10,’Raj’,21); SQL Functions Functions in MySQL always return a value. Thus defining a return type and returning a value is must for functions CREATE Function function_name ( list of parameters) RETURNS datatype BEGIN [ DECLARE VARIABLENAME DATATYPE ] Execution section RETURN value; END;
  • 117. calling a function: select function_name(parameters); Example: defining a function DELIMITER $ Create Function square(num int) returns int declare sqr int; set sqr=num*num; return sqr; END; $ calling a functiona select square(5); SQL Triggers: A trigger is a pl/sql block structure which is fired when a DML statements like Insert, Delete, Update is executed on a database table. A trigger is triggered automatically when an associated DML statement is executed. Delimiter $ CREATE TRIGGER trigger_name {BEFORE | AFTER } {INSERT | UPDATE | DELETE} ON table_name [FOR EACH ROW] BEGIN sql query END; $ EXAMPLE: CREATE TRIGGER addEmp after insert on EMPLOYEE for each row begin insert into EmpBackup values(new.empid,new.empname,new.deptName); end;
  • 118. $ QUERY to be executed: insert into EMPLOYEE values(101,’Amit’,’IT’); Chapter 14 : Python Database Connectivity What is MySQLdb? MySQLdb is an interface for connecting to a MySQL database server from Python There are the following steps to connect a python application to our database. • Import pymysql • Create the connection object. • Create the cursor object • Execute the query Creating the connection To create a connection between the MySQL database and the python application, the connect() method of pymsql.connect module is used. Pass the database details like HostName, username, and the database password in the method call. The method returns the connection object. The syntax to use the connect() is given below. Connection-Object=pymysql.connector.connect(host=<host-name>,user=<username>,passwd=<password>)
  • 119. Performing CRUD operations on Employee table
  • 120. Chapter 15 Tkinter Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter outputs the fastest and easiest way to create the GUI applications. Creating a GUI using tkinter is an easy task. To create a tkinter: Importing the module – tkinter Create the main window (container) Add any number of widgets to the main window Apply the event Trigger on the widgets *Importing tkinter is same as importing any other module in the python code. import tkinter There are two main methods used you the user need to remember while creating the Python application with GUI. 1.Tk(screenName=None, baseName=None, className=’Tk’, useTk=1): To create a main window, tkinter offers a method ‘Tk(screenName=None, baseName=None, className=’Tk’, useTk=1)’. To change the name of the window, you can change the className to the desired one. The basic code used to create the main window of the application is: 2.mainloop(): There is a method known by the name mainloop() is used when you are ready for the application to run. mainloop() is an infinite loop used to run the application, wait for an event to occur and process the event till the window is not closed.
  • 121. Example: #import tkinter module import tkinter #create parent window or main window of application m = tkinter.Tk() ''' widgets are added here ''' #mainloop method that runs your application m.mainloop() There are number of widgets which you can put in your tkinter application. 1.Button:To add button in your application the general syntax is: w=Button(master,option=value) master is the parameter used to represent the parent window There are number of options which are used to change the format of the buttons.Number of options can be passed as parameters separated by comma. 1.activebackground:to set the background color when button is under the cursor. 2.activeforeground:to set foreground color when button is under the cursor 3.bg:-to set the background color 4.coomand:-to call function 5.font:-To set the font on the button label 6.image:-set image on button 7.fg:-to set font color of button 8.width:-To set width of button 9.height:-to set height of button 10.text:-set title/text of button Example import tkinter as tk #to create frame/window r=t.Tk() #set the title of frame/window r.title(‘Counting seconds’) #create Button button=tk.Button(r,text=’stop’,width=25,command=r.destroy) #Placing button in parent window Button.pack() r.mainloop() 2.canvas: It is used to draw pictures and other complex layout like graphics, text and widgets.
  • 122. Syntax: w=canvas(master,option=value) there are number of options are used to change the format of the widgets.Number of options can be passed as parameters separated by comma. 1.bd:-to set the border width in pixels 2.bg:-to set the normal background colour 3.cursor:to set the cursor used in canvas. 4.highlightcolor:-to set the color shown in the focus highlight. 5.width:-to set width of the widget 6.height:-to set height of the widget Example: from tkinter import * master=Tk() w=Canvas(master,width=40,height=60) w.pack() canvas_height=20 canvas_width=200 y=int(canvas_height/2) w.create_line(0,y,canvas_width,y) master.mainloop() 6.Label: IIt refers to the display box where you can put any text or image which can be updated any time as per the code. The general syntax is: w=Label(master, option=value) master is the parameter used to represent the parent window. There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below. bg: to set he normal background color. bg to set he normal background color. command: to call a function. font: to set the font on the button label. image: to set the image on the button. width: to set the width of the button. height” to set the height of the button.
  • 123. Example:- from tkinter import * root = Tk() w = Label(root, text='GeeksForGeeks.org!') w.pack() root.mainloop() 4)checkButton:-To select any number of options by displaying number of options by displaying number of option to user as toggle buttons.The general syntax is: w=checkbutton(master,option=value) Options are: 1.Title:to set title of widget 2.activebackground:to set the background color when widget is under the cursor 2.activeforeground:to set the foreground color when widget is under cursor 3.bg:-to set the normal bqackground color 4.command:to call function 5.font:to set font on button label 6.To set image on the widget from tkinter import * master=Tk() var1=IntVar() checkbutton(master,text=’male’,variable=var1).grid(row=0,sticky=W) var2=IntVar() checkbutton(master,text=’female’,variable=var2).grid(row=1,sticky=W) master.mainloop() 5.)Entry:It is used to input the single line text entry from user.for multiline text input,text widget is used.The syntax is: w=Entry(master,option=value) master represents the parent window. Options are 1.bd:-to set the border width in pixels 2.bg:-to set the normal background colour 3.cursor:to set the cursor used. 4.command:-to call function 5.highlightcolor:-to set the color shown in the focus highlight. 6.width:-to set width of the widget 7.height:-to set height of the widget Example:
  • 124. from tkinter import * master=TK() Label(master,text=”First Name”).grid(row=0) Label(master,text=”Last Name”).grid(row=1) e1=Entry(master) e2=Entry(master) e1.grid(row=0,column=1) e1.grid(row=1,column=1) master.mainloop() 6.Frame:It acts as a container to hold the widgets.It is used for grouping and organizing the widgets. Their are number of options are used to change the format of widget. Number of options can be passed as parameters separated by comma.some of them are listed. 1.bd:-to set the border width in pixels 2.bg:-to set the normal background colour 3.cursor:to set the cursor used. 4.command:-to call function 5.highlightcolor:-to set the color shown in the focus highlight. 6.width:-to set width of the widget 7.height:-to set height of the widget Example: from tkinter import * root = Tk() frame = Frame(root) frame.pack() bottomframe = Frame(root) bottomframe.pack( side = BOTTOM ) redbutton = Button(frame, text = 'Red', fg ='red') redbutton.pack( side = LEFT) greenbutton = Button(frame, text = 'Brown', fg='brown') greenbutton.pack( side = LEFT ) bluebutton = Button(frame, text ='Blue', fg ='blue') bluebutton.pack( side = LEFT ) blackbutton = Button(bottomframe, text ='Black', fg ='black') blackbutton.pack( side = BOTTOM) root.mainloop() 7. Listbox: It offers a list to the user from which the user can accept any number of options. The general syntax is: w = Listbox(master, option=value)
  • 125. master is the parameter used to represent the parent window. There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.  highlightcolor: To set the color of the focus highlight when widget has to be focused.  bg: to set he normal background color.  bd: to set the border width in pixels.  font: to set the font on the button label.  image: to set the image on the widget.  width: to set the width of the widget.  height: to set the height of the widget. Example from tkinter import * top = Tk() Lb = Listbox(top) Lb.insert(1, 'Python') Lb.insert(2, 'Java') Lb.insert(3, 'C++') Lb.insert(4, 'Any other') Lb.pack() top.mainloop() 8. MenuButton: It is a part of top-down menu which stays on the window all the time. Every menubutton has its own functionality. The general syntax is: w = MenuButton(master, option=value) master is the parameter used to represent the parent window. There are number of options which are used to change the format of the widget. Number of options can be can be passed as parameters separated by commas. Some of them are listed below.  activebackground: To set the background when mouse is over the widget.  activeforeground: To set the foreground when mouse is over the widget.  bg: to set he normal background color.  bd: to set the size of border around the indicator.  cursor: To appear the cursor when the mouse over the menubutton.  image: to set the image on the widget.
  • 126.  width: to set the width of the widget.  height: to set the height of the widget.  highlightcolor: To set the color of the focus highlight when widget has to be focused. top = Tk() mb = Menubutton ( top, text = "condiments", relief = RAISED ) mb.grid() mb.menu = Menu ( mb, tearoff = 0 ) mb["menu"] = mb.menu mayoVar = IntVar() ketchVar = IntVar() mb.menu.add_checkbutton ( label = "mayo", variable = mayoVar ) mb.menu.add_checkbutton ( label = "ketchup", variable = ketchVar ) mb.pack() top.mainloop() 9. Menu: It is used to create all kinds of menus used by the application. The general syntax is: w = Menu(master, option=value) master is the parameter used to represent the parent window. There are number of options which are used to change the format of this widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.  title: To set the title of the widget.  activebackground: to set the background color when widget is under the cursor.  activeforeground: to set the foreground color when widget is under the cursor.  bg: to set he normal background color.  command: to call a function.
  • 127.  font: to set the font on the button label.  image: to set the image on the widget. from tkinter import * root = Tk() menu = Menu(root) root.config(menu=menu) filemenu = Menu(menu) menu.add_cascade(label='File', menu=filemenu) filemenu.add_command(label='New') filemenu.add_command(label='Open...') filemenu.add_separator() filemenu.add_command(label='Exit', command=root.quit) helpmenu = Menu(menu) menu.add_cascade(label='Help', menu=helpmenu) helpmenu.add_command(label='About') mainloop() Message: It refers to the multi-line and non-editable text. It works same as that of Label. The general syntax is: w = Message(master, option=value) master is the parameter used to represent the parent window. There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.  bd: to set the border around the indicator.  bg: to set he normal background color.  font: to set the font on the button label.  image: to set the image on the widget.  width: to set the width of the widget.  height: to set the height of the widget. from tkinter import * main = Tk() ourMessage ='This is our Message' messageVar = Message(main, text = ourMessage) messageVar.config(bg='lightgreen') messageVar.pack( )
  • 128. main.mainloop( ) 10. RadioButton: It is used to offer multi-choice option to the user. It offers several options to the user and the user has to choose one option. The general syntax is: w = RadioButton(master, option=value) There are number of options which are used to change the format of this widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.  activebackground: to set the background color when widget is under the cursor.  activeforeground: to set the foreground color when widget is under the cursor.  bg: to set he normal background color.  command: to call a function.  font: to set the font on the button label.  image: to set the image on the widget.  width: to set the width of the label in characters.  height: to set the height of the label in characters. from tkinter import * root = Tk() v = IntVar() Radiobutton(root, text='GfG', variable=v, value=1).pack(anchor=W) Radiobutton(root, text='MIT', variable=v, value=2).pack(anchor=W) mainloop() Scale: It is used to provide a graphical slider that allows to select any value from that scale. The general syntax is: w = Scale(master, option=value) master is the parameter used to represent the parent window. There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.  cursor: To change the cursor pattern when the mouse is over the widget.  activebackground: To set the background of the widget when mouse is over the widget.  bg: to set he normal background color.
  • 129.  orient: Set it to HORIZONTAL or VERTICAL according to the requirement.  from_: To set the value of one end of the scale range.  to: To set the value of the other end of the scale range.  image: to set the image on the widget.  width: to set the width of the widget. from tkinter import * master = Tk() w = Scale(master, from_=0, to=42) w.pack() w = Scale(master, from_=0, to=200, orient=HORIZONTAL) w.pack() mainloop() 11. Scrollbar: It refers to the slide controller which will be used to implement listed widgets. The general syntax is: w = Scrollbar(master, option=value) master is the parameter used to represent the parent window. There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.  width: to set the width of the widget. width: to set the width of the widget.  activebackground: To set the background when mouse is over the widget.  bg: to set he normal background color.  bd: to set the size of border around the indicator.  cursor: To appear the cursor when the mouse over the menubutton.  activebackground: To set the background when mouse is over the widget. from tkinter import * root = Tk() scrollbar = Scrollbar(root) scrollbar.pack( side = RIGHT, fill = Y ) mylist = Listbox(root, yscrollcommand = scrollbar.set ) for line in range(100): mylist.insert(END, 'This is line number' + str(line)) mylist.pack( side = LEFT, fill = BOTH ) scrollbar.config( command = mylist.yview ) mainloop()
  • 130. Text: To edit a multi-line text and format the way it has to be displayed. The general syntax is: w =Text(master, option=value) There are number of options which are used to change the format of the text. Number of options can be passed as parameters separated by commas. Some of them are listed below.  highlightcolor: To set the color of the focus highlight when widget has to be focused.  insertbackground: To set the background of the widget.  bg: to set he normal background color.  font: to set the font on the button label.  image: to set the image on the widget.  width: to set the width of the widget.  height: to set the height of the widget. from tkinter import * root = Tk() T = Text(root, height=2, width=30) T.pack() T.insert(END, 'GeeksforGeeksnBEST WEBSITEn') mainloop() 12)TopLevel: This widget is directly controlled by the window manager. It don’t need any parent window to work on.The general syntax is: w = TopLevel(master, option=value) There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.  bg: to set he normal background color.  bd: to set the size of border around the indicator.  cursor: To appear the cursor when the mouse over the menubutton.  width: to set the width of the widget.  height: to set the height of the widget. from tkinter import * root = Tk() root.title('GfG') top = Toplevel() top.title('Python') top.mainloop() 13.SpinBox: It is an entry of ‘Entry’ widget. Here, value can be input by selecting a fixed value of numbers.The general syntax is:
  • 131. w = SpinBox(master, option=value) There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.  bg: to set he normal background color.  bd: to set the size of border around the indicator.  cursor: To appear the cursor when the mouse over the menubutton.  command: To call a function.  width: to set the width of the widget.  activebackground: To set the background when mouse is over the widget.  disabledbackground: To disable the background when mouse is over the widget.  from_: To set the value of one end of the range.  to: To set the value of the other end of the range. from tkinter import * master = Tk() w = Spinbox(master, from_ = 0, to = 10) w.pack() mainloop() 14. PannedWindow:It is a container widget which is used to handle number of panes arranged in it. The general syntax is: w = PannedWindow(master, option=value) master is the parameter used to represent the parent window. There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.  bg: to set he normal background color.  bd: to set the size of border around the indicator.  cursor: To appear the cursor when the mouse over the menubutton.  width: to set the width of the widget.  height: to set the height of the widget. from tkinter import * m1 = PanedWindow() m1.pack(fill = BOTH, expand = 1) left = Entry(m1, bd = 5) m1.add(left)
  • 132. m2 = PanedWindow(m1, orient = VERTICAL) m1.add(m2) top = Scale( m2, orient = HORIZONTAL) m2.add(top) mainloop()