Python_Programming_Notes
Python_Programming_Notes
Chapter 1
Introduction to Python
Python is a general purpose, dynamic, high level, interpreted, interactive, and
scripting, object oriented programming language.
It is simple and easy to learn and provides lots of high-level data structures.
----------------------------------------------------------------------------------------------
Python Evolution/History
▪ The implementation of Python was started in the December 1989 by Guido Van
Rossum in Netherland
▪ He was a ducth Scientist/programmer.
▪ Python is derived from ABC programming language, which is a general-purpose
programming language that had been developed at the CWI.
▪ Rossum chose the name "Python", since he was a big fan of Monty Python's Flying
Circus.
-----------------------------------------------------------------------------------------------
Python Versions
Python programming language is updated regularly with new features. Python has
mainly 3 versions, they are 1,2 and 3 sub versions are
▪ 1989------------- implementation started
▪ 1991------------- labeled version 0.9.0
▪ 1994------------- Python 1.0 – lambda, map, reduce and filter
▪ 2000------------- Python 2.0 – list, garbage, collection system etc..
▪ 2001------------- Pyhton 2.1
▪ 2008------------- Python 3.0 [also called “Py3k”] – It was designed to rectify
fundamental flaw of the language.
▪ 2016------------- Python 3.6
▪ 2017------------- Python 3.6.4 Latest Version
Built-in breakpoint()
Data classes
Context variables
Python 3.8 October 2019 Assignment Expression
Positional-only parameters
Parallel filesystem cache for compiled bytecode
files
Python 3.9 October 2020 Dictionary Merge & Update Operators
- Current New removeprefix() and removesuffix() string
Version methods
Builtin Generic Types
-----------------------------------------------------------------------------------------------
Features of Python
▪ Simple & Easy to learn:
– Python is a simple and minimalistic language. Reading a good Python program
feels almost like reading English language.
– Python has an extraordinarily simple syntax and simple program structure.
▪ Portable & Platform independent:
– Due to its open-source nature, Python has been ported to (i.e. changed to make
it work on) many platforms.
– Using a Python Virtual Machine (PVM), anybody can run these byte code
instructions on any computer system. Hence, Python programs are not
dependent on any specific operating system.
– All your Python programs can work on any platforms without requiring any
changes at all if you are careful enough to avoid any system-dependent features.
▪ Object-Oriented Language:
– Python supports object-oriented language and concepts of classes and objects
come into existence.
– It supports inheritance, polymorphism, and encapsulation, etc.
– The object-oriented procedure helps to programmer to write reusable code and
develop applications in less code.
▪ Interpreted Language:
– Python converts the source code into an intermediate form called byte codes and
then translates this into the native language of your computer using PVM(Is s
interpreter) and then runs it.
▪ High level language:
– When you write programs in Python, you never need to bother about the low-
level details such as managing the memory used by your program, etc.
▪ Open Source:
– There is no need to pay for Python software.
– It can be free downloaded from www.python.org website. Its source can be read,
modified and used in programs as desired by the programmers.
▪ GUI Programming Support:
– Graphical User Interface is used for the developing Desktop application.
– PyQT5, Tkinter, Kivy are the libraries which are used for developing the web
application.
– It provides a vast range of libraries for the various fields such as machine
learning, web developer, and also for the scripting.
– There are various machine learning libraries, such as Tensor flow, Pandas,
Numpy, Keras, and Pytorch, etc. Django, flask, pyramids are the popular
framework for Python web development.
▪ Scripting language:
– Python is considered as scripting language as it is interpreted and it is used on
the Internet to support other software.
▪ Database connectivity:
– Python provides interface to connect its programs to all major databases like
Oracle, Sybase or MySQL.
----------------------------------------------------------------------------------------------
Applications
▪ GUI based desktop applications (Games, Scientific Applications)
▪ Web frameworks and applications
▪ Enterprise and Business applications
▪ Operating Systems
▪ Language Development
▪ Prototyping
----------------------------------------------------------------------------------------------
Interpreter
▪ An interpreter is a program that reads and executes code. This includes source code,
pre-compiled code, and scripts.
▪ Interpreters and compilers are similar, since they both recognize and process source
code; a compiler simply converts the source code into machine code, which can be
run directly by the operating system as an executable program.
▪ Interpreters bypass the compilation process and execute the code directly.
▪ Interpreters are commonly installed on Web servers, which allow developers to run
executable scripts within their webpages. These scripts can be easily edited and
saved without the need to recompile the code.
------------------------------------------------------------------------------------------------
Python shell
▪ Python provides a Python Shell, which is used to execute a single Python command
and display the result.
▪ It is also known as REPL (Read, Evaluate, Print, Loop), where it reads the command,
evaluates the command, prints the result, and loop it back to read the command
again.
▪ Python shell is like a window, which gives you access to the Python interactive mode.
▪ It also has a file editor that lets you create and edit existing Python source files.
----------------------
Python Interpreter is a program which translates your code into machine language and
then executes it line by line.
We can use Python Interpreter in two modes:
➢ Interactive Mode.
➢ Script Mode.
Interactive Mode:
• Python interpreter in interactive mode is commonly known as Python Shell.
• In Interactive Mode, Python interpreter waits for you to enter command. When you
type the command, Python interpreter goes ahead and executes the command, and
then it waits again for your next command.
To start the Python Shell enter the following command in terminal or command prompt:
Script Mode:
▪ In Script mode, Python Interpreter runs a program from the source file.
▪ Python Shell is great for testing small chunks of code but there is one problem – the
statements you enter in the Python shell are not saved anywhere.
▪ In case, you want to execute same set of statements multiple times you would be
better off to save the entire code in a file. Then, use the Python interpreter in script
mode to execute the code from a file.
Create a new file named first.pyand following code to it:
Save the file. all Python programs have .py extension and Run/execute
---------------------------------------------------------------------------------------------
Indentation
▪ Indentation refers to the ‘whitespaces at the beginning of a code line’.
▪ Python uses indentation to indicate a block of code. This means that statements
which go together must have the same indentation.
▪ Where in other programming languages the indentation in code is for readability
only, the indentation in Python is very important.
▪ Leading whitespace (spaces and tabs) at the beginning of the logical line is used to
determine the indentation level of the logical line, which in turn is used to determine
the grouping of statements.
Example:
if 5 > 2:
print("Five is greater than two!")
Identifiers:
▪ Identifier is the name given to various program elements like variables, function,
arrays, classes, strings etc.,
▪ The Python identifiers follow the following rules:
o The Name should begin with an alphabet.
o Only alphabets, digits and underscores are permitted.
o Distinguish between uppercase and lowercase alphabets.
o Keywords should not be used as identifiers.
o No blank space between the identifiers.
Comments:
▪ Comments are non-executable statements.
▪ Comments are text notes added to the program to provide explanatory information
about the source code.
▪ Python supports two types of comments:
o Single Lined Comment
Keywords:
▪ The keywords have predefined meaning assigned by the Python Complier.
▪ The keywords are also called as reserved word.
▪ All keywords are written in lower case alphabets.
▪ The Python keywords are:
and del for lambda true
as elif from not try
assert else global or while
break except if pass with
class exec import print yield
continue false in raise
def finally is return
Data types:
A data type represents the type of data stored into a variable or memory.
There are 4 different data types are:
▪ Numeric type
▪ Sequences
▪ Sets
▪ Dictionary(Mappings)
▪ The int data type represents positive or negative whole numbers (without
fraction or decimal).
▪ In Python there is no limit to how long an integer value can be.
▪ Example. a=10 b=-10
type() function:
We can use the type() function to know which class a variable or a value
belongs to
Example
a=5
print(a, "is of type", type(a))
b = 2.0
print(a, "is of type", type(b))
Output:
5 is of type <class 'int'>
2.0 is of type <class 'float'>
2. Sequences:
▪ A sequence represents a group of items or elements.
▪ There are several types of sequences in Python, few important sequences as follows,
o str
o list
o tuple
Example
str=”tumkur”
print(str) # it display - tumkur
print(str[0]) # it display -t
print(str[2:4]) # it display 2nd to 4th character
print(str[-1]) # it display first character from end – r
Example
list=[10,3.5,-20,'python','tumkur']
print(list) # It display all elements in the list
output:
[10,3.5,-20, 'python','tumkur']
print(list[0]) # it display 10
print(list[1:3]) # it display 3.5, -20
list[1]=1.5 # replace 1st location element by 1.5
Example
tpl=(10,3.5,-20,'python','tumkur')
print(tpl)
output:
(10,3.5,-20, 'python','tumkur')
print(tpl[0]) # it display 10
print(tpl[1:3]) # it display 3.5, -20
tpl[1]=1.5 # replace 1st location element by 1.5 Display an error message -
“tuple does not support this assignment, tuples are immutable.
3. Sets:
▪ Set is an unordered collection of unique items and un-indexed.
▪ The order of elements is not maintained in the sets.
▪ A set does not accept duplicate elements.
▪ Set is defined by values separated by comma inside braces { }.
▪ There are two sub types in sets:
o Set data type
o Frozen set data type
output: {10,5,30,50}
In the above example, it displays un-orderly and repeated elements only once, because
set is unordered collection and unique items.
4. Dictionary:
▪ A dictionary is an unordered collection, changeable and indexed.
▪ In Python dictionaries are written with curly brackets, and they have keys and
values.
▪ That means dictionary contains pair of elements such that first element represents
the key and the next one becomes its value.
▪ The key and value should be separated by a colon(:) and every pair should be
separated by comma.
▪ All the elements should be enclosed inside curly brackets.
Example
d={1:12,2:'hi',3:"hi"}
print(d) # prints {1: 12, 2: 'hi', 3: 'hi'}
Here, d is the name of dictionary. 1 is the key and its associated value is 12. The next
is 2 and its value is ‘hi’ and so on.
Literals:
Literal is a raw data given in a variable or constant. In Python, there are various
types of literals they are as follows:
Numeric Literals :
Numeric Literals are immutable (unchangeable). Numeric literals can belong to 3
different numerical types Integer, Float and Complex.
Example:
a=5 # integer literal
b=2.5 # float literal
c=3.5j # complex literal
String literals :
A string literal is a sequence of characters surrounded by quotes. We can use
both - single, double or triple quotes for a string. Character literal is a single character
surrounded by single or double quotes.
Example:
a=’s’
Boolean literals :
A Boolean literal can have any of the two values: True or False.
Example:
x=true
Y=false
Special literals:
Python contains one special literal i.e. None. We use it to specify to that field
that is not created.
Example:
k=none
-----------------------------------------------------------------------------------------------
Operators
▪ Operators are special symbols that are used to perform operations on operands.
▪ Python supports different types of operators,
o Arithmetic Operators.
o Relational Operators.
o Assignment Operators.
o Logical Operators.
o Membership Operators.
o Identity Operators.
o Bitwise Operators.
Arithmetic operator:
These are the operators which are used to perform arithmetic operations,
10-5
- Subtraction
5
5*6
* Multiplication
30
7/3
/ Division
2.333
5%2
% Remainder / Modulo
1
2**3
** Exponentiation
8
7 // 3
// Integer Division
2
Relati
onal operator:
These are the operators which are used to perform comparison,
Logical operator:
These are the operators which are used to perform combining two or more expressions,
Assignment operator:
These are the operators which are used to perform assigning values to variables,
Symbol Description Example-1
Assigned values from right
= x=10
side operands
to left variable. 10
Multiple Assignment:
Python allows us to assign a value to multiple variables in a single statement
which is also known as multiple assignment.
We can apply multiple assignments in two ways,
Assigning single value to multiple variables:
x=y=z=50
Assigning multiple values to multiple variables:
a,b,c=2,3,4
Membership operators:
Identity operator:
Identity operators compare the memory locations of two objects.
There are two Identity operators are:
X=10 x=[1,2,3]
is
Y=10 y=[1,2,3]
Returns True if two variables
point to the same object and X is Y x is y
False, otherwise
true false
X=10 x=[1,2,3]
is not
Y=10 y=[1,2,3]
Returns False if two variables
point to the same object and X is not Y x is not y
True, otherwise
false true
---------------------------------------------------------------------------------------------
String Operations
1. Extract specified character from the string.
Get the character at position 1 (remember that the first character has the position 0):
a= "Hello,Python!"
print(a[6]) # it display : P
2. Substring:
Extract number of character from the specified position. Get the characters from
position 2 to position 5 (not included):
b= "Hello,Python!"
print(b[6:8]) # it display : Ph
3. strip():
The strip() method removes any whitespace from the beginning or the end of the
given string.
a= " Hello,Python! "
4. len():
The len() method returns the length of a given string
a= " Python"
print(len(a)) # it display : 6
5. lower():
The lower() method returns the given string in lower case.
a= " PYTHON"
print(a.lower()) # it display : python
6. upper():
The upper() method returns the given string in upper case.
a= " python"
print(a.upper()) # it display : PYTHON
7. replace():
The replace() method replaces a given string with another string
a= "FOR"
print(a.replace(“O”, “A”)) # it display : FAR
8. split():
The split() method splits the string into substrings if it finds instances of the separator
a= "Hello,Python!"
print(a.split(‘,’)) # it display :[‘Hello’,‘Python’]
9. capitalize():
It is used to capitalize letter the 1st character of a string.
txt="welcome"
x=txt.capitalize()
print(x) # it display : Welcome
10. count():
This function searches the substring in the given string and returns how many times
the substring is present in it.
string = "Python is awesome, isn't it?"
substring = "is"
count = string.count(substring)
print(count) # it display : 2
11. isalpha():
It returns true, when all the characters in the string and alphabet otherwise false.
str1="welcome"
print(str1.isalpha()) # it display : True
13. isdigit():
It returns true when all character in the string is digit otherwise false.
s = "28212"
print(s.isdigit()) # it display : True
14. islower():
It returns true when all the character are lower case otherwise false of a string.
str1="welcome";
print(str1.islower()) # it display : True
str2="ABC"
print(str2.islower()) # it display : False
15. isupper():
It return true when all the character of a string are in uppercase otherwise false.
str1="welcome";
print(str1. isupper()) # it display : False
str2="ABC"
print(str2. isupper()) # it display : True
-----------------------------------------------------------------------------------------
Ternary Operator
▪ Ternary operator is also called as conditional operator.
▪ It operates on 3 data elements.
▪ It was added to Python in version 2.5.
▪ It simply allows testing a condition in a single line replacing the multiline if-else
making the code compact.
Syntax: var = [true statement] if(condition) else [flase statement]
Example:
a=12
b=10
big=a if(a>b) else b
print(big)
-----------------------------------------------------------------------------------------
Difference between,
C Python
An Imperative programming model is An object-oriented programming model is
basically followed by C. basically followed by Python.
Variables are declared in C. Python has no declaration.
C doesn’t have native OOP. Python has OOP which is a part of language.
No pointers functionality is available in
Pointers are available in C language.
Python.
C is a compiled language. Python is an interpreted language.
There is a limited number of built-in There is a large library of built-in functions
functions available in C. in Python.
Implementation of data structures It is easy to implement data structures in
requires its functions to be explicitly Python with built-in insert, append
implemented. functions.
C is compiled direct to machine code Python is firstly compiled to a byte-code and
which is executed directly by the CPU then it is interpreted by a large C program.
Declaring of variable type in C is There is no need to declare a type of
necessary condition. variable in Python.
C does not have complex data
Python has some complex data structures.
structures.
C is statically typed. Python is dynamically typed.
Syntax of C is harder than python
It is easy to learn, write and read Python
because of which programmers prefer
programs than C.
to use python instead of C
C programs are saved with .c Python programs are saved by .py
extension. extension.
Assignment gives an error in line. For
An assignment is allowed in a line.
example, a=5 gives an error in python.
In C language testing and debugging In Python, testing and debugging is not
is harder. harder than C.
C is complex than Python. Python is much easier than C.
Java Python
Pure Object-Oriented Programming Both Object-Oriented and Procedure-Oriented
Language programming language
Java programs are verbose. Python programs are concise and compact.
Declaration of variable is compulsory Type declaration is NOT required.
Type discipline is static and weak Type discipline is dynamic and string
It has while, for and do-while loops It has while and for loops
It has switch-case statement It does not have switch-case statement
The variable in for loop does not The variable in the for loop incremented
incremented automatically. automatically.
Memory allocation and de-allocation Memory allocation and de-allocation is done
is automatically by PVM.
automatically by JVM
It supports single and multi dimensional It supports only single dimensional array.
arrays Implement multi dimensional array we should
The array index should be positive Array index can be positive and negative
integer. integer. Negative index represents location
from the end of the array.
Indentation of statements in not Indentation is required to represents a block
necessary of statements.
A semicolon is used to terminate the New line indicates end of the statements and
statements and comma is used to semicolon is used as an expression separator.
separate expressions / variables.
The collection objects like stack, linked The collection objects like lists and
list or vector but not primitive data dictionaries can store objects of
types like int, any type including
float, char etc., numbers and lists.
Chapter 2
Syntax:
print(“expression”/constant/variable)
Example:
print(“hello”) # it display hello
print(10) # it display 10
a=5
print('The value of a is', a) # it display The value of a is 5
Syntax:
▪ If prompt is present, it is displayed on monitor, after which the user can provide
data from keyboard.
▪ Input takes whatever is typed from the keyboard and evaluates it.
▪ As the input provided is evaluated, it expects valid python expression.
▪ If the input provided is not correct then either syntax error or exception is raised by
python.
Example
x=input(“Enter data‟)
-------------------------------------------------------------------------------------------
CONTROL STATEMENTS
▪ Generally execution of program takes place sequentially sometimes we need to skip
some statements and repeat some statements, that time we switch to the control
statement.
▪ Control statements define the direction or flow in which execution of a program
should take place.
SEQUENCE:
▪ It is the order in which the statements are executed one after the other from top to
bottom direction or left to right direction.
▪ By default all programming logics are sequence.
Example:
p = int(input("Enter the principle amount: "))
r = float(input("Enter the rate of interest: "))
t = int(input("Enter the time period: "))
si = (p * r * t) / 100
print("\nSimple interest:", si)
-----------------------
SELECTION OR BRANCHING.
Branching statements are decision making statement, are used to select one path
based on the result of the evaluated expression.
Python If Statements
▪ The Python if statement is a statement which is used to test specified condition.
▪ We can use if statement to perform conditional operations in our Python application.
▪ The if statement executes only when specified condition is true.
▪ We can pass any valid expression into the if parentheses.
There are various types of if statements in Python:
➢ If statement
➢ If-else statement
➢ Elif statement
➢ Nested if statement
if statement:
▪ The if statement is the simplest form of selection statement.
▪ It is very frequently used in decision making and altering the flow of execution of
the program.
Syntax:
if (condition) :
Statement-1
Example:
a=10
if (a==10):
print("the value of a is 10")
If the values of the variable a is 10 then only the print statement gets executed.
Otherwise, it is skipped.
If Else Statements
▪ The If statement is used to test specified condition and if the condition is true, if
block executes, otherwise else block executes.
▪ The else statement executes when the if statement is false.
Syntax:
if (condition) :
Statement-block-1
else :
Statement-block-2
ELIF statement
▪ The elif is short for else if. It allows us to check for multiple expressions.
▪ If the condition for if is False, it checks the condition of the next elif block and so on.
▪ If all the conditions are False, the body of else is executed.
▪ Only one block among the several if...elif...else blocks is executed according to the
condition.
▪ The if block can have only one else block. But it can have multiple elif blocks.
Syntax:
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
Example program
'''In this program, we input a number check if the number is positive or negative or zero
and display an appropriate message This time we use nested if statement'''
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
--------------------------------------------
3. LOOPING OR ITERATION
Syntax:
while expression:
statements
Example program,
n = int(input("Enter a number: "))
while i <= n:
fact *= i
i += 1
print("\nFactorial of", n, "is:", fact)
The for loop in Python is used to iterate the statements or a part of the program
several times.
It is frequently used to traverse the data structures like list, tuple, or dictionary.
Syntax
for iterating_var in sequence:
statement(s)
Example 1
str = "Python"
for i in str:
print(i)
Example 2
list = [1,2,3,4,5,6,7,8,9,10]
n=5
for i in list:
c = n*i
print(c)
Syntax:
range(start,stop,step size)
– The step size is used to skip the specific numbers from the iteration. It is optional
to use.
– By default, the step size is 1.
– range(5) It generates a sequence is [0,1, 2, 3, 4 ]
– range(2,9) It generates a sequence is [ 2, 3, 4, 5, 6, 7, 8]
– range(2,10,2) It generates a sequence is [ 2, 4, 6, 8]
Example
n = int(input("Enter the number "))
for i in range(1,11):
c = n*i
print(n,"*",i,"=",c)
NESTED LOOPS:
Python programming language allows to use one loop inside another loop.
Syntax:
for iterator_var in sequence:
for iterator_var in sequence:
statements(s)
statements(s)
Output:
1
22
333
4444
------------------------------------------------
4. JUMPING
▪ The statements which are unconditionally transferring the program control within a
program are called jump statement.
▪ Loop control statements change execution from its normal sequence.
▪ When execution leaves a scope, all automatic objects that were created in that
scope are destroyed.
▪ The jump statements are
o break
o continue
o pass
▪ When the loops are nested, the break statement only exits from the loop containing
it. That means the break will exit only single loop.
Syntax:
break
Example
i=1
while(i<=10):
print i if(i==4):
break
i=i+1
print “Out of loop”
Syntax:
Continue
Example
i=0
while(i<=9):
i=i+1
if(i==4):
continue
print i
print “Out of loop”
Syntax:
pass
Example
i=0
while(i<=5):
i=i+1
if(i==4):
pass print i
print "Out of loop"
-------------------------------------------------------------------------------------------
PYTHON ARRAYS
▪ Array is a collection of homogeneous elements or array is a collection of similar data
elements under single name.
▪ In python array can increase or decrease their size dynamically. It means, we need
not declare the size of the array.
▪ When the elements are added, it will increase its size and when the elements are
removed, it will automatically decrease its size in memory.
Creating an Array:
▪ In python, there is a standard module by the name ‘array’ the helps to create and
process the arrays.
▪ The array module is import to python program by using import statement.
Syntax:
import array
arrayName = array(typecode, [elements])
– ‘array’ is the standard module in python, which helps to create and process the
arrays.
– where typecode represents the type of array.
– In other words type of data stored in an array.
– The typecode should be enclosed in single quote(‘ ‘).
Minimum
TypeCode Type Description size
in bytes
b Signed integer 1
B Unsigned integer 1
i Signed integer 2
I Unsigned integer 2
l Signed integer 4
L Unsigned integer 4
f Floating point 4
Double precession floating
d 8
point
u Unicode character 2
Example
X=array(‘i’ ,[4, 6, 3, 8])
– This is creating an integer array with the name X and store whole number each
taking 2 bytes memory.
Example program 1
import array as arr
a=arr.array('d', [1.1 , 2.1 ,3.1] )
print(a)
output:
enter araay limit 3
enter array elements
20
30
10
array('i', [20, 30, 10])
2. Remove():
Remove any array element using remove() method
output
array('i', [1, 2, 3, 5])
3. Pop():
Remove last array element using pop() method, pop removes the last element
from the array.
output
array('i', [1, 2, 3, 4])
So we see that the last element (5) was popped out of array.
4. Index():
Fetch any element through its index using index(), this methis returns first index
of the matching value. Remember that arrays are zero-indexed.
output:
5
5. reverse()
The reverse() method reverses the given data.
output
array('i', [5, 4, 3, 2, 1])
----------------------------------------------------------------------------------------------
MULTI-DIMENSIONAL ARRAY
▪ An array containing more than one row and column is called multidimensional array.
Matrix in Numpy
▪ In python we can show matrices as 2D array using Numpy.
▪ NumPy is a general-purpose array-processing package.
▪ It provides a high-performance multidimensional array object, and tools for
working with these arrays.
Example:
import numpy as np
a=np.array([[1,2,3],[4,5,6]])
print(a)
Example:
a=np.array([[1,2,3],[4,5,6]])
print(a)
print(a.ndim)
Example 2:
2. itemsize()
The itemsize() is used to calculate the byte size of each element.
Example:
3. Shape()
Example
This means the array has two dimensions, and each dimension contains two elements.
4. reshape()
The reshape() function is used to reshape the array.
Example
Now the array has three dimensions, with two elements in each dimension.
5. append()
The append() function is used to add new values to an existing array.
Example:
Example: Matrix_Operation.py
import numpy as np
a=np.array([[1,2,3],[4,5,6]])
b=np.array([[1,2,3],[4,5,6]])
c=a+b
print(c)
c=a*b
print(c)
c=a-b
print(c)
OUTPUT:
[[ 2 4 6]
[ 8 10 12]]
[[ 1 4 9]
[16 25 36]]
[[0 0 0]
[0 0 0]]
----------------------------------------------------------------------------------------------
FUNCTIONS-
▪ Function is a group of statements and perform a specific task
▪ When a function is written inside a class, it becomes a method, A method can be
called using object / class name
– The def keyword, along with the function name is used to define the function.
– The identifier rule must follow the function name.
– A function accepts the parameter (argument), and they can be optional.
– The function block is started with the colon (:), and block statements must be at
the same indentation.
– The return statement is used to return the value. A function can have only
one return
Example
def sum():
a = 10
b = 20
c = a+b
# calling sum() function in print statement
print(sum())
Types of function:
Functions are three types, There are:
➢ Built-in function
➢ Module
➢ User-defined function.
➢ Built-in Functions:
▪ Built-in functions are the functions that are built into Python and can be accessed by
programmer any time without importing any module.
Example,
X= abs(-34)
Y=min(5,2,7,19)
Z=max(2,20,4,33,21)
Pirnt(range(1,5))
➢ Module:
▪ A module is a file that contains a collection of related functions and other definitions.
▪ Modules are extensions that can be imported into Python programs.
▪ Module are user-defined modules or built in module.
Built in module:
Python has a math module that includes a number of specialized mathematical
tools. To include math module into your program by importing it.
Example:
File name : module1.py
def sum1(a,b):
c = a+b
return c
def mul1(a,b):
c = a*b
return c
Filename: Test_module1.py
import module1
x = 12
y = 34
➢ User-Defined Functions:
A user defined function represents a function which is named and provided by user to
produce the desired and certain output.
Syntax:
def function-Name(argument-list) : #Function header
St-1 St-2
: # Function body
St-n return()
Example:
def printname(str):
print str
return
printname("Python")
----------------------------------------------------------------------------------------
Types of Parameters or Formal Arguments:
The user defined functions can be call by using the following types of formal arguments.
➢ Required arguments
➢ Keyword arguments
➢ Default arguments
➢ Variable –length arguments
Required Arguments:
▪ Required arguments are the arguments passed to a function in correct positional
order.
▪ The number of arguments in the function call should match exactly with the function
definition.
Example:
def printinfo(name,sem)
print name
print sem
return
printinfo(“aaa”,6)
In the above example, we have passed two arguments. The function definition contains
two arguments to receive those values.
Keyword Arguments:
▪ Keyword arguments are the arguments with assigned values passed in the function
call statement, i.e., when you use keyword argument in a function call, the caller
identifies the arguments by the parameter name.
▪ The Python interpreter is able to use the keywords provided to match the values
with parameters.
Example:
def printinfo(name,sem)
print name
print sem
return
printinfo(sem=6,name=“aaa”)
In the above example, we passed arguments with different order and then the caller
identifies the arguments by the parameter name.
Default Arguments:
▪ A default argument is an argument that assumes a default values if a value is not
provided in the function call for that argument.
▪ A parameter having default value in the function header is known as a default
parameter.
Example:
def printinfo(name=”bbb”,sem=6)
print name
print sem
return
printinfo()
printinfo(sem=6)
printinfo(name=“aaa”,sem=2)
In the above example, first call, we missing both the arguments and then function take
default values. In second time call, we missing one argument and then take name
values as the default value. In third time call, we r not missing any arguments and then
function takes both the arguments provided by the user.
Variable-length arguments:
➢ To process a function for more arguments than you specified while defining the
function. These arguments are called variable length arguments and are not named
in the function definition, unlike required and default arguments.
➢ A asterisk (*) is placed before the variable name that will hold the values of all non-
keyword variable arguments. This tuple remains empty if not additional arguments
are specified during the function call.
Example:
def printinfo(arg1, *vartuple)
print arg1
for k in vartuple :
print k
return
printinfo(10)
printinfo(1,2,3,4,5)
----------------------------------------------------------------------------------------
RECURSION
A recursive function is one that invokes itself. Or A recursive function is a function
that calls itself in its definition.
Example:
def factorial(n):
if n == 0:
return( 1)
else:
return (n*factorial(n-1)) # Recursive call
Syntax:
List-var =[ele1,ele2, …,elen]
Example,
k=[1,2,3,4,5,”python”]
List Operations:
Let us consider the list k=[1,2,3,4,5,”PYTHON”]
1. Indexing:
▪ For accessing an element of the list, indexing is used.
▪ List index starts from 0 in left to right method.
▪ Working from right to left, the first element has the index -1, the next one -2
and so on, but left most element is still 0.
Example:
print k[2] # output is 3
2. Slicing:
▪ A slice of a list is sub-list.
▪ Slicing using to access range of elements.
▪ This operation using two indices, separated by colon(:).
▪ First index is the starting point to extraction starts and second index is the last
point to be stop.
Example
Print k[2:5] #output is 3,4,5
4. Repeating list:
▪ Multiplying a list by an integer n creates a new list that repeats the original list n
times.
▪ The operator * is used to repeating the list by n times.
Example
a=[1,2,3]
print (a*3) # It produce [1,2,3,1,2,3,1,2,3]
------------------------------------------
List functions and methods:
1. len(): It is used to get the length of a list.
Example:
k=[]
for i in range(0,3):
el=input("enter value")
k.append(el)
print(k)
print(len(k))
Example
k=[]
for i in range(0,3):
el=input("enter value")
k.append(el)
print(k)
Example
k=[]
for i in range(0,3):
el=input("enter value")
k.append(el)
print(k)
k.insert(5,30)
print(k)
4. remove(value):
To remove the first occurrence of the specified element from the list.
Example
k=[]
for i in range(0,3):
el=input("enter value")
k.append(el)
print(k)
k.remove(20)
print(k)
5. sort(): This function used to sort/arrange the list item.
Example
k=[]
for i in range(0,3):
el=input("enter value")
k.append(el)
print(k)
k.sort()
print(k)
Example
k=[]
for i in range(0,3):
el=input("enter value")
k.append(el)
print(k)
print(k.reverse())
Characteristics of a Dictionary:
▪ A dictionary is an unordered collection of objects.
▪ Values are accessed using a key
▪ A dictionary can shrink or grow as needed
▪ The contents of dictionaries can be modified.
▪ Dictionaries can be nested.
▪ Sequence operations, such as slice cannot be used with dictionary
Example
OUTPUT:
{}
{1: 'apple', 2: 'ball'}
{'name': 'John', 1: [2, 4, 3]}
Example
my_dict = {'name': 'aaa', 'age': 26}
print(my_dict['name'])
print(my_dict.get('age'))
OUTPUT:
Jack
26
Example
d = {1: "one", 2: "two"}
d.clear()
print('d =', d)
Output
d = {}
Example
original = {1:'one', 2:'two'}
new = original.copy()
print('Orignal: ', original)
print('New: ', new)
Output
Orignal: {1: 'one', 2: 'two'}
New: {1: 'one', 2: 'two'}
Example
person = {'name': 'Phill', 'age': 22}
print('Name: ', person.get('name'))
print('Age: ', person.get('age'))
print('Salary: ', person.get('salary'))
print('Salary: ', person.get('salary', 0.0))
Output
Name: Phill
Age: 22
Salary: None
Salary: 0.0
Example
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
print(squares.pop(4))
Example
person = {'name': 'Phill', 'age': 22, 'salary': 3500.0}
print(person.keys())
empty_dict = {}
print(empty_dict.keys())
Output
dict_keys(['name', 'salary', 'age'])
dict_keys([])
Example
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }
print(sales.values())
Output
dict_values([2, 4, 3])
Example
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }
print(sales.items())
Output
dict_items([('apple', 2), ('orange', 3), ('grapes', 4)])
----------------------------------------------------------------------------------------
SET
▪ A set is an unordered collection of items.
▪ Every set element is unique (no duplicates) and must be immutable (cannot be
changed).
▪ However, a set itself is mutable. We can add or remove items from it.
▪ Sets can also be used to perform mathematical set operations like union,
intersection, symmetric difference, etc.
# set of integers
my_set = {1, 2, 3}
print(my_set)
Output
{1, 2, 3}
{1.0, (1, 2, 3), 'Hello'}
Set Operations
Set Operations
Python provides the methods for performing set union, intersection, difference,
and symmetric difference operations.
Example:
s1 = {1, 4, 5, 6}
s2 = {1, 3, 6, 7}
print(s1.union(s2))
print(s1 | s2)
print(s1.intersection(s2))
print(s1 & s2)
print(s1.difference(s2))
print(s1 - s2)
print(s1.symmetric_difference(s2))
print(s1 ^ s2)
---------------------------------------------------------------------------------------
TUPLE
▪ A tuple is similar to list.
▪ A tuple contains group of elements which can be different types.
▪ Thes elements in the tuple are separated by commas and enclosed in parentheses
(). The only difference is that tuple are immutable.
▪ Tuples once created cannot be modified.
▪ The tuple cannot change dynamically. That means a tuple can be treated as read-
only list.
Syntax:
file_object = open(file_name ,access_mode)
– The first argument file_name is specifies the name of the filename that is to be
opened.
– The second argument access_mode is determines in which mode the file has to
be opened, that is, read, write and append.
Examples:
1. f = open (‘student.txt', 'r')
This statement creates a file object as f, it opens the student.txt file as read
only purpose if the file is exists.
This statement creates a file object as f, it creates new file student.txt for write
purpose if the file is does not exists. If the file is exists overwrite the file.
Examples:
f = open("student.txt",'a')
f.write("100, maya,6 sem")
f.close()
Reading Data
▪ After a file is opened for reading data, you can use the read() method to read a
specified number of characters or all characters from the file and return them as a
string, the readline() method to read the next line, and the readlines() method
to read all the lines into a list of strings.
Examples:
f = open ("student.txt", "a")
f.write("abc 100 fg 50.3")
for i in range(1,10):
f.write("%d" %i)
f.close()
f = open ("student.txt", "r")
c=f.read()
print(c)
------------------------------------------------------------------------------------------
EXCEPTION HANDLING:
▪ An Exception is a condition that is caused by a run-time error in the program.
▪ When the Python interpreter encounters an error such as dividing an integer by zero,
it creates an Exception object and throws it [i.e., informs us that, an error has
occurred].
▪ If the Exception object is not caught and handled property, the interpreter will
display an error message and will terminate the program.
▪ If we want the program to continue with the execution of the remaining code, then
we should try to catch the Exception object thrown by the error condition and then
display an appropriate message for taking corrective actions. This task is known as
Exception handling.
▪ The purpose of Exception handling mechanism is to provide a means to detect and
report an “Exceptional circumstance”, So that appropriate action can be taken, the
mechanism performs the following task:
o Find the error/ detect the error [hit the Exception].
o Inform that an error has occurred [throw the Exception].
o Receive the error information [catch the Exception].
o Take corrective actions / appropriate actions [handle the Exception].
Syntax:
try:
#block of code
except Exception1:
#block of code
except Exception2:
#block of code
#other code
If the Python program contains suspicious code that may throw the exception, we must
place that code in the try block.
The try block must be followed with the except statement, which contains a block of
code that will be executed if there is some exception in the try block.
Examples:
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
except:
print("Can't divide with zero")
We can also use the else statement with the try-except statement in which, we can
place the code which will be executed in the scenario if no exception occurs in the try
block.
The syntax to use the else statement with the try-except statement is given below.
try:
#block of code
except Exception1:
#block of code
else:
#this code executes if no except block is executed
Example:
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d"%c)
except Exception:
print("can't divide by zero")
print(Exception)
else:
print("Hi I am else block")
Common Exceptions
▪ Python provides the number of built-in exceptions, but here we are describing the
common standard exceptions.
▪ A list of common exceptions that can be thrown from a standard Python program is
given below,
o ZeroDivisionError: Occurs when a number is divided by zero.
o NameError: It occurs when a name is not found. It may be local or global.
o IndentationError: If incorrect indentation is given.
o IOError: It occurs when Input Output operation fails.
o EOFError: It occurs when the end of the file is reached, and yet operations
are being performed.
finally block:
▪ This can be used to handle an exception that is not caught by any of the previous
except statements.
▪ Finally block can be used to handle any exception generated within a try block.
▪ It may be added immediately after the try block or after the last except block.
▪ When a finally block is defined, this is guaranteed to execute, regardless of whether
or not an exception is thrown.
▪ As a result, we can use it to perform certain housekeeping operations such as closing
files and releasing system resources.
Syntax
try:
<body>
except <ExceptionType-1>:
<handler>
except <ExceptionType-2>:
<handler>
:
except <ExceptionType-n>:
<handler>
finally :
<handler>
-------------------------------------------------------------------------------------------
MULTI THREADING
▪ Multithreading is a conceptual programming paradigm where a program (process) is
divided into two or more subprograms (process), which can be implemented at the
same time in parallel.
▪ A Thread is similar to a program that has a single flow of control.
▪ It has beginning, a body and an end, and executes command sequentially.
▪ Every java program will have at least one thread called main thread.
Runnable
As the newly born thread is started, the thread becomes runnable i.e. waiting to run.
In this state, it has all the resources but still task scheduler have not scheduled it to
run.
Running
In this state, the thread makes progress and executes the task, which has been chosen
by task scheduler to run. Now, the thread can go to either the dead state or the non-
runnable/ waiting state.
Non-running/waiting
In this state, the thread is paused because it is either waiting for the response of some
I/O request or waiting for the completion of the execution of other thread.
Dead
A runnable thread enters the terminated state when it completes its task or otherwise
terminates.
Chapter 3
Creating a class
Creating a class in Python with the following syntax:
Class classname:
<method definition-1>
<method definition-n>
Example:
Class student:
Reg=1234
Name=”aaa”
def display(self):
print(self.Reg)
print(self.Name)
----------------------------------------------------------------------------------------------------------------------------- --------------
OBJECT
“An object is a real world entity / run time entity which represent
characteristics, state and behavior”.
In other words, Object is a variable of type class or object is an instance, which
represents the characteristics of a class.
Syntax:
objname=classname(args)
Example:
Class student:
Reg=1234
Name=”aaa”
def display(self):
print(self.Reg)
print(self.Name)
stu=student();
stu.display();
---------------------------------------------------------------------------------
SELF PARAMETER
▪ The self is used as a reference variable, which refers to the current class object.
▪ It is used to access variables which belong to same class.
▪ We can use anything instead of self, but it must be the first parameter of any function
which belongs to the class.
Example:
Class student:
Reg=1234
Name=”aaa”
def display(self):
print(self.Reg)
print(self.Name)
stu=student()
stu.display()
METHODS
The class functions are known by common name, methods. In Python, methods
are defined as part of the class definition and are invoked only by an instance.
To call a method we have to :
▪ Define the class (and the methods),
▪ Create an instance, and finally,
▪ Invoke the method from that instance.
The self is a parameter that references the object itself. Using self, you can
access object’s members in a class definition.
To invoke the method we have to instantiate the class and call the method as follows.
obj=first()
obj.display()
-----------------------------------------------------------------------------------------------
_ _init_ _( ) method:
Each class associated with the function called _ _init_ _( ) function which is
always executed when the class being created.
This function which is always executed when the class being creating. Using the
function we can assign/access class variable.
class student:
def _ _init_ _(self,reg,name):
self.Reg=reg
self.name=name
def display(self):
print(self.Reg)
print(self.Name)
stu=student(“1234”,”aaa”)
stu.display()
--------------------------------------------------------------------------------------------
INHERITANCE
▪ Inheritance provides code reusability.
▪ “Inheritance is a process of creating new class from an existing class. The
new class is called the derived class or subclass or child class. The existing
class is called the base class or super class or parent class.
▪ The derived class inherits all the properties of the base class and it can add new
features of its own.
▪ The derived class members automatically inherit the features of the base class.
▪ The derived class may also posses additional features, apart from those inherited
from the base class.
▪ A class could be derived from different base classes.
Syntax:
class BaseClassName():
<statement-1>
..
<statement-N>
class DerivedClassName(BaseClassName):
<statement-1>
. .<statement-N>
Example:
class First:
def input(self):
self.a = int(input("Enter first number:"))
self.b = int(input("Enter second number:"))
class Second(First):
def add(self):
self.z = self.a + self.b
print("Sum of two numbers:", self.z)
obj = Second()
obj.input()
obj.add()
TYPES OF INHERITANCE
➢ Single level Inheritance
➢ Multi level inheritance
➢ Multiple inheritances
➢ Hierarchical inheritance
➢ Hybrid inheritance
Syntax:
class BaseClassName():
<statement-1>
..
<statement-N>
class DerivedClassName(BaseClassName):
<statement-1>
..
<statement-N>
Example:
class First:
def input(self):
self.a = int(input("Enter first number:"))
self.b = int(input("Enter second number:"))
class Second(First):
def add(self):
self.z = self.a + self.b
print("Sum of two numbers:", self.z)
obj = Second()
obj.input()
obj.add()
Syntax
class BaseClassName():
<statement-1>
..
<statement-N>
class DerivedClassName(BaseClassName):
<statement-1>
..
<statement-N>
Example:
class First:
def input(self):
self.a = int(input("Enter first number:"))
self.b = int(input("Enter second number:"))
class Second(First):
def add(self):
self.z = self.a + self.b
class Third(Second):
def result(self):
print("Sum of two numbers:", self.z)
obj = Third()
obj.input()
obj.add()
obj.result()
Multiple inheritances: -
If a class is derived from more than one base class, it is called multiple inheritances.
Syntax
class BaseClassName ():
<statement-1>
..
<statement-N>
Example:
class First:
def input1(self):
self.x = int(input("Enter first number:"))
class Second:
def input2(self):
self.y = int(input("Enter second number:"))
def add(self):
super().input1()
super().input2()
self.z = self.x + self.y
print("Sum is:", self.z)
obj = Third()
obj.add()
Hierarchical inheritance: -
The process of inheriting the properties of one base class by more than one derived
class is called hierarchical inheritance.
Syntax
class BaseClassName(object):
<statement-1>
..
<statement-N>
class DerivedClassName1(BaseClassName):
<statement-1>
..
<statement-N>
class DerivedClassName2(BaseClassName):
<statement-1>
..
<statement-N>
Example:
class First:
def input(self):
self.a = int(input("Enter first number:"))
self.b = int(input("Enter second number:"))
class Second(First):
def add(self):
self.z = self.a + self.b
print("Sum of two numbers:", self.z)
class Third(First):
def mul(self):
self.z = self.a * self.b
print("Product of two numbers:", self.z)
obj1 = Second()
obj1.input()
obj1.add()
obj = Third()
obj.input()
obj.mul()
Here A is the base class, B and C are the derived classes of A. B and C are the base
class of D. D is the base class of E.
----------------------------------------------------------------------------------------------------------------------------------------
Constructor: [ init () ]method
▪ A Constructor is a special method, which is executed automatically when an object
is created.
▪ Constructor is used to initialize the instance variable of a class.
▪ In constructor, we create the instance variable and initialize them with some starting
values.
▪ The first parameter of the constructor will be ‘self’ variable that contains the memory
address of the instance.
▪ The python provides a special method, init is a constructor. This method, known as
an initializer, is invoked to initialize a new object’s state when it is created.
▪ An initializer can perform any action, but initializers are designed to perform
initializing actions, such as creating an object’s data fields with initial values.
default Constructor
If we are creating any constructor externally the python interpreter automatically
provide default constructor.
Example:
class student:
def __init__(self):
self.reg = 1234
self.name = "aaa"
print(self.reg)
print(self.name)
obj=student()
without invoking any method program executes.
Parameterized Constructor
It is a constructor which having parameter, while at the time of creating the
object, we can pass the data for constructor.
Example:
class student:
def __init__(self,reg,name):
self.reg=reg
self.name=name
def display(self):
print(self.reg)
print(self.name)
obj=student("1234","aaa")
obj.display()
----------------------------------------------------------------------------------------------------------------------------- --------
Example:
class xyz(object):
def init (self): # Constructor print (“Object is created and Initialize”)
def del (self): # Destructor print(“xyz object is deleted / Destructor is
executed”)
K=xyz() # Constructor call
del K # Destructor call
-------------------------------------------------------------------------------------------------------------------------------------------
METHOD OVERRIDING
If subclass (child class) has the same method as declared in the parent class, it
is known as method overriding.
class Department(Employee):
def message(self):
print('This Department class is inherited from Employee')
emp = Employee()
emp.message()
print('------------')
dept = Department()
dept.message()
In this example,
– we created an employee class, which contains a message method that prints a
message.
– Next, we created a department class that inherits from Employee class.
– Within this class, we created a method with the same name message with a
different print message.
– The emp object is printing a string from the Employee class message function.
– Whereas, dept.message() is a printing test from Department class.
----------------------------------------------------------------------------------------------
METHOD OVERLOADING
If the process of defining two or more methods are having same name with
different arguments.
Python doesn’t support method overloading directly. Alternative solution to achieve
overloading in python,
Class student
def _ _init_ _(self,n1,n2):
self.n1=n1
self.n2=n2
def sum(self,a,b):
s=0
def sum(self, a=None, b=None, c=None):
stu=student(50,60)
stu=sum(4,9,11)
------------------------------------------------------------------------------------------
PACKAGE
▪ Packages are a way of structuring many packages and modules which helps in a
well-organized hierarchy of data set, making the directories and modules easy to
access.
▪ Just like there are different drives and folders in an OS to help us store files,
similarly packages help us in storing other sub-packages and modules, so that it
can be used by the user when necessary.
Creating Packages
To create a package in Python, we need to follow these three simple steps:
➢ First, we create a directory and give it a package name, preferably related to
its operation.
➢ Then we put the classes and the required functions in it.
➢ Finally we create an __init__.py file inside the directory, to let Python know that
the directory is a package.
To do this we need to create a file with the name Bmw.py and create its content by
putting this code into it.
#Python code to illustrate the Module Audi
class Bmw:
def __init__(self):
self.models = ['i8', 'x1', 'x5', 'x6']
def outModels(self):
print('These are the available models for BMW')
for model in self.models:
print('\t%s ' % model)
Then we create another file with the name Audi.py and add the similar type of code
to it with different members.
Then we create another file with the name Nissan.py and add the similar type of code
to it with different members.
– Finally we create the __init__.py file. This file will be placed inside Cars
directory and can be left blank or we can put this initialisation code into it.
To do this make a sample.py file in the same directory where Cars package is located
and add the following code to it:
ModAudi = Audi()
ModAudi.outModels()
Chapter-5
GUI in Python:
Python offers tkinter module to create graphical programs.
The tkinter represents ‘toolkit interface’ for GUI.
This is a interface for Python programmers that enable them to the classes of TK
module of TCL/TK [Tool Command Language].
TCL language use TK[Tool Kit] language to generate graphics.
Create a canvas/frame:
Canvas and frame are child windows in the root window. Canvas and frames are
called as Tkinter widgets.
Example:
C=canvas(root, bg=’blue’, height=500, width=’400’, cursor=’pencil’)
Example program to illustrate or draw line, oval, polygon, rectangle and text.
Root=TK()
Root.title(“Basic shapes”)
#create line
Can.create-line (15,25,200,25)
Can.create-line (300,35,300,200,dash=(4,2))
#create Oval
Can.create-oval(20,30,100,80, width=2
Fill=”yellow”,Activefill=”blue”)
#rectangle
#Text
Can.create-text(50,100,text=”msg”,font=”style(verdanas)”, fill=”black”,
Activefill=”red”)
Can.Pack()
Root.mainloop()
--------------------------------------------------------------------------------------
Frame
Frame is a similar to canvas. It is a child window under root window. It can hold
the components of forms (like object).
Widgets
Widgets are called as form element, these are GUI components that is displayed
on the screen, these Components can perform a task as designed by the user.
Button
It is a component that performs some action when clicked. These buttons are
created as object of button class
Syntax:
Identifier= Button (parent/root, options)
Example:-
b=Buttons(root, text=“click here”)
We can use many properties like, width, Underline , Bg, Bd, Font, Height, etc…
Example Program:-
From tkiner import *
Root = TK()
Root.geomatry(“200*100”)
B=Button (root, text=:click here”, Bg=”blue”)
b.pack( )
top.mainloop( )
LABEL
The Label is used to specify the container box where we can place the text or
images.
Syntax:
Identifier= Lable (parent/root, options)
Example:
UN= Label(top, text = "Username").place(x = 30,y = 50)
Example Program:
From tkiner import *
top = TK()
top.geomatry(“200*100”)
uname = Label(top, text = "Username").place(x = 30,y = 50)
password = Label(top, text = "Password").place(x = 30, y = 90)
sbmitbtn = Button(top, text = "Submit",activebackground = "pink", activeforeground =
"blue").place(x = 30, y = 120)
e1 = Entry(top,width = 20).place(x = 100, y = 50)
JANHAVI N L, Asst, Proof, Dept. of BCA, VVFGC, Tumkur Page 4
PYTHON PROGRAMMING GRAPHICAL USER INTERFACE
Radiobutton
The Radiobutton widget is used to implement one-of-many selection in the python
application.
It shows multiple choices to the user out of which, the user can select only one
out of them.
We can associate different methods with each of the radiobutton.
Syntax:
Identifier= Radiobutton (parent/root, options)
Example:
Radiobutton(top, text="C++", variable=radio, value=2,
command=selection)
Example Program:
From tkiner import *
Root.geomatry(“200*300”)
r1 = Radiobutton(f, text="male", bg='green', fg='red', font=('Times', 20, 'italic'),
value=0)
r1.pack(side=LEFT)
r2 = Radiobutton(f, text="female", bg='green', fg='red', font=('Times', 20, 'italic'),
value=1)
r2.pack(side=LEFT)
Root.mainloop()
Checkbutton
Checkbutton is used to implement on/off selections.
Checkbutton can contain text or images.
Check buttons are also known as check boxes are useful for the user to select one
or more options from available group of options.
Check buttons are displayed in the form of square shaped boxes. When check box
is selected, a tick mark is displayed on the check box.
Syntax:
Identifier= Radiobutton (parent/root, options)
TEXT:
A text widget is same as label. But text widget has several options and can
display multiple lines of text in different colors and fonts.
It is possible to insert text into a text widget, modify it or delete it. We can also
display images in the text widget.
Here,
– ‘t’ is the object of Text class,
– ‘f’ represents the frame for which the text is created as a child.
– The width and height represents the size of the text box,
– ‘bg’ represents the background color and ‘fg’ represents the fore ground color of
the text,
– ‘font ‘ represents a tuple that contains font name, size and style.
– The ‘wrap’ represents the text information can be align with in the text box.
def buttonClick(self):
print ("You have cliked Ok button")
root=Tk()
root.title ("Button Example")
f=Frame(root,bg="blue",height=700,width=1200,cursor='
cross') f.propagate(0)
f.pack()
b.bind("<Button-1>", buttonClick)
t=Text(f,width=20,
height=3,font=('Times',20,'italic'),fg='blue',bg="yellow",wrap=
WORD) t.insert(END," Text Demo")
t.pack(side=LEFT)
c1=Checkbutton(f,
text="Python",bg='yellow',fg='red',
font=('Times',20,'italic'))
c1.pack(side=LEFT)
c2=Checkbutton(f,
text="Networking",bg='yellow',fg='red',
font=('Times',20,'italic'))
c2.pack(side=LEFT)
c3=Checkbutton(f,
text="Java",bg='yellow',fg='red',
font=('Times',20,'italic'))
c3.pack(side=LEFT)
r1=Radiobutton(f, text="male",
bg='green',fg='red',
font=('Times',20,'italic'),value=0)
r1.pack(side=LEFT)
r2=Radiobutton(f, text="female",
bg='green',fg='red',
font=('Times',20,'italic'),value=1)
r2.pack(side=LEFT)
root.mainloop()
-------------------------------------------------------------------------------------
Sample Graphics programming to produce charts
Or
Data Visualization with different charts
Data visualization is the presentation of data in graphical format.
Data visualization helps to understand the significance and analyzing the data.
Matplotlib is package is used create 2 D Plots and graphs.
Line chart:-
Line charts represent scores of data points with a continuous line. First need to
import matplotlib, We need to take set of data points using array or list. Then plot line
chart using those data sets/points.
Example :-
plot(x,y)
Bar charts
Histogram
Is an approximated representation of the distribution of numerical data. It look like bar
chart.
Example:-
Import matplotlib,ptplot as plt
Dataset=[20,30,10,10,30,10,20,30,30,40,20,40,40)
Plot.hist(data sd, facecolor=’red’,edgecolor=’yellow’)
Plot.title(“ “)
Plot.show
Pie chart
Numpy
Numpy is a library for scientific computing. It is useful for working with arrays and matrices.
Most of its code is written in C, so it is very fast. Numpy is used in many scientific
computing applications, including machine learning and deep learning. Numpy is imported
using the import keyword. Numpy is usually imported using the alias np .
import numpy as np
Numpy arrays
Numpy arrays are used to store multiple items in a single variable. They can be created
using the np.array function. Numpy arrays are similar to lists, but they are faster and
more efficient. Numpy arrays can be created from lists, tuples, and other arrays.
x = np.array([1, 2, 3])
array([1, 2, 3])
4.92 ms ± 9.35 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
130 µs ± 75.3 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
X.T # transpose
X@Y # matrix multiplication
X*X # element-wise multiplication
np.dot(X, Y) # matrix multiplication
np.matmul(X, Y) # matrix multiplication
np.vdot(x, x) # dot product
np.inner(x, x) # dot product
np.outer(x, x) # outer product
np.linalg.norm(x) # norm
np.linalg.det(X@Y) # determinant
np.linalg.inv(X@Y) # inverse
np.linalg.eig(X@Y) # eigenvalues and eigenvectors
np.linalg.svd(X@Y) # singular value decomposition
Numpy types
Numpy allows to store data in different types. This is useful when you want to save
memory, or when you want to perform operations on different types of data. Data types
include int32, int64, float32, float64, bool, and object. The default data type is float64.
x = np.array([1, 2, 3], dtype=np.int8)
x.dtype # dtype('int8')
Matplotlib
Matplotlib is a library for plotting data. It is useful for visualizing data. Matplotlib is imported
using the import keyword. Matplotlib is usually imported using the alias plt .
import matplotlib.pyplot as plt
# or
from matplotlib import pyplot as plt
Customizing plots
plt.title- Set the title of the plot
plt.xlabel - Set the label for the x-axis
Dataframes are the main data structure in Pandas. They are used to store tabular data.
They can be created using the pd.DataFrame function. Dataframes can be created from
lists, tuples, dictionaries, and other dataframes. It is common to name dataframes df .
df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})
a b
0 1 4
1 2 5
2 3 6
Juan F. Imbet Ph.D. 15
Python for Finance
Pandas - miscellaneous
Pandas can load data from a URL.
df = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv')
Pandas and NumPy are closely related. Pandas is built on top of NumPy, and it uses NumPy
arrays to store data. Pandas can convert dataframes to NumPy arrays using the to_numpy
method.
df.to_numpy()
Columns can be accessed using the [] operator. The [] operator is used to access
columns by label. Columns can also be accessed using the . operator. The . operator is
used to access columns by label. The . operator cannot be used to describe a column
that does not exist, and cannot be used to describe a column with a reserved name. E.g.
df.dtype is not a valid column.
group
A 3
B 7
sex - The
sibsp - The number of siblings or spouses the passenger had aboard the Titanic
parch - The number of parents or children the passenger had aboard the Titanic
fare - The fare the passenger paid
Questions (2)
Estimate the average age of the passengers who survived and the passengers who
did not survive.
Estimate the average fare paid by the passengers who survived and the passengers
who did not survive.
Based on the documentation of pandas and matplotlib, create a plot that shows the
relatiin between the fare paid and the age of the passengers.
How does this relationship change across the different classes?
i
Python SQLite
This tutorial explains how to communicate with SQLite database in detail, along with
examples.
Audience
This tutorial is designed for python programmers who would like to understand the Python
sqlite3 module in detail.
Prerequisites
Before proceeding with this tutorial, you should have a good understanding of python
programming language. It is also recommended to have basic understanding of the
databases — SQLite.
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at contact@tutorialspoint.com
ii
Python SQLite
Table of Contents
About the Tutorial ........................................................................................................................................... ii
Audience .......................................................................................................................................................... ii
Prerequisites .................................................................................................................................................... ii
iii
Python SQLite
iv
1. Python SQLite ― Introduction Python SQLite
SQLite3 can be integrated with Python using sqlite3 module, which was written by Gerhard
Haring. It provides an SQL interface compliant with the DB-API 2.0 specification described
by PEP 249. You do not need to install this module separately because it is shipped by
default along with Python version 2.5.x onwards.
To use sqlite3 module, you must first create a connection object that represents the
database and then optionally you can create a cursor object, which will help you in
executing all the SQL statements.
This API opens a connection to the SQLite database file. You can use ":memory:"
to open a database connection to a database that resides in RAM instead of on
disk. If database is opened successfully, it returns a connection object.
2 connection.cursor([cursorClass])
This routine creates a cursor which will be used throughout your database
programming with Python. This method accepts a single optional parameter
cursorClass. If supplied, this must be a custom cursor class that extends
sqlite3.Cursor.
For example − cursor.execute("insert into people values (?, ?)", (who, age))
This routine is a shortcut of the above execute method provided by the cursor
object and it creates an intermediate cursor object by calling the cursor method,
then calls the cursor's execute method with the parameters given.
1
Python SQLite
5 cursor.executemany(sql, seq_of_parameters)
6 connection.executemany(sql[, parameters])
7 cursor.executescript(sql_script)
This routine executes multiple SQL statements at once provided in the form of
script. It issues a COMMIT statement first, then executes the SQL script it gets
as a parameter. All the SQL statements should be separated by a semi colon
(;).
8 connection.executescript(sql_script)
9 connection.total_changes()
This routine returns the total number of database rows that have been modified,
inserted, or deleted since the database connection was opened.
10 connection.commit()
This method commits the current transaction. If you don't call this method,
anything you did since the last call to commit() is not visible from other database
connections.
11 connection.rollback()
This method rolls back any changes to the database since the last call to
commit().
12 connection.close()
This method closes the database connection. Note that this does not
automatically call commit(). If you just close your database connection without
calling commit() first, your changes will be lost!
13 cursor.fetchone()
This method fetches the next row of a query result set, returning a single
sequence, or None when no more data is available.
2
Python SQLite
14 cursor.fetchmany([size = cursor.arraysize])
This routine fetches the next set of rows of a query result, returning a list. An
empty list is returned when no more rows are available. The method tries to
fetch as many rows as indicated by the size parameter.
15 cursor.fetchall()
This routine fetches all (remaining) rows of a query result, returning a list. An
empty list is returned when no rows are available.
3
2. Python SQLite — Establishing Connection Python SQLite
To establish connection with SQLite Open command prompt, browse through the location
of where you have installed SQLite and just execute the command sqlite3 as shown
below:
To establish a connection with SQLite3 database using python you need to:
The connect() method accepts the name of the database you need to connect with
as a parameter and, returns a Connection object.
Example
import sqlite3
conn = sqlite3.connect('example.db')
Output
print("Connection established ..........")
4
3. Python SQLite ― Create Table Python SQLite
Using the SQLite CREATE TABLE statement you can create a table in a database.
Syntax
Following is the syntax to create a table in SQLite database:
Example
Following SQLite query/statement creates a table with name CRICKETERS in SQLite
database:
Let us create one more table OdiStats describing the One-day cricket statistics of each
player in CRICKETERS table.
5
Python SQLite
);
sqlite>
You can get the list of tables in a database in SQLite database using the .tables command.
After creating a table, if you can verify the list of tables you can observe the newly created
table in it as:
sqlite> . tables
CRICKETERS ODIStats
sqlite>
Create a cursor object by invoking the cursor() method on the above created
connection object.
Now execute the CREATE TABLE statement using the execute() method of the
Cursor class.
Example
Following Python program creates a table named Employee in SQLite3:
import sqlite3
#Connecting to sqlite
conn = sqlite3.connect('example.db')
SEX CHAR(1),
INCOME FLOAT)'''
cursor.execute(sql)
print("Table created successfully........")
Output
Table created successfully........
7
4. Python SQLite — Insert Data Python SQLite
You can add new rows to an existing table of SQLite using the INSERT INTO statement. In
this, you need to specify the name of the table, column names, and values (in the same
order as column names).
Syntax
Following is the recommended syntax of the INSERT statement:
Where, column1, column2, column3,.. are the names of the columns of a table and value1,
value2, value3,... are the values you need to insert into the table.
Example
Assume we have created a table with name CRICKETERS using the CREATE TABLE
statement as shown below:
While inserting records using the INSERT INTO statement, if you skip any columns names,
this record will be inserted leaving empty spaces at columns which you have skipped.
You can also insert records into a table without specifying the column names, if the order
of values you pass is same as their respective column names in the table.
8
Python SQLite
After inserting the records into a table you can verify its contents using the SELECT
statement as shown below:
Create a connection object using the connect() method by passing the name of the
database as a parameter to it.
The cursor() method returns a cursor object using which you can communicate
with SQLite3. Create a cursor object by invoking the cursor() object on the (above
created) Connection object.
Then, invoke the execute() method on the cursor object, by passing an INSERT
statement as a parameter to it.
Example
Following python example inserts records into to a table named EMPLOYEE:
import sqlite3
#Connecting to sqlite
conn = sqlite3.connect('example.db')
print("Records inserted........")
Output
Records inserted........
10
5. Python SQLite ― Select Data Python SQLite
You can retrieve data from an SQLite table using the SELCT query. This query/statement
returns contents of the specified relation (table) in tabular form and it is called as result-
set.
Syntax
Following is the syntax of the SELECT statement in SQLite:
Example
Assume we have created a table with name CRICKETERS using the following query:
Following SELECT query retrieves the values of the columns FIRST_NAME, LAST_NAME
and, COUNTRY from the CRICKETERS table.
11
Python SQLite
Virat|Kohli|India
Rohit|Sharma|India
sqlite>
As you observe, the SELECT statement of the SQLite database just returns the records of
the specified tables. To get a formatted output you need to set the header, and mode
using the respective commands before the SELECT statement as shown below:
sqlite> .header on
sqlite> .mode column
sqlite> SELECT FIRST_NAME, LAST_NAME, COUNTRY FROM CRICKETERS;
First_Name Last_Name Country
---------- -------------------- ----------
Shikhar Dhawan India
Jonathan Trott SouthAfric
Kumara Sangakkara Srilanka
Virat Kohli India
Rohit Sharma India
sqlite>
If you want to retrieve all the columns of each record, you need to replace the names of
the columns with "*" as shown below:
sqlite> .header on
sqlite> .mode column
sqlite> SELECT * FROM CRICKETERS;
First_Name Last_Name Age Place_Of_Birth Country
---------- ---------- ---------- -------------- ----------
Shikhar Dhawan 33 Delhi India
Jonathan Trott 38 CapeTown SouthAfric
Kumara Sangakkara 41 Matale Srilanka
Virat Kohli 30 Delhi India
Rohit Sharma 32 Nagpur India
sqlite>
In SQLite by default the width of the columns is 10 values beyond this width are chopped
(observe the country column of 2nd row in above table). You can set the width of each
column to required value using the .width command, before retrieving the contents of a
table as shown below:
12
Python SQLite
The sqlite3.Cursor class provides three methods namely fetchall(), fetchmany() and,
fetchone() where,
The fetchall() method retrieves all the rows in the result set of a query and returns
them as list of tuples. (If we execute this after retrieving few rows it returns the
remaining ones).
The fetchone() method fetches the next row in the result of a query and returns it
as a tuple.
The fetchmany() method is similar to the fetchone() but, it retrieves the next set
of rows in the result set of a query, instead of a single row.
Note: A result set is an object that is returned when a cursor object is used to query a
table.
Example
Following example fetches all the rows of the EMPLOYEE table using the SELECT query and
from the obtained result set initially, we are retrieving the first row using the fetchone()
method and then fetching the remaining rows using the fetchall() method.
Following Python program shows how to fetch and display records from the COMPANY
table created in the above example.
import sqlite3
#Connecting to sqlite
conn = sqlite3.connect('example.db')
13
Python SQLite
cursor = conn.cursor()
#Retrieving data
cursor.execute('''SELECT * from EMPLOYEE''')
Output
('Ramya', 'Rama priya', 27, 'F', 9000.0)
[('Vinay', 'Battacharya', 20, 'M', 6000.0),
('Sharukh', 'Sheik', 25, 'M', 8300.0),
('Sarmista', 'Sharma', 26, 'F', 10000.0),
('Tripthi', 'Mishra', 24, 'F', 6000.0)]
14
6. Python SQLite — Where Clause Python SQLite
If you want to fetch, delete or, update particular rows of a table in SQLite, you need to
use the where clause to specify condition to filter the rows of the table for the operation.
For example, if you have a SELECT statement with where clause, only the rows which
satisfies the specified condition will be retrieved.
Syntax
Following is the syntax of the WHERE clause in SQLite:
You can specify a search_condition using comparison or logical operators. like >, <, =,
LIKE, NOT, etc. The following examples would make this concept clear.
Example
Assume we have created a table with name CRICKETERS using the following query:
15
Python SQLite
sqlite>
Following SELECT statement retrieves the records whose age is greater than 35:
Create a cursor object by invoking the cursor() method on the above created
connection object.
Now execute the CREATE TABLE statement using the execute() method of the
Cursor class.
Example
Following example creates a table named Employee and populates it. Then using the where
clause it retrieves the records with age value less than 23.
import sqlite3
#Connecting to sqlite
conn = sqlite3.connect('example.db')
16
Python SQLite
AGE INT,
SEX CHAR(1),
INCOME FLOAT)'''
cursor.execute(sql)
print(cursor.fetchall())
Output
[('Vinay', 'Battacharya', 20, 'M', 6000.0)]
17
7. Python SQLite ― Order By Python SQLite
While fetching data using SELECT query, you will get the records in the same order in
which you have inserted them.
You can sort the results in desired order (ascending or descending) using the Order By
clause. By default, this clause sorts results in ascending order, if you need to arrange them
in descending order you need to use “DESC” explicitly.
Syntax
Following is the syntax of the ORDER BY clause in SQLite.
SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
Example
Assume we have created a table with name CRICKETERS using the following query:
18
Python SQLite
sqlite>
Following SELECT statement retrieves the rows of the CRICKETERS table in the ascending
order of their age:
You can use more than one column to sort the records of a table. Following SELECT
statements sorts the records of the CRICKETERS table based on the columns AGE and
FIRST_NAME.
By default, the ORDER BY clause sorts the records of a table in ascending order you can
arrange the results in descending order using DESC as:
19
Python SQLite
Example
In the following example we are creating a table with name and Employee, populating it,
and retrieving its records back in the (ascending) order of their age, using the ORDER BY
clause.
import psycopg2
20
Python SQLite
conn.commit()
print(cursor.fetchall())
Output
[('Vinay', 'Battacharya', 20, 'M', 6000, None),
('Tripthi', 'Mishra', 24, 'F', 6000, None),
('Sharukh', 'Sheik', 25, 'M', 8300, None),
('Sarmista', 'Sharma', 26, 'F', 10000, None),
('Ramya', 'Rama priya', 27, 'F', 9000, None)]
21
8. Python SQLite — Update Table Python SQLite
UPDATE Operation on any database implies modifying the values of one or more records
of a table, which are already available in the database. You can update the values of
existing records in SQLite using the UPDATE statement.
To update specific rows, you need to use the WHERE clause along with it.
Syntax
Following is the syntax of the UPDATE statement in SQLite:
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
Example
Assume we have created a table with name CRICKETERS using the following query:
22
Python SQLite
Following Statement modifies the age of the cricketer, whose first name is Shikhar:
If you retrieve the record whose FIRST_NAME is Shikhar you observe that the age value
has been changed to 45:
If you haven’t used the WHERE clause values of all the records will be updated. Following
UPDATE statement increases the age of all the records in the CRICKETERS table by 1:
If you retrieve the contents of the table using SELECT command, you can see the updated
values as:
Create a connection object using the connect() method by passing the name of the
database as a parameter to it.
The cursor() method returns a cursor object using which you can communicate
with SQLite3 . Create a cursor object by invoking the cursor() object on the (above
created) Connection object.
23
Python SQLite
Then, invoke the execute() method on the cursor object, by passing an UPDATE
statement as a parameter to it.
Example
Following Python example, creates a table with name EMPLOYEE, inserts 5 records into it
and, increases the age of all the male employees by 1:
import sqlite3
#Connecting to sqlite
conn = sqlite3.connect('example.db')
#Inserting data
cursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME)
VALUES ('Ramya', 'Rama priya', 27, 'F', 9000),('Vinay', 'Battacharya', 20, 'M',
6000), ('Sharukh', 'Sheik', 25, 'M', 8300), ('Sarmista', 'Sharma', 26, 'F',
10000),('Tripthi', 'Mishra', 24, 'F', 6000)''')
conn.commit()
24
Python SQLite
Output
Contents of the Employee table:
[('Ramya', 'Rama priya', 27, 'F', 9000.0), ('Vinay', 'Battacharya', 20, 'M',
6000.0), ('Sharukh', 'Sheik', 25, 'M', 8300.0), ('Sarmista', 'Sharma', 26, 'F',
10000.0), ('Tripthi', 'Mishra', 24, 'F', 6000.0)]
Table updated......
Contents of the Employee table after the update operation:
[('Ramya', 'Rama priya', 27, 'F', 9000.0), ('Vinay', 'Battacharya', 21, 'M',
6000.0), ('Sharukh', 'Sheik', 26, 'M', 8300.0), ('Sarmista', 'Sharma', 26, 'F',
10000.0), ('Tripthi', 'Mishra', 24, 'F', 6000.0)]
25
9. Python SQLite ― Delete Data Python SQLite
To delete records from a SQLite table, you need to use the DELETE FROM statement. To
remove specific records, you need to use WHERE clause along with it.
Syntax
Following is the syntax of the DELETE query in SQLite:
Example
Assume we have created a table with name CRICKETERS using the following query:
Following statement deletes the record of the cricketer whose last name is 'Sangakkara'.
26
Python SQLite
If you retrieve the contents of the table using the SELECT statement, you can see only 4
records since we have deleted one.
If you execute the DELETE FROM statement without the WHERE clause, all the records
from the specified table will be deleted.
Since you have deleted all the records, if you try to retrieve the contents of the
CRICKETERS table, using SELECT statement you will get an empty result set as shown
below:
Create a connection object using the connect() method by passing the name of the
database as a parameter to it.
The cursor() method returns a cursor object using which you can communicate
with SQLite3 . Create a cursor object by invoking the cursor() object on the (above
created) Connection object.
Then, invoke the execute() method on the cursor object, by passing an DELETE
statement as a parameter to it.
Example
27
Python SQLite
Following python example deletes the records from EMPLOYEE table with age value greater
than 25.
import sqlite3
#Connecting to sqlite
conn = sqlite3.connect('example.db')
#Deleting records
cursor.execute('''DELETE FROM EMPLOYEE WHERE AGE > 25''')
Output
Contents of the table:
[('Ramya', 'Rama priya', 27, 'F', 9000.0), ('Vinay', 'Battacharya', 21, 'M',
6000.0), ('Sharukh', 'Sheik', 26, 'M', 8300.0), ('Sarmista', 'Sharma', 26, 'F',
10000.0), ('Tripthi', 'Mishra', 24, 'F', 6000.0)]
Contents of the table after delete operation
[('Vinay', 'Battacharya', 21, 'M', 6000.0), ('Tripthi', 'Mishra', 24, 'F',
6000.0)]
28
10. Python SQLite — Drop Table Python SQLite
You can remove an entire table using the DROP TABLE statement. You just need to specify
the name of the table you need to delete.
Syntax
Following is the syntax of the DROP TABLE statement in PostgreSQL:
Example
Assume we have created two tables with name CRICKETERS and EMPLOYEES using the
following queries:
Now if you verify the list of tables using the .tables command, you can see the above
created tables in it ( list) as:
sqlite> .tables
CRICKETERS EMPLOYEE
sqlite>
Following statement deletes the table named Employee from the database:
Since you have deleted the Employee table, if you retrieve the list of tables again, you can
observe only one table in it.
sqlite> .tables
CRICKETERS
sqlite>
If you try to delete the Employee table again, since you have already deleted it you will
get an error saying “no such table” as shown below:
29
Python SQLite
To resolve this, you can use the IF EXISTS clause along with the DELTE statement. This
removes the table if it exists else skips the DLETE operation.
Example
To drop a table from a SQLite3 database using python invoke the execute() method on
the cursor object and pass the drop statement as a parameter to it.
import sqlite3
#Connecting to sqlite
conn = sqlite3.connect('example.db')
Output
Table dropped...
30
11. Python SQLite ― Limit Python SQLite
While fetching records if you want to limit them by a particular number, you can do so,
using the LIMIT clause of SQLite.
Syntax
Following is the syntax of the LIMIT clause in SQLite:
Example
Assume we have created a table with name CRICKETERS using the following query:
Following statement retrieves the first 3 records of the Cricketers table using the LIMIT
clause:
31
Python SQLite
If you need to limit the records starting from nth record (not 1st), you can do so, using
OFFSET along with LIMIT.
Example
Following python example retrieves the first two records of the EMPLOYEE table using the
LIMIT clause.
import sqlite3
#Connecting to sqlite
conn = sqlite3.connect('example.db')
32
Python SQLite
Output
[('Ramya', 'Rama priya', 27, 'F', 9000.0), ('Vinay', 'Battacharya', 20, 'M',
6000.0), ('Sharukh', 'Sheik', 25, 'M', 8300.0)]
33
12. Python SQLite — Join Python SQLite
When you have divided the data in two tables you can fetch combined records from these
two tables using Joins.
Example
Assume we have created a table with name CRICKETERS using the following query:
Let us create one more table OdiStats describing the One-day cricket statistics of each
player in CRICKETERS table.
Following statement retrieves data combining the values in these two tables:
sqlite> SELECT
34
Python SQLite
import sqlite3
#Connecting to sqlite
conn = sqlite3.connect('example.db')
#Retrieving data
sql = '''SELECT * from EMP INNER JOIN CONTACT ON EMP.CONTACT = CONTACT.ID'''
print(result)
Output
[('Ramya', 'Rama priya', 27, 'F', 9000.0, 101, 101, 'Krishna@mymail.com',
'Hyderabad'), ('Vinay', 'Battacharya', 20, 'M', 6000.0, 102, 102,
35
Python SQLite
36
13. Python SQLite ― Cursor Object Python SQLite
The sqlite3.Cursor class is an instance using which you can invoke methods that execute
SQLite statements, fetch data from the result sets of the queries. You can create Cursor
object using the cursor() method of the Connection object/class.
Example
import sqlite3
#Connecting to sqlite
conn = sqlite3.connect('example.db')
Methods
Following are the various methods provided by the Cursor class/object.
Method Description
fetchone() This method fetches the next row of a query result set,
returning a single sequence, or None when no more data is
available.
fetchmany() This routine fetches the next set of rows of a query result,
returning a list. An empty list is returned when no more rows
are available. The method tries to fetch as many rows as
indicated by the size parameter.
37
Python SQLite
Properties
Following are the properties of the Cursor class:
Method Description
arraySize This is a read/write property you can set the number of rows
returned by the fetchmany() method.
description This is a read only property which returns the list containing the
description of columns in a result-set.
38