0% found this document useful (0 votes)
13 views141 pages

Python_Programming_Notes

The document provides an overview of Python programming, covering its history, versions, features, and applications. It explains the basics of Python, including its syntax, data types, and the importance of indentation. Additionally, it discusses the Python interpreter, modes of operation, and key programming concepts such as variables, identifiers, comments, and data structures.

Uploaded by

shashi740690
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views141 pages

Python_Programming_Notes

The document provides an overview of Python programming, covering its history, versions, features, and applications. It explains the basics of Python, including its syntax, data types, and the importance of indentation. Additionally, it discusses the Python interpreter, modes of operation, and key programming concepts such as variables, identifiers, comments, and data structures.

Uploaded by

shashi740690
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 141

PYTHON PROGRAMMING PYTHON PROGRAMMING BASICS

Chapter 1

PYTHON PROGRAMMING BASICS

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

The following table lists all the important versions of Python:


Version Release Date Important Features
Python 0.9.0 February 1991 Classes with inheritance exception handling
Functions
Modules
Python 1.0 January 1994 Functional programming tools (lambda, map,
filter and reduce).
Support for complex numbers.
Functions with keyword arguments
Python 2.0 October 2000 List comprehension.
Python 2.7.0 July 2010 Cycle-detecting garbage collector.
Support for Unicode. Unification of data types
and classes
Python 3 December 2008 Backward incompatible.
[Py3k] print keyword changed to print() function
Python 3.6 December 2016 raw_input() function depreciated
Python 3.6.5 March 2018 Unified str/Unicode types.
Utilities for automatic conversion of Pytthon 2.x
code
Python 3.7.0 May 2018 New C API for thread-local storage

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 1


PYTHON PROGRAMMING PYTHON PROGRAMMING BASICS

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.

▪ Large Standard Library:

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 2


PYTHON PROGRAMMING PYTHON PROGRAMMING BASICS

– 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.

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 3


PYTHON PROGRAMMING PYTHON PROGRAMMING BASICS

• 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:

• What you are seeing is called Python Shell.


• >>>is known as prompt string, it simply means that Python shell is ready to accept
you commands.
• Python shell allows you type Python code and see the result immediately.

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’.

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 4


PYTHON PROGRAMMING PYTHON PROGRAMMING BASICS

▪ 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!")

Python will give you an error if you skip the indentation:


if 5 > 2:
print("Five is greater than two!")
------------------------------------------------------------------------------------------------
Elements of Python
Variables:
▪ Variable is a name which is used to refer memory location.
▪ Variable also known as identifier and used to hold value, whose value changes during
the execution of the program.
▪ In Python, we don't need to specify the type of variable, because Python is smart
enough to get variable type.
▪ Unlike other programming languages, Python has no command for declaring a
variable.
▪ When we assign any value to the variable that variable is declared automatically.
▪ Variables do not need to be declared with any particular type and can even change
type after they have been set.
Example:
a=10
Now this a is of type int
a=’s’
This as type char.

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

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 5


PYTHON PROGRAMMING PYTHON PROGRAMMING BASICS

o Multi Lined Comment


Single lined comment:
In case user wants to specify a single line comment, then comment must start
with # symbol.
Example: # This is single line comment.

Multi lined Comment:


Multi lined comment can be given inside triple double quotes (“””) or triple single
quotes (‘’’).
Example: ''''' This
Is
Multiline 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)

1. Numeric data type:


▪ Numeric data type represents the data which has numeric value.
▪ Numeric value can be integer, floating number or even complex numbers.
▪ There are 3 sub types:
o int
o float
o complex
int data type:

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 6


PYTHON PROGRAMMING PYTHON PROGRAMMING BASICS

▪ 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

float data type:


▪ The float data type represents floating point number. A floating point number is
a number with fraction.
▪ Floating point numbers can also be written in scientific notation using
exponentiation format.
▪ A floating point number is accurate up to 15 decimal places.
▪ Example. c=2.0
d=-29.45
x=2.5E4

complex data type:


▪ A complex number is number is written in the form of x +yj or x+yJ.
▪ Here x is the real part and y is the imaginary part.
▪ Example. a= 5 +6j
b= 2.5 + 6.2J

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

str data type :


The str represents string data type. A string is a collection of character enclosed
in single or double quotes. Both are valid.
Example
str=”python”
# str is name of string variable, string value is python.

▪ The [] operator used to retrieve specified character from the string.


▪ The string index starts from 0. Hence, str[0] indicates the 0th character in the string.

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 7


PYTHON PROGRAMMING PYTHON PROGRAMMING BASICS

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

list data type:


▪ A List is a collection which is ordered and changeable.
▪ A list is similar to array. Lists are represented by square brackets [] and the elements
are separated by comma.
▪ The main difference between a list and an array is that a list can store different data
type elements, but an array can store only one type of elements.
▪ It allows duplicate members.
▪ List can also grow dynamically in memory but the size of array is fixed and they
cannot grow dynamically.

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

tuple data type:


▪ A tuple is similar to list.
▪ A tuple contains group of elements which can be different types.
▪ The elements in the tuple are separated by commas and enclosed in parentheses ().
▪ The only difference is that tuples are immutable.
▪ Tuples once created cannot be modified.
▪ The tuple cannot change dynamically. That means a tuple can be treated as read-
only list.

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.

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 8


PYTHON PROGRAMMING PYTHON PROGRAMMING BASICS

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

Set data type:


To create a set, we should enter the elements separated by comma inside a curly
brace.
Example
s = {10,30,5, 30,50}
print(s)

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.

The update() method used to add new elements to a set


s.update([25,15])
print(s) #output: {10,5,15,30,25,30}

The remove() method used to remove a particular element from the


s.remove(30)
print(s) # it display: {10,5,15,25,30}

Frozen set data type:


▪ Frozen set is just an immutable version of a Python set object.
▪ While elements of a set can be modified at any time, an element of frozen set
remains the same after creation.
▪ Due to this, frozen sets can be used as key in Dictionary or as element of another
set.

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.

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 9


PYTHON PROGRAMMING PYTHON PROGRAMMING BASICS

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,

Symbol Description Example-1


5+6
+ Addition
11

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 10


PYTHON PROGRAMMING PYTHON PROGRAMMING BASICS

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,

Symbol Description Example-1


7<10
< Less than
True
7 >10
> Greater Than
False
7<=10
<= Less than or equal to
True
7>=10
>= Greater than or equal to
False
7!=10
!= , <> Not equal to
True
7==10
== Equal to
False

Logical operator:
These are the operators which are used to perform combining two or more expressions,

Symbol Description Example-2


If any one of the operand is
7<=10 or 7 ==10
or true, then condition
True
becomes TRUE
If both the operands are
7<10 and 7 >20
and true, then the
False
condition becomes TRUE
Reverse the state of
not not 7<10 False
operand / condition

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

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 11


PYTHON PROGRAMMING PYTHON PROGRAMMING BASICS

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

Variations of Assignment Operators:


Symbol Description Example-1
added and assign back the
>>> x+=2
+= result
7
to left operand
subtracted and assign back
>>> x-=2
-= the
3
result to left operand
multiplied and assign back
>>> x*=2
*= the
10
result to left operand
divided and assign back the >>> x/=2
/=
result to left operand 2

Bit wise operator:


These are the operators which are used to perform operation based on bits.
Symbol Description Example

| Performs binary OR operation 5 | 3 gives 7


Performs binary AND
& 5 & 3 gives 1
operation
Performs binary XOR
~ 5 ^ 3 gives 6
operation
Performs binary one's
^ ~5 gives -6
complement operation
Left shift operator: The
left-hand side operand bit is
<< moved left by the number 0010 << 2 gives 8
specified on the right-hand
side (Multiply by 2)
Left shift operator: The
left-hand side operand bit is
>> moved left by the number 2 gives 1
specified on the right-hand
side (Divided by 2)

Membership operators:

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 12


PYTHON PROGRAMMING PYTHON PROGRAMMING BASICS

Python has membership operators, which test for membership in a sequence,


such as strings, lists or tuples.
There are two membership operators are:

Symbol Description Example

Returns True if the specified x = [1,2,4,6,8]


in operand is found in the 3 in x
sequence false
Returns True if the specified x = [1,2,4,6,8]
Not in operand is found in the 3 not in x
sequence true

Identity operator:
Identity operators compare the memory locations of two objects.
There are two Identity operators are:

Symbol Description Example 1 Example 2

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! "

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 13


PYTHON PROGRAMMING PYTHON PROGRAMMING BASICS

print(a.strip()) # it display : "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

str2="python version 3.4.2"


print(str2.isalpha()) # it display : False

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 14


PYTHON PROGRAMMING PYTHON PROGRAMMING BASICS

13. isdigit():
It returns true when all character in the string is digit otherwise false.
s = "28212"
print(s.isdigit()) # it display : True

s = "Welcome abc 1"


print(s.isdigit()) # it display : False

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)
-----------------------------------------------------------------------------------------

Python Virtual Machine (PVM) or Interpreter


Python converts the source code into byte code. Byte code represents the fixed
set of instructions created by Python developers representing all types of operations.
The size of each byte code instruction is 1 byte.
The role of PVM is to convert the byte code instructions into machine code. So
that the computer can execute those machine code instruction and display the final
output. The PVM is also called as interpreter.
------------------------------------------------------------------------------------------

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 15


PYTHON PROGRAMMING PYTHON PROGRAMMING BASICS

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

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 16


PYTHON PROGRAMMING PYTHON PROGRAMMING BASICS

use third party application like numpy.

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.

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 17


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

Chapter 2

CREATING PYTHON PROGRAMS


INPUT AND OUTPUT STATEMENTS
Python provides functions like input() and print() are widely used for standard
input and output operations respectively.

Python Output statement Using print() function:


▪ The print() function prints the specified message to the screen.
▪ The message can be a string, or any other object, the object will be converted into
a string before written to the screen.

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

Python input statement Using input() function:


The input() function read values for a particular variable.

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.

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 1


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

Python supports four types of control statements.


1. Sequence.
2. Selection or branching.
3. Looping or iteration.
4. Jumping.

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

– The condition / expression must be enclosed within parentheses.


– The expression / condition is evaluated true, to perform the statement-1,
otherwise skip the statement-1 and perform next statement followed by if
structure.

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 2


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

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

– The condition within the parenthesis is evaluated to true then statement-block-1


is executed otherwise statement-block-2 is executed.
– The condition may be simple, compound or complex.
– Blocks can have multiple lines.
– As long as they are all indented with the same amount of spaces, they constitute
one block.

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 3


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

Example program Check if the given year is leap year or not.

year = int(input("Enter the year: "))


if (year % 4):
print(year, "is a leap year.")
else:
print(year, "is not a leap year.")

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

Example program Check if the given number is positive, negative or zero.

n = float(input("Enter any number: "))


print()
if n > 0:
print(n, "is a positive number.")
elif n == 0:
print("The entered value is ZERO.")
else:
print(n, "is a negative number.")
– When variable num is positive, Positive number is printed.

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 4


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

– If num is equal to 0, Zero is printed.


– If num is negative, Negative number is printed.
---------------------------------------
Nested if statement
▪ In this construct introduce new condition only if the pervious condition is true.
▪ The second if is nested in the first if condition.
▪ When the first condition is true, then second if condition is tested.

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

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 5


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

A loop statement allows us to execute a statement or group of statements


multiple times.

WHILE LOOP STATEMENT


A while loop statement in Python programming language repeatedly executes a
target statement as long as a given condition is true.

Syntax:
while expression:
statements

– Here, the statements can be a single statement or a group of statements.


– The expression should be any valid Python expression resulting in true or false.
– The true is any non-zero value and false is 0.

While loop Flowchart

Example program,
n = int(input("Enter a number: "))
while i <= n:
fact *= i
i += 1
print("\nFactorial of", n, "is:", fact)

Using else with while loop


Python allows us to use the else statement with the while loop also. The else
block is executed when the condition given in the while statement becomes false.

Consider the following example.


i=1
n = int(input("Enter a number: "))
while(i<=5):
print(i)
i=i+1
else:
print("The while loop exhausted")
FOR LOOP STATEMENT

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 6


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

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)

For loop Using range() function


The range() function
▪ The range() function is used to generate the sequence of the numbers.
▪ If we pass the range(10), it will generate the numbers from 0 to 9.
The syntax of the range() function is given below,

Syntax:
range(start,stop,step size)

– The start represents the beginning of the iteration.


– The stop represents that the loop will iterate till stop-1.
– The range(1,5) will generate numbers 1 to 4 iterations.

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 7


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

– 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)

# Python program to illustrate nested for loops in Python


for i in range(1, 5):
for j in range(i):
print(i, end=' ')
print()

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

The break statement:


▪ The break statement is used to terminate loops.
▪ When a break statement is encountered inside a loop, the loop is immediately
terminated and next statement immediately following the loop is executed.

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 8


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

▪ 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”

The continue statement:


▪ The name implies that loop to be continued with next iteration.
▪ The continue statement tells the python interpreter to skip the following statements
and continue with next iteration i.e. control automatically passes to the beginning of
the loop.
▪ In while loop, continue causes control to transfer directly to the conditional part and
continue the iteration.
▪ In case of for loop, update section of the loop will execute before test condition is
evaluated.

Syntax:
Continue

Example
i=0
while(i<=9):
i=i+1
if(i==4):
continue
print i
print “Out of loop”

The pass statement:


▪ The pass statement does not do anything.
▪ It is used with “if statement” or inside a loop to represent no operation.
▪ We use pass statement when we need a statement syntactically but we do not want
to do any operation.
▪ Pass is also used for empty control statement, function and classes.

Syntax:
pass

Example
i=0

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 9


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

while(i<=5):
i=i+1
if(i==4):
pass print i
print "Out of loop"

Difference between break and continue statement:

-------------------------------------------------------------------------------------------

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(‘ ‘).

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 10


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

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)

Example program 2 (to read n number and display)


import array as arr
n=int(input("enter araay limit"))
a=arr.array('i',[])
print("enter array elements")
for i in range(0, n):
ele = int(input())
a.append(ele)
print(a)

output:
enter araay limit 3
enter array elements
20
30
10
array('i', [20, 30, 10])

BUILT-IN ARRAY METHODS:


1. append()
Append any value to the array using append()

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 11


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

my_array = array('i', [1,2,3,4,5])


my_array.append(6)

2. Remove():
Remove any array element using remove() method

my_array = array('i', [1,2,3,4,5])


my_array.remove(4)

output
array('i', [1, 2, 3, 5])

We see that the element 4 was removed from the array.

3. Pop():
Remove last array element using pop() method, pop removes the last element
from the array.

my_array = array('i', [1,2,3,4,5])


my_array.pop()

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.

my_array = arr.array('i', [1, 2, 3, 4, 5])


print(my_array.index(2))

output:
5

5. reverse()
The reverse() method reverses the given data.

my_array = arr.array('i', [1, 2, 3, 4, 5])


a.reverse()
print(a)

output
array('i', [5, 4, 3, 2, 1])
----------------------------------------------------------------------------------------------

MULTI-DIMENSIONAL ARRAY
▪ An array containing more than one row and column is called multidimensional array.

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 12


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

▪ It is also called combination of several 1D arrays.


▪ 2D array is also considered as matrix.

A=array([1,2,3,4]) # Represents 1D array with 1 row


B=array([1,2,3,4],[5,6,7,8]) # Represents 2D array with 2 row

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)

NumPy Array build in functions:


1. Ndim():
The ndim() attribute can be used to find the dimensions of the array,

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:

Each item occupies four bytes in the above array.

3. Shape()

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 13


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

This array attribute returns a tuple consisting of array dimensions.

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:

NumPy Mathematical Operation


▪ In NumPy, basic mathematical functions operate elementwise on an array.
▪ Matrix addition and multiplication.
▪ We can use arithmetic operators like +, -,* ,/ to perform different operations on
matrices.

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

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 14


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

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

Creating a Function / Defining Functions


Python provides the def keyword to define the function.

The syntax of the define function is given below.


def my_function(parameters):
function_block
return expression

– 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.

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 15


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

▪ These functions are also called as standard functions.


▪ These functions are available in all versions of Python.

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.

WAP to illustrate math module


import math
print "Absolute value of -34.45 is ",math.fabs(-34.45)
print "Absolute value of 56.34 is ",math.fabs(56.34)
print "ceil of 100.12 is ",math.ceil(100.12)
print "ceil of 100.67 is ",math.ceil(100.67)
print "floor of 50.34 is ",math.floor(50.34)
print "floor of 50.89 is ",math.floor(50.89)
print "E rise to 2 is ",math.exp(1)
print "squre root of 25 is ",math.sqrt(25)

Create your own Module / Construct the user defined module:


▪ Module contain set of user defined function and regular expressions.
▪ In order to create user defined module, first create module description/user defined
functions and save with the module name along with extension py.
▪ We can those modules using other python programs my importing those module
name.

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

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 16


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

print("Sum is ", module1.sum1(x,y))


print("Multiple is ", module1.mul1(x,y))

➢ User-Defined Functions:
A user defined function represents a function which is named and provided by user to
produce the desired and certain output.

Simple rules to defined user defined function are:


▪ A function blocks begins with the keyword def followed by function name followed
by parenthesized parameter list and the colon
▪ Any input parameters or arguments should be placed within these parentheses.
▪ The body of the function followed by colon and is indented.
▪ The return statement exits a function. The return statement contain zero or with an
argument.
▪ Calling / invoking a function by its function-name.

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

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 17


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

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.

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 18


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

➢ 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.

Any recursive function can be divided into two parts.


First, there must be one or more base cases, to solve the simplest case, which is
referred to as the base case or the stopping condition
Next, recursive cases, here function is called with different arguments, which are
referred to as a recursive call. These are values that are handled by “reducing” the
problem to a “simpler” problem of the same form.

Example:
def factorial(n):
if n == 0:
return( 1)
else:
return (n*factorial(n-1)) # Recursive call

n=int(input("Enter a nonnegative integer: "))


print("Factorial of", n, "is", factorial(n))
---------------------------------------------------------------------------------------------

LIST DATA TYPE


▪ A List is a collection which is ordered and changeable / mutable.
▪ It allows duplicate members.
▪ A list is similar to array.
▪ Lists are represented by square brackets [] and the elements are separated by
comma.
▪ The main difference between a list and an array is that a list can store different data
type elements, but an array can store only one type of elements.
▪ List can grow dynamically in memory but the size of array is fixed and they cannot
grow dynamically.

The following are the characteristics of a Python list:

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 19


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

➢ Values are ordered


➢ Mutable
➢ A list can hold any number of values
➢ A list can add, remove, and modify the values

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

3. Joining two list:


▪ Concatenate two lists together.
▪ The plus(+) operator used to concatenate two list
Example
a= [1,2,3]
b=[4,5]
c=a+b
print c # it produce [1,2,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.

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 20


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

Example:
k=[]
for i in range(0,3):
el=input("enter value")
k.append(el)
print(k)

print(len(k))

2. append(): To add an item to the end of a list.

Example
k=[]
for i in range(0,3):
el=input("enter value")
k.append(el)
print(k)

3. insert(): To insert a new element at the specified location.

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=[]

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 21


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

for i in range(0,3):
el=input("enter value")
k.append(el)
print(k)

k.sort()
print(k)

6. reverse(): This function reverse the list elements.

Example
k=[]
for i in range(0,3):
el=input("enter value")
k.append(el)
print(k)

print(k.reverse())

7. count(value): To find the number of times a value occurs in a list.


8. extend(): To add the items in one list to an existing another list.
9. pop(): To returns and remove the rightmost element from the list.
-----------------------------------------------------------------------------------------
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.

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

Creating Python Dictionary


▪ Creating a dictionary is as simple as placing items inside curly braces {} separated
by commas.
▪ An item has a key and a corresponding value that is expressed as a pair (key:
value).

Example

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 22


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

my_dict = {} # empty dictionary

my_dict = {1: 'apple', 2: 'ball'} # dictionary with integer keys

my_dict = {'name': 'aaa', 1: [2, 4, 3]} # dictionary with mixed keys

OUTPUT:
{}
{1: 'apple', 2: 'ball'}
{'name': 'John', 1: [2, 4, 3]}

Accessing Elements from Dictionary


▪ While indexing is used with other data types to access values, a dictionary
uses keys.
▪ Keys can be used either inside square brackets [] or with the get() method.

Example
my_dict = {'name': 'aaa', 'age': 26}
print(my_dict['name'])
print(my_dict.get('age'))

OUTPUT:
Jack
26

Dictionary functions and methods:


1. Python Dictionary clear():
▪ It removes all the items from the dictionary.
▪ The clear() method removes all items from the dictionary.

Example
d = {1: "one", 2: "two"}
d.clear()
print('d =', d)

Output
d = {}

2. Python Dictionary copy()


They copy() method returns a shallow copy of the dictionary.

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'}

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 23


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

3. Python Dictionary get()


▪ It returns the value from a dictionary associated with the name.
▪ The get() method returns the value for the specified key if key is in dictionary.

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

4. Python Dictionary pop():


It remove the last item in the dictionary.

Example
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
print(squares.pop(4))

5. Python Dictionary keys()


▪ It returns list of all the keys used in the dictionary, in arbitrary order.
▪ The keys() method returns a view object that displays a list of all the keys in the
dictionary

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([])

6. Python Dictionary values()


▪ It returns list of all values used in the dictionary.
▪ The values() method returns a view object that displays a list of all the values in
the dictionary.

Example
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }
print(sales.values())

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 24


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

Output
dict_values([2, 4, 3])

7. Python Dictionary items()


▪ It returns list of tuple(key : value) used in the dictionary.
▪ The items() method returns a view object that displays a list of dictionary's (key,
value) tuple pairs.

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.

Creating Python Sets


A set is created by placing all the items (elements) inside curly braces {},
separated by comma, or by using the built-in set() function.

# Different types of sets in Python

# set of integers
my_set = {1, 2, 3}
print(my_set)

# set of mixed datatypes


my_set = {1.0, "Hello", (1, 2, 3)}
print(my_set)

Output
{1, 2, 3}
{1.0, (1, 2, 3), 'Hello'}

Set Operations

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 25


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

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.

Difference between list and tuple


LIST TUPLE

List are enclosed in square brackets [] Tuple are enclosed in parentheses ()

Element and size can be changed Can’t be changed.

Is a mutable object Is a Immutable object


It can grow and shrink as needed It is read only list
-----------------------------------------------------------------------------------------
FILES

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 26


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

▪ Files are used to store data permanently.


▪ Data used in a program is temporary; unless the data is specifically saved, it is lost
when the program terminates.
▪ To permanently store the data created in a program, you need to save it in a file on
a disk or some other permanent storage device. The file can be transported and can
be read later by other programs.
▪ Python’s standard library has a file class that makes it easy for programmers to
make objects that can store data to the disk and retrieves data from the disk.

In Python, a file operation takes place in the following order:


➢ Open a file
➢ Read or write (perform operation)
➢ Close the file

Opening Files in Python


▪ Python has a built-in open() function to open a file.
▪ In order to read and write into a file, we will use the open() as built-in function
to open the file in specified mode of operations. The open() function creates an
file_object object.

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.

The File open modes are:


Mode Description

"r" Opens a file for reading.


Opens a new file for writing. If the file already exists, it hold contents are
"w"
destroyed
"a" Opens a file for appending data from the end of the file.

"rb" Opens a file for reading binary data.

"wb" Opens a file for writing binary data.

"r+" Opens a file for reading and writing.


Opens a file for reading and writing. If the file doesn't exist, then a new
"w+"
file is created.

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.

2. f = open ('student.txt', 'w')

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 27


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

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.

3. f = open ('student.txt', 'a')


This statement creates a file object as f, it opens file student.txt for append
mode if the file is exists. That means add new content to the end of existing file.

Writing to Files in Python


▪ In order to write into a file in Python, we need to open it in write w, append a
▪ Writing text to a file.
▪ The 'w' mode creates a new file. If the file already exists, then the file would be
overwritten. We will use the write() function.

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.

Closing Files in Python


▪ When we are done with performing operations on the file, we need to properly close
the file.
▪ Closing a file will free up the resources that were tied with the file. It is done using
the close() method available in Python.

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

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 28


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

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].

▪ The error handling code basically consists of two segments,


o To detect the errors and throw Exception.
o To catch Exception and perform appropriate action.

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

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 29


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

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.

A try with multiple except clause and finally block:


▪ In some cases, more than one exception should be raised by a single piece of code.
▪ To handle this type of situation, you specify two or more except clauses, each
catching different types of exception.
▪ When an exception is thrown, each except statement is inspected in order, and the
first one whose type matches that of the exception is executed.
▪ After one except statement executes, the others are bypassed, and execution
continues after the try / except block.

Syntax # Multiple except


try:
<body>
except <ExceptionType-1>:
<handler>
except <ExceptionType-2>:
<handler>
:
except <ExceptionType-n>:
<handler>

finally block:

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 30


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

▪ 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.

Life Cycle of thread:


To understand the functionality of threads in depth, we need to learn about the
lifecycle of the threads or the different thread states.
Typically, a thread can exist in five distinct states.
The different states are shown below:
New Thread
A new thread begins its life cycle in the new state. But, at this stage, it has not yet
started and it has not been allocated any resources. We can say that it is just an instance
of an object.

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

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 31


PYTHON PROGRAMMING CREATING PYTHON PROGRAMS

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.

Example Program to illustrate multithreading.


import _thread
import time
def cal_sqre(num): # define the cal_sqre function
print(" Calculate the square root of the given number")
for n in num:
time.sleep(0.6) # at each iteration it waits for 0.3 time
print(' Square is : ', n * n)
def cal_cube(num): # define the cal_cube() function
print(" Calculate the cube of the given number")
for n in num:
time.sleep(0.3) # at each iteration it waits for 0.3 time
print(" Cube is : ", n * n * n)
arr = [4, 5, 6, 7, 2] # given array
t1 = time.time() # get total time to execute the functions
cal_sqre(arr) # call cal_sqre() function
cal_cube(arr) # call cal_cube() function
print(" Total time taken by threads is :", time.time() - t1)
# print the total time
--------------------------------------------------------------------------------------

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 32


PYTHON PROGRAMMING OBJECT ORIENTED PROGRAMMING

Chapter 3

OBJECT ORIENTED PROGRAMMING


Python is an object-oriented language since its beginning. It allows us to develop
applications using an Object-Oriented approach. In Python, we can easily create and
use classes and objects.

Major principles of object-oriented programming system are given below,


➢ Class:
A Class represents a set of objects that shares common characteristics and
behaviour.
➢ Object:
An object is a real world entity / real world identifiable entity which represent
characteristics, state and behaviour.
➢ Inheritance:
In OOP, the concept of inheritance provides the idea of reusability. This means that
we can add additional features to an existing class without modifying it. This is
possible by deriving a new class form the existing one.
➢ Polymorphism:
Polymorphism means the ability to take more than one form. An operation may
exhibit different behavior in different instance. The behavior depends upon the type
of data used in the operation.
➢ Method
The method is a function that is associated with an object. In Python, a method is
not unique to class instances.
➢ Data Abstraction
Abstraction is used to hide internal details and show only functionalities. Abstracting
something means to give names to things so that the name captures the core of
what a function or a whole program does.
➢ Encapsulation
The wrapping up of data and method into a single unit is known as Encapsulation.
The data is not accessible to the outside world and only those methods, which are
wrapped in the class, can access it. These methods provide the interface between
the object data and the program.
----------------------------------------------------------------------------------------
CLASS
Class defined as collection of objects, that has some specific attributes and
methods.

Creating a class
Creating a class in Python with the following syntax:

Class classname:
<method definition-1>
<method definition-n>

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 1


PYTHON PROGRAMMING OBJECT ORIENTED PROGRAMMING

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.

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 2


PYTHON PROGRAMMING OBJECT ORIENTED PROGRAMMING

Here is an example class with a method:


class first:
def display(self):
print(“welcome”)

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>

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 3


PYTHON PROGRAMMING OBJECT ORIENTED PROGRAMMING

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

Single level Inheritance


It contains only one base class and only one derived class. One parent class one child
class.

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):

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 4


PYTHON PROGRAMMING OBJECT ORIENTED PROGRAMMING

def add(self):
self.z = self.a + self.b
print("Sum of two numbers:", self.z)
obj = Second()
obj.input()
obj.add()

Multi level inheritance


If a class is derived from another derived class, It is called multilevel inheritance.

Syntax
class BaseClassName():
<statement-1>
..
<statement-N>

class DerivedClassName(BaseClassName):
<statement-1>
..
<statement-N>

class DerivedClassName (DerivedClassName):


<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

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 5


PYTHON PROGRAMMING OBJECT ORIENTED PROGRAMMING

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>

class BaseClassName (object):


<statement-1>
..
<statement-N>

class DerivedClassName(BaseClassName 1, BaseClassName 2):


<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:"))

class Third(First, Second):

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 6


PYTHON PROGRAMMING OBJECT ORIENTED PROGRAMMING

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)

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 7


PYTHON PROGRAMMING OBJECT ORIENTED PROGRAMMING

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()

Hybrid inheritance: -It is a combination of single, hierarchical, multiple and multi-


level inheritance.

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.

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 8


PYTHON PROGRAMMING OBJECT ORIENTED PROGRAMMING

There are two types of constructor,


➢ default constructor
➢ parameterized constructor

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()
----------------------------------------------------------------------------------------------------------------------------- --------

Destructor [ del () ]Method :


▪ A destructor is a special method, which is executed automatically when an object
scope is ended.
▪ Like constructor, there is an equivalent destructor special method called __del__().
▪ Due to the way Python manages garbage collection of objects, this function is not
executed until all references to an instance object have been removed.
▪ Destructors in Python are methods which provide special processing before instances
are de-allocated and are not commonly implemented since instances are rarely de-
allocated explicitly.

Example:

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 9


PYTHON PROGRAMMING OBJECT ORIENTED PROGRAMMING

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.

Example program to illustrate Method overriding:


class Employee:
def message(self):
print('This message is from Employee Class')

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):

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 10


PYTHON PROGRAMMING OBJECT ORIENTED PROGRAMMING

if a!=None and b!=None and c!=None:


s=a+b+c
elif a!=None and b!=None
s=a+b
else:
s=a
print(s)

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.

Example of Creating Package


Let’s create a package named Cars and build three modules in it namely, Bmw,
Audi and Nissan.

Below steps and example Python code to illustrate the Modules


– First we create a directory and name it Cars.
– Then we need to create modules.

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.

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 11


PYTHON PROGRAMMING OBJECT ORIENTED PROGRAMMING

#Python code to illustrate the Module Audi


class Audi:
def __init__(self):
self.models = ['q7', 'a6', 'a8', 'a3']
def outModels(self):
print('These are the available models for Audi')
for model in self.models:
print('\t%s ' % model)

Then we create another file with the name Nissan.py and add the similar type of code
to it with different members.

# Python code to illustrate the Module


class Nissan:
def __init__(self):
self.models = ['altima', '370z', 'cube', 'rogue']
def outModels(self):
print('These are the available models for Nissan')
for model in self.models:
print('\t%s ' % model)

– 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.

from Bmw import Bmw


from Audi import Audi
from Nissan import Nissan

– Now, let’s use the package that we created.

To do this make a sample.py file in the same directory where Cars package is located
and add the following code to it:

# Import classes from your brand new package


from Cars import Bmw
from Cars import Audi
from Cars import Nissan

# Create an object of Bmw class & call its method


ModBMW = Bmw()
ModBMW.outModels()

# Create an object of Audi class & call its method

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 12


PYTHON PROGRAMMING OBJECT ORIENTED PROGRAMMING

ModAudi = Audi()
ModAudi.outModels()

# Create an object of Nissan class & call its method


ModNissan = Nissan()
ModNissan.outModels()

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 13


PYTHON PROGRAMMING GRAPHICAL USER INTERFACE

Chapter-5

GRAPHICAL USER INTERFACE


The User can Interface with an application through graphics or an image is called
GUI. It can be happen with some events, like click, drag, scroll, select etc…
The user need not remember any commands. User can perform task just by
clicking on relevant images.

Advantages of GUI in Python


 It is user friendly.
 It adds attraction and beauty to any application by adding pictures, colors,
menus, animation.
 It is possible to simulate the real life objects using GUI.
 GUI helps to create graphical components like push button, radio button, check
box, text box, menus etc.,

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.

General steps involved in basic GUI Program:


 Create a root Window :
The root window is top level window that provides rectangular space on the screen.
We can display text, color, images, events etc.. over that root window. First we need
to import module tkinter then, create root window object.

Example:- from tkinter import * or import tkinter


root=TK( ) root=tkinter .TK( )

 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’)

– Note: Curser can be circle, pencil, star, watch tec..

 Create widgets components:


For canvas – create line, rectangle and any geometric object.
For Frame – Button, text box, link, check box etc..

JANHAVI N L, Asst, Proof, Dept. of BCA, VVFGC, Tumkur Page 1


PYTHON PROGRAMMING GRAPHICAL USER INTERFACE

 Create a Event Handler


Write the function/code for corresponding event/widgets.

Example program to illustrate or draw line, oval, polygon, rectangle and text.

From tkinter import *

Root=TK()

Root.title(“Basic shapes”)

Root.gromatry(“300*500”) #area of GUI Window, #300 width & 500height

# Set Canvas area where you want to put[ widges or shapes]

Can=canvas (root, width=300, height=200,bg=”white”)

# Create Rectangle over the canvas

Can.create-rectangle (50,30,200,25) # x,y co-ordinator sharting point & Ending


point

Can.create-rectangle (50,30,300,50, fill=’blue’)

Can.create-rectangle(50,20,70,40, width=2, fill=”gray” outline”yellow” activefill”green)

#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()

--------------------------------------------------------------------------------------

JANHAVI N L, Asst, Proof, Dept. of BCA, VVFGC, Tumkur Page 2


PYTHON PROGRAMMING GRAPHICAL USER INTERFACE

Frame
Frame is a similar to canvas. It is a child window under root window. It can hold
the components of forms (like object).

Example:- create frame class object


F=frame(root,height=400,width=500,bg=”yellow”, cursor=”curve”
– F is object of frame class
– Height and width represent the area of frames in pixels.
– Bg represents backgroung color to be displayed
– Cursor represents type of the cursor to be displayed in the frame.

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.

Basic building blocks of GUI application:


The widgets are:-
 Button
 Label
 Textbox
 Checkbox
 List box
 Option buttons
 Scroll bars
 Menus

Steps to create widget object:


 Create a widget object
B=button(f, text=“Submit”)
 Define the event performed by the widget
def buttonClick(self) :
print(“You have clicked submit button”)
 Clicking event should be linked with the callback handler
B.bind(‘<Button-1>’, buttonClick)
 Call event loop
root.mainloop()

JANHAVI N L, Asst, Proof, Dept. of BCA, VVFGC, Tumkur Page 3


PYTHON PROGRAMMING GRAPHICAL USER INTERFACE

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)

– Identifies is a name of the object of button class.


– Parent/root are name of the root window.
– Options are properties which we can use of buttons.

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)

– Identifies is a name of the object of button class.


– Parent/root are name of the root window.
– Options are properties which we can use of buttons.

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

e2 = Entry(top, width = 20).place(x = 100, y = 90)


top.mainloop()

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)

– Identifies is a name of the object of button class.


– Parent/root are name of the root window.
– Options are properties which we can use of buttons.

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)

– Identifies is a name of the object of button class.


– Parent/root are name of the root window.

JANHAVI N L, Asst, Proof, Dept. of BCA, VVFGC, Tumkur Page 5


PYTHON PROGRAMMING GRAPHICAL USER INTERFACE

– Options are properties which we can use of buttons.

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.

A text is created as an object of Text class as,


t=Text(f,width=20, height=3, font=('Times',20,'italic'), fg='blue',
bg="yellow", wrap=WORD)

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.

WAP to illustrate button, label, text, checkbox and radio button


from tkinter import *

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=Button(f, text="Ok", width=15,height=3, bg="yellow",


fg="blue") b.pack()

b.bind("<Button-1>", buttonClick)

l=Label(f, text=" Label


Demo",width=25,height=3,
font=('Times',14,'bold'),
fg='blue',bg='yellow') l.pack()

JANHAVI N L, Asst, Proof, Dept. of BCA, VVFGC, Tumkur Page 6


PYTHON PROGRAMMING GRAPHICAL USER INTERFACE

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.

JANHAVI N L, Asst, Proof, Dept. of BCA, VVFGC, Tumkur Page 7


PYTHON PROGRAMMING GRAPHICAL USER INTERFACE

Different types of charts


 Pie chart
 Histogram
 Line chart

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)

– Plot is method of matplotlib.


– X and Y are data Sets.

Python Program to implements line charts,


import matplotlib .pyplot as plt
X = [3,5,7, 8,15,18]
Y = [10,15,18,22,24,25]
PH.title (“line chart”)
Plt.plot(X,Y)
Plt.show()

Python program to plot 2 line chart


Import matplotlib.pyplot as plt
X = [3,5,7, 8,15,18]
Y = [10,15,18,22,24,25]
X1 = [3,5,7, 8,15,18]
Y1 = [10,15,18,22,24,25]
Plt.plot(X,Y,’g—‘,X1,Y1,’r’)

JANHAVI N L, Asst, Proof, Dept. of BCA, VVFGC, Tumkur Page 8


PYTHON PROGRAMMING GRAPHICAL USER INTERFACE

Bar charts

Import matplotlib,ptplot as plt


Course=(‘BCA’,’BCOM’,’MCOM’,’MCA’)
No stu=[300,350,100,200]
Plt.bar(course, No.stu)
Plt.title(“ “)
Plt.xlable(“ “)
Ply.ylable(“ “)
Plt.show( )

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

JANHAVI N L, Asst, Proof, Dept. of BCA, VVFGC, Tumkur Page 9


PYTHON PROGRAMMING GRAPHICAL USER INTERFACE

Pie chart

Import matplotlib,ptplot as plt


Sub=’python’,’c++’,’webtech’,’jaca’,’c#’
Jcount=[700,200,600,600,500]
Col=(‘red’,’blue’,’white’,’green’,’pink’]
Plot.pie(Jobcourt,lable=SUB,colors=col)
Plot.title(“ “)
Plot.show( )

JANHAVI N L, Asst, Proof, Dept. of BCA, VVFGC, Tumkur Page 10


Python for Finance

NumPy, Matplotlib,and Pandas

Juan F. Imbet Ph.D. 1


Python for Finance

Community developed libraries

Juan F. Imbet Ph.D. 2


Python for Finance

Juan F. Imbet Ph.D. 3


Python for Finance

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

Juan F. Imbet Ph.D. 4


Python for Finance

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])

Juan F. Imbet Ph.D. 5


Python for Finance

Numpy arrays are faster than lists


x = list(range(1000000))
y = np.array(x)
%timeit sum(x)
%timeit np.sum(y)

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)

Juan F. Imbet Ph.D. 6


Python for Finance

Why are numpy arrays faster than lists?


NumPy arrays are faster than lists because they are stored efficiently in memory, allowing
for faster data access and manipulation. They also support vectorized operations, which
are optimized and implemented in lower-level languages like C, making them much faster
than equivalent Python loops. Additionally, NumPy takes advantage of CPU caching,
optimized algorithms, and specialized functions, resulting in faster computations compared
to pure Python list operations.

Juan F. Imbet Ph.D. 7


Use numpy for linear algebra
Python for Finance

Most common functions


X = np.array([[1, 2, 3], [4, 5, 6]])
Y = np.array([[1, 2], [3, 4], [5, 6]])
x = np.array([1, 2, 3])

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

Juan F. Imbet Ph.D. 8


Python for Finance

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')

Juan F. Imbet Ph.D. 9


Python for Finance

Juan F. Imbet Ph.D. 10


Python for Finance

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

Juan F. Imbet Ph.D. 11


Python for Finance

Matplotlib - Most common plots


Line plot - plt.plot
Scatter plot - plt.scatter
Bar plot - plt.bar
Histogram - plt.hist
Box plot - plt.boxplot
Pie chart - plt.pie
Matplotlib is a very powerful library. Graphs can be customized in many ways, and a
complete guide would be too long.
Juan F. Imbet Ph.D. 12
Python for Finance

Customizing plots
plt.title- Set the title of the plot
plt.xlabel - Set the label for the x-axis

plt.ylabel - Set the label for the y-axis

plt.rotate - Rotate the x-axis labels

plt.legend - Show the legend

plt.show - Show the plot

Check out the examples here

Juan F. Imbet Ph.D. 13


Python for Finance

Juan F. Imbet Ph.D. 14


Python for Finance
Pandas
Pandas is a library for data analysis. Probably the most used library in data science. Pandas
is imported using the import keyword. Pandas is usually imported using the alias pd .
import pandas as pd

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 - Load data from a file


Pandas can load data from CSV files, JSON files, Excel files, parquet files, and SQL
databases.
df = pd.read_csv('file.csv')
df = pd.read_json('file.json')
df = pd.read_excel('file.xlsx')
df = pd.read_sql('SELECT * FROM table', connection)
df = pd.read_parquet('file.parquet')

Juan F. Imbet Ph.D. 16


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()

Juan F. Imbet Ph.D. 17


Python for Finance
Dataframe indexing
Dataframes can be indexed using the iloc and loc methods. The iloc method is
used to index dataframes by position. The loc method is used to index dataframes by
label. Dataframes can also be indexed using the [] operator. The [] operator is used to
index dataframes by label.
Using iloc
df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})
df.iloc[0] # First row
df.iloc[0, 0] # First element of first row
df.iloc[:, 0] # First column
df.iloc[0:2] # First two rows
df.iloc[0:2, 0:2] # First two rows and columns
df.iloc[[0, 2]] # First and third row
df.iloc[[0, 2], [0, 2]] # First and third row and column
df.iloc[lambda x: x.index % 2 == 0] # Even rows
df.iloc[lambda x: x.index % 2 == 0, lambda x: x.columns % 2 == 0] # Even rows and columns

Juan F. Imbet Ph.D. 18


Python for Finance

Dataframe indexing (2)


Using loc
df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})
df.loc[0] # First row
df.loc[0, 'a'] # First element of first row
df.loc[:, 'a'] # First column
df.loc[0:2] # First two rows
df.loc[0:2, 'a':'b'] # First two rows and columns
df.loc[[0, 2]] # First and third row
df.loc[[0, 2], ['a', 'b']] # First and third row and column
df.loc[lambda x: x.index % 2 == 0] # Even rows
df.loc[lambda x: x.index % 2 == 0, lambda x: x.columns % 2 == 0] # Even rows and columns

Juan F. Imbet Ph.D. 19


Python for Finance
Data operations
Dataframes can be modified using the assign method. The assign method is used to
modify dataframes by adding new columns. Dataframes can also be modified using the
[] operator. The [] operator is used to modify dataframes by adding new columns.

df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})


df['c'] = df.a + df.b # Add a new column
df['c'] = df['a'] + df['b'] # Add a new column

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.

Juan F. Imbet Ph.D. 20


Python for Finance

Inplace vs not inplace


Dataframes can be modified inplace or not inplace. The inplace parameter is used to
specify whether or not the dataframe should be modified inplace. The inplace parameter
has two possible values: True and False . For efficiency reasons, it is recommended to
not modify dataframes inplace.
df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})
df.rename(columns={'a': 'A'}, inplace=True) # Modify inplace
df = df.rename(columns={'a': 'A'}) # Modify not inplace

Juan F. Imbet Ph.D. 21


Python for Finance

The groupby operation produces a DataFrameGroupBy object


df = pd.DataFrame({'group': ['A', 'A', 'B', 'B'], 'value': [1, 2, 3, 4]})
df.groupby('group')

<pandas.core.groupby.generic.DataFrameGroupBy object at 0x7f8e1c0b5d90>

Juan F. Imbet Ph.D. 22


Python for Finance
apply and custom functions
The apply method is used to apply a function to a dataframe. The apply method has
two arguments: a function, and an axis. The function is applied to each row or column of
the dataframe. The axis is used to specify whether the function should be applied to each
row or column. The axis can be 0 for rows, or 1 for columns. The default axis is 0 .
df = pd.DataFrame({'group': ['A', 'A', 'B', 'B'], 'value': [1, 2, 3, 4]})
df.groupby('group').apply(lambda x: x.value.sum())
# or
df.groupby('group')['value'].apply(lambda x: x.sum())
# or
df.groupby('group').value.sum()

group
A 3
B 7

Juan F. Imbet Ph.D. 23


Python for Finance

Homework (Optional, do not use GPT)


In this homework you will process and analyze a dataset of the Titanic passengers. The
dataset is available here. The dataset contains the following columns:
survived - Whether the passenger survived (0 = No, 1 = Yes)

pclass - The class of the passenger (1 = 1st, 2 = 2nd, 3 = 3rd)

sex - The

age - The age of the passenger

sibsp - The number of siblings or spouses the passenger had aboard the Titanic

Juan F. Imbet Ph.D. 24


Python for Finance

parch - The number of parents or children the passenger had aboard the Titanic
fare - The fare the passenger paid

embarked - The port the passenger embarked from (C = Cherbourg, Q =


Queenstown, S = Southampton)
class - The class of the passenger

who - (man, woman, child).

adult_male - Whether the passenger is an adult male.

deck - The deck the passenger was on.

embark_town - The town the passenger embarked from.

alive - Whether the passenger survived (yes, no).

alone - Whether the passenger was alone.

Juan F. Imbet Ph.D. 25


Python for Finance
Questions
Estimate the probability of survival for a passenger in each class. (1, 2, 3). The
probability of survival is the number of survivors divided by the total number of
passengers in each class.
How does this probability change if the passenger was a man, a woman, a male child,
or a female child?
Determine if the event of not surviving given that the passenger was an adult male is
independent of the class of the passenger. Recall that two events are independent if
the probability of one event occurring does not affect the probability of the other event
occurring.

Juan F. Imbet Ph.D. 26


Python for Finance

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?

Juan F. Imbet Ph.D. 27


Python SQLite

i
Python SQLite

About the Tutorial


Python is a general-purpose interpreted, interactive, object-oriented, and high-level
programming language. It was created by Guido van Rossum during 1985-1990. Like Perl,
Python source code is also available under the GNU General Public License (GPL). This
tutorial gives enough understanding on Python programming language.

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.

Copyright & Disclaimer


 Copyright 2020 by Tutorials Point (I) Pvt. Ltd.

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

Copyright & Disclaimer .................................................................................................................................... ii

Table of Contents ........................................................................................................................................... iii

1. Python SQLite ― Introduction .................................................................................................................. 1

2. Python SQLite — Establishing Connection................................................................................................. 4

Establishing connection using python ............................................................................................................. 4

3. Python SQLite ― Create Table .................................................................................................................. 5

Creating a table using python .......................................................................................................................... 6

4. Python SQLite — Insert Data ..................................................................................................................... 8

Inserting data using python ............................................................................................................................. 9

5. Python SQLite ― Select Data .................................................................................................................. 11

Retrieving data using python......................................................................................................................... 13

6. Python SQLite — Where Clause .............................................................................................................. 15

Where clause using python ........................................................................................................................... 16

7. Python SQLite ― Order By ...................................................................................................................... 18

ORDER BY clause using python ...................................................................................................................... 20

8. Python SQLite — Update Table ............................................................................................................... 22

Updating existing records using python ........................................................................................................ 23

9. Python SQLite ― Delete Data ................................................................................................................. 26

Deleting data using python ........................................................................................................................... 27

10. Python SQLite — Drop Table ................................................................................................................... 29

Dropping a table using Python ...................................................................................................................... 30

11. Python SQLite ― Limit ............................................................................................................................ 31

LIMIT clause using Python ............................................................................................................................. 32

iii
Python SQLite

12. Python SQLite — Join .............................................................................................................................. 34

Join clause using python ................................................................................................................................ 35

13. Python SQLite ― Cursor Object............................................................................................................... 37

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.

Python sqlite3 module APIs


Following are important sqlite3 module routines, which can suffice your requirement to
work with SQLite database from your Python program. If you are looking for a more
sophisticated application, then you can look into Python sqlite3 module's official
documentation.

S.No. API & Description

1 sqlite3.connect(database [,timeout ,other optional arguments])

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.

3 cursor.execute(sql [, optional parameters])

This routine executes an SQL statement. The SQL statement may be


parameterized (i. e. placeholders instead of SQL literals). The sqlite3 module
supports two kinds of placeholders: question marks and named placeholders
(named style).

For example − cursor.execute("insert into people values (?, ?)", (who, age))

4 connection.execute(sql [, optional parameters])

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)

This routine executes an SQL command against all parameter sequences or


mappings found in the sequence sql.

6 connection.executemany(sql[, parameters])

This routine is a shortcut that creates an intermediate cursor object by calling


the cursor method, then calls the cursor.s executemany method with the
parameters given.

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)

This routine is a shortcut that creates an intermediate cursor object by calling


the cursor method, then calls the cursor's executescript method with the
parameters given.

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:

Establishing connection using python


You can communicate with SQLite2 database using the SQLite3 python module. To do so,
first of all you need to establish a connection (create a connection object).

To establish a connection with SQLite3 database using python you need to:

 Import the sqlite3 module using the import statement.

 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:

CREATE TABLE database_name.table_name(


column1 datatype PRIMARY KEY(one or more columns),
column2 datatype,
column3 datatype,
.....
columnN datatype
);

Example
Following SQLite query/statement creates a table with name CRICKETERS in SQLite
database:

sqlite> CREATE TABLE CRICKETERS (


First_Name VARCHAR(255),
Last_Name VARCHAR(255),
Age int,
Place_Of_Birth VARCHAR(255),
Country VARCHAR(255)
);
sqlite>

Let us create one more table OdiStats describing the One-day cricket statistics of each
player in CRICKETERS table.

sqlite> CREATE TABLE ODIStats (


First_Name VARCHAR(255),
Matches INT,
Runs INT,
AVG FLOAT,
Centuries INT,
HalfCenturies INT

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>

Creating a table using python


The Cursor object contains all the methods to execute quires and fetch data etc. The
cursor method of the connection class returns a cursor object.

Therefore, to create a table in SQLite database using python:

 Establish connection with a database using the connect() method.

 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')

#Creating a cursor object using the cursor() method


cursor = conn.cursor()

#Doping EMPLOYEE table if already exists.


cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
#Creating table as per requirement
sql ='''CREATE TABLE EMPLOYEE(
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
6
Python SQLite

SEX CHAR(1),
INCOME FLOAT)'''
cursor.execute(sql)
print("Table created successfully........")

# Commit your changes in the database


conn.commit()

#Closing the connection


conn.close()

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:

INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)


VALUES (value1, value2, value3,...valueN);

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:

sqlite> CREATE TABLE CRICKETERS (


First_Name VARCHAR(255),
Last_Name VARCHAR(255),
Age int,
Place_Of_Birth VARCHAR(255),
Country VARCHAR(255)
);
sqlite>

Following PostgreSQL statement inserts a row in the above created table.

sqlite> insert into CRICKETERS (First_Name, Last_Name, Age, Place_Of_Birth,


Country) values('Shikhar', 'Dhawan', 33, 'Delhi', 'India');
sqlite>

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.

sqlite> insert into CRICKETERS (First_Name, Last_Name, Country) values


('Jonathan', 'Trott', 'SouthAfrica');
sqlite>

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

sqlite> insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');


sqlite> insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');
sqlite> insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India');
sqlite>

After inserting the records into a table you can verify its contents using the SELECT
statement as shown below:

sqlite> select * from cricketers;


Shikhar |Dhawan | 33 | Delhi | India
Jonathan |Trott | | | SouthAfrica
Kumara |Sangakkara | 41 | Matale | Srilanka
Virat |Kohli | 30 | Delhi | India
Rohit |Sharma | 32 | Nagpur | India
sqlite>

Inserting data using python


To add records to an existing table in SQLite database:

 Import sqlite3 package.

 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')

#Creating a cursor object using the cursor() method


cursor = conn.cursor()

# Preparing SQL queries to INSERT a record into the database.


9
Python SQLite

cursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX,


INCOME) VALUES ('Ramya', 'Rama Priya', 27, 'F', 9000)''')

cursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX,


INCOME) VALUES ('Vinay', 'Battacharya', 20, 'M', 6000)''')

cursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX,


INCOME) VALUES ('Sharukh', 'Sheik', 25, 'M', 8300)''')

cursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX,


INCOME) VALUES ('Sarmista', 'Sharma', 26, 'F', 10000)''')

cursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX,


INCOME) VALUES ('Tripthi', 'Mishra', 24, 'F', 6000)''')

# Commit your changes in the database


conn.commit()

print("Records inserted........")

# Closing the connection


conn.close()

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:

SELECT column1, column2, columnN FROM table_name;

Example
Assume we have created a table with name CRICKETERS using the following query:

sqlite> CREATE TABLE CRICKETERS (


First_Name VARCHAR(255),
Last_Name VARCHAR(255),
Age int,
Place_Of_Birth VARCHAR(255),
Country VARCHAR(255)
);
sqlite>

And if we have inserted 5 records in to it using INSERT statements as:

sqlite> insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi', 'India');


sqlite> insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown',
'SouthAfrica');
sqlite> insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');
sqlite> insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');
sqlite> insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India');
sqlite>

Following SELECT query retrieves the values of the columns FIRST_NAME, LAST_NAME
and, COUNTRY from the CRICKETERS table.

sqlite> SELECT FIRST_NAME, LAST_NAME, COUNTRY FROM CRICKETERS;


Shikhar|Dhawan|India
Jonathan|Trott|SouthAfrica
Kumara|Sangakkara|Srilanka

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:

sqlite> .width 10, 10, 4, 10, 13


sqlite> SELECT * FROM CRICKETERS;

12
Python SQLite

First_Name Last_Name Age Place_Of_B Country


---------- ---------- ---- ---------- -------------
Shikhar Dhawan 33 Delhi India
Jonathan Trott 38 CapeTown SouthAfrica
Kumara Sangakkara 41 Matale Srilanka
Virat Kohli 30 Delhi India
Rohit Sharma 32 Nagpur India
sqlite>

Retrieving data using python


READ Operation on any database means to fetch some useful information from the
database. You can fetch data from MYSQL using the fetch() method provided by the sqlite
python module.

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')

#Creating a cursor object using the cursor() method

13
Python SQLite

cursor = conn.cursor()

#Retrieving data
cursor.execute('''SELECT * from EMPLOYEE''')

#Fetching 1st row from the table


result = cursor.fetchone();
print(result)

#Fetching 1st row from the table


result = cursor.fetchall();
print(result)

#Commit your changes in the database


conn.commit()

#Closing the connection


conn.close()

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:

SELECT column1, column2, columnN


FROM table_name
WHERE [search_condition]

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:

sqlite> CREATE TABLE CRICKETERS (


First_Name VARCHAR(255),
Last_Name VARCHAR(255),
Age int,
Place_Of_Birth VARCHAR(255),
Country VARCHAR(255)
);
sqlite>

And if we have inserted 5 records in to it using INSERT statements as:

sqlite> insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi',


'India');
sqlite> insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown',
'SouthAfrica');
sqlite> insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale',
'Srilanka');
sqlite> insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');
sqlite> insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur',
'India');

15
Python SQLite

sqlite>

Following SELECT statement retrieves the records whose age is greater than 35:

sqlite> SELECT * FROM CRICKETERS WHERE AGE > 35;


First_Name Last_Name Age Place_Of_B Country
---------- ---------- ---- ---------- -------------
Jonathan Trott 38 CapeTown SouthAfrica
Kumara Sangakkara 41 Matale Srilanka
sqlite>

Where clause using python


The Cursor object/class contains all the methods to execute queries and fetch data, etc.
The cursor method of the connection class returns a cursor object.

Therefore, to create a table in SQLite database using python:

 Establish connection with a database using the connect() method.

 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')

#Creating a cursor object using the cursor() method


cursor = conn.cursor()

#Doping EMPLOYEE table if already exists.


cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
sql = '''CREATE TABLE EMPLOYEE(
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),

16
Python SQLite

AGE INT,
SEX CHAR(1),
INCOME FLOAT)'''
cursor.execute(sql)

#Populating the table


cursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX,
INCOME) VALUES ('Ramya', 'Rama priya', 27, 'F', 9000)''')
cursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX,
INCOME) VALUES ('Vinay', 'Battacharya', 20, 'M', 6000)''')
cursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX,
INCOME) VALUES ('Sharukh', 'Sheik', 25, 'M', 8300)''')
cursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX,
INCOME) VALUES ('Sarmista', 'Sharma', 26, 'F', 10000)''')
cursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX,
INCOME) VALUES ('Tripthi', 'Mishra', 24, 'F', 6000)''')

#Retrieving specific records using the where clause


cursor.execute("SELECT * from EMPLOYEE WHERE AGE <23")

print(cursor.fetchall())

#Commit your changes in the database


conn.commit()

#Closing the connection


conn.close()

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:

sqlite> CREATE TABLE CRICKETERS (


First_Name VARCHAR(255),
Last_Name VARCHAR(255),
Age int,
Place_Of_Birth VARCHAR(255),
Country VARCHAR(255)
);
sqlite>

And if we have inserted 5 records in to it using INSERT statements as:

sqlite> insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi',


'India');
sqlite> insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown',
'SouthAfrica');
sqlite> insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale',
'Srilanka');
sqlite> insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');
sqlite> insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur',
'India');

18
Python SQLite

sqlite>

Following SELECT statement retrieves the rows of the CRICKETERS table in the ascending
order of their age:

sqlite> SELECT * FROM CRICKETERS ORDER BY AGE;


First_Name Last_Name Age Place_Of_B Country
---------- ---------- ---- ---------- -------------
Virat Kohli 30 Delhi India
Rohit Sharma 32 Nagpur India
Shikhar Dhawan 33 Delhi India
Jonathan Trott 38 CapeTown SouthAfrica
Kumara Sangakkara 41 Matale Srilanka
sqlite>

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.

sqlite> SELECT * FROM CRICKETERS ORDER BY AGE, FIRST_NAME;


First_Name Last_Name Age Place_Of_B Country
---------- ---------- ---- ---------- -------------
Virat Kohli 30 Delhi India
Rohit Sharma 32 Nagpur India
Shikhar Dhawan 33 Delhi India
Jonathan Trott 38 CapeTown SouthAfrica
Kumara Sangakkara 41 Matale Srilanka
sqlite>

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:

sqlite> SELECT * FROM CRICKETERS ORDER BY AGE DESC;


First_Name Last_Name Age Place_Of_B Country
---------- ---------- ---- ---------- -------------
Kumara Sangakkara 41 Matale Srilanka
Jonathan Trott 38 CapeTown SouthAfrica
Shikhar Dhawan 33 Delhi India
Rohit Sharma 32 Nagpur India
Virat Kohli 30 Delhi India
sqlite>

19
Python SQLite

ORDER BY clause using python


To retrieve contents of a table in specific order, invoke the execute() method on the cursor
object and, pass the SELECT statement along with ORDER BY clause, as a parameter to
it.

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

#establishing the connection


conn = psycopg2.connect(database="mydb", user='postgres', password='password',
host='127.0.0.1', port= '5432')

#Setting auto commit false


conn.autocommit = True

#Creating a cursor object using the cursor() method


cursor = conn.cursor()

#Doping EMPLOYEE table if already exists.


cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
#Creating a table
sql = '''CREATE TABLE EMPLOYEE(
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT, SEX CHAR(1),
INCOME INT,
CONTACT INT)'''
cursor.execute(sql)

#Populating the table


#Populating the table
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)''')

20
Python SQLite

conn.commit()

#Retrieving specific records using the ORDER BY clause


cursor.execute("SELECT * from EMPLOYEE ORDER BY AGE")

print(cursor.fetchall())

#Commit your changes in the database


conn.commit()

#Closing the connection


conn.close()

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:

sqlite> CREATE TABLE CRICKETERS (


First_Name VARCHAR(255),
Last_Name VARCHAR(255),
Age int,
Place_Of_Birth VARCHAR(255),
Country VARCHAR(255)
);
sqlite>

And if we have inserted 5 records in to it using INSERT statements as:

sqlite> insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi',


'India');
sqlite> insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown',
'SouthAfrica');
sqlite> insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale',
'Srilanka');
sqlite> insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');
sqlite> insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur',
'India');
sqlite>

22
Python SQLite

Following Statement modifies the age of the cricketer, whose first name is Shikhar:

sqlite> UPDATE CRICKETERS SET AGE = 45 WHERE FIRST_NAME = 'Shikhar' ;


sqlite>

If you retrieve the record whose FIRST_NAME is Shikhar you observe that the age value
has been changed to 45:

sqlite> SELECT * FROM CRICKETERS WHERE FIRST_NAME = 'Shikhar';


First_Name Last_Name Age Place_Of_B Country
---------- ---------- ---- ---------- -------------
Shikhar Dhawan 45 Delhi India
sqlite>

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:

sqlite> UPDATE CRICKETERS SET AGE = AGE+1;


sqlite>

If you retrieve the contents of the table using SELECT command, you can see the updated
values as:

sqlite> SELECT * FROM CRICKETERS;


First_Name Last_Name Age Place_Of_B Country
---------- ---------- ---- ---------- -------------
Shikhar Dhawan 46 Delhi India
Jonathan Trott 39 CapeTown SouthAfrica
Kumara Sangakkara 42 Matale Srilanka
Virat Kohli 31 Delhi India
Rohit Sharma 33 Nagpur India
sqlite>

Updating existing records using python


To add records to an existing table in SQLite database:

 Import sqlite3 package.

 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')

#Creating a cursor object using the cursor() method


cursor = conn.cursor()

#Doping EMPLOYEE table if already exists.


cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
#Creating table as per requirement
sql ='''CREATE TABLE EMPLOYEE(
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT)'''
cursor.execute(sql)

#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()

#Fetching all the rows before the update


print("Contents of the Employee table: ")
cursor.execute('''SELECT * from EMPLOYEE''')
print(cursor.fetchall())

#Updating the records

24
Python SQLite

sql = '''UPDATE EMPLOYEE SET AGE=AGE+1 WHERE SEX = 'M' '''


cursor.execute(sql)
print("Table updated...... ")

#Fetching all the rows after the update


print("Contents of the Employee table after the update operation: ")
cursor.execute('''SELECT * from EMPLOYEE''')
print(cursor.fetchall())

#Commit your changes in the database


conn.commit()

#Closing the connection


conn.close()

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:

DELETE FROM table_name [WHERE Clause]

Example
Assume we have created a table with name CRICKETERS using the following query:

sqlite> CREATE TABLE CRICKETERS (


First_Name VARCHAR(255),
Last_Name VARCHAR(255),
Age int,
Place_Of_Birth VARCHAR(255),
Country VARCHAR(255)
);
sqlite>

And if we have inserted 5 records in to it using INSERT statements as:

sqlite> insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi',


'India');
sqlite> insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown',
'SouthAfrica');
sqlite> insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale',
'Srilanka');
sqlite> insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');
sqlite> insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur',
'India');
sqlite>

Following statement deletes the record of the cricketer whose last name is 'Sangakkara'.

sqlite> DELETE FROM CRICKETERS WHERE LAST_NAME = 'Sangakkara';


sqlite>

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.

sqlite> SELECT * FROM CRICKETERS;


First_Name Last_Name Age Place_Of_B Country
---------- ---------- ---- ---------- -------------
Shikhar Dhawan 46 Delhi India
Jonathan Trott 39 CapeTown SouthAfrica
Virat Kohli 31 Delhi India
Rohit Sharma 33 Nagpur India
sqlite>

If you execute the DELETE FROM statement without the WHERE clause, all the records
from the specified table will be deleted.

sqlite> DELETE FROM CRICKETERS;


sqlite>

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:

sqlite> SELECT * FROM CRICKETERS;


sqlite>

Deleting data using python


To add records to an existing table in SQLite database:

 Import sqlite3 package.

 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')

#Creating a cursor object using the cursor() method


cursor = conn.cursor()

#Retrieving contents of the table


print("Contents of the table: ")
cursor.execute('''SELECT * from EMPLOYEE''')
print(cursor.fetchall())

#Deleting records
cursor.execute('''DELETE FROM EMPLOYEE WHERE AGE > 25''')

#Retrieving data after delete


print("Contents of the table after delete operation ")
cursor.execute("SELECT * from EMPLOYEE")
print(cursor.fetchall())

#Commit your changes in the database


conn.commit()

#Closing the connection


conn.close()

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:

DROP TABLE table_name;

Example
Assume we have created two tables with name CRICKETERS and EMPLOYEES using the
following queries:

sqlite> CREATE TABLE CRICKETERS (First_Name VARCHAR(255), Last_Name


VARCHAR(255), Age int, Place_Of_Birth VARCHAR(255), Country VARCHAR(255));
sqlite> CREATE TABLE EMPLOYEE(FIRST_NAME CHAR(20) NOT NULL, LAST_NAME
CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT);
sqlite>

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:

sqlite> DROP table employee;


sqlite>

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:

sqlite> DROP table employee;

29
Python SQLite

Error: no such table: employee


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.

sqlite> DROP table IF EXISTS employee;


sqlite>

Dropping a table using Python


You can drop a table whenever you need to, using the DROP statement of MYSQL, but you
need to be very careful while deleting any existing table because the data lost will not be
recovered after deleting a table.

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')

#Creating a cursor object using the cursor() method


cursor = conn.cursor()

#Doping EMPLOYEE table if already exists


cursor.execute("DROP TABLE emp")
print("Table dropped... ")

#Commit your changes in the database


conn.commit()

#Closing the connection


conn.close()

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:

SELECT column1, column2, columnN


FROM table_name
LIMIT [no of rows]

Example
Assume we have created a table with name CRICKETERS using the following query:

sqlite> CREATE TABLE CRICKETERS (


First_Name VARCHAR(255),
Last_Name VARCHAR(255),
Age int,
Place_Of_Birth VARCHAR(255),
Country VARCHAR(255)
);
sqlite>

And if we have inserted 5 records in to it using INSERT statements as:

sqlite> insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi',


'India');
sqlite> insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown',
'SouthAfrica');
sqlite> insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale',
'Srilanka');
sqlite> insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');
sqlite> insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur',
'India');
sqlite>

Following statement retrieves the first 3 records of the Cricketers table using the LIMIT
clause:
31
Python SQLite

sqlite> SELECT * FROM CRICKETERS LIMIT 3;


First_Name Last_Name Age Place_Of_B Country
---------- ---------- ---- ---------- -------------
Shikhar Dhawan 33 Delhi India
Jonathan Trott 38 CapeTown SouthAfrica
Kumara Sangakkara 41 Matale Srilanka
sqlite>

If you need to limit the records starting from nth record (not 1st), you can do so, using
OFFSET along with LIMIT.

sqlite> SELECT * FROM CRICKETERS LIMIT 3 OFFSET 2;


First_Name Last_Name Age Place_Of_B Country
---------- ---------- ---- ---------- -------------
Kumara Sangakkara 41 Matale Srilanka
Virat Kohli 30 Delhi India
Rohit Sharma 32 Nagpur India
sqlite>

LIMIT clause using Python


If you Invoke the execute() method on the cursor object by passing the SELECT query
along with the LIMIT clause, you can retrieve required number of records.

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')

#Creating a cursor object using the cursor() method


cursor = conn.cursor()

#Retrieving single row


sql = '''SELECT * from EMPLOYEE LIMIT 3'''

32
Python SQLite

#Executing the query


cursor.execute(sql)

#Fetching the data


result = cursor.fetchall();
print(result)

#Commit your changes in the database


conn.commit()

#Closing the connection


conn.close()

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:

sqlite> CREATE TABLE CRICKETERS (


First_Name VARCHAR(255),
Last_Name VARCHAR(255),
Age int,
Place_Of_Birth VARCHAR(255),
Country VARCHAR(255)
);
sqlite>

Let us create one more table OdiStats describing the One-day cricket statistics of each
player in CRICKETERS table.

sqlite> CREATE TABLE ODIStats (


First_Name VARCHAR(255),
Matches INT,
Runs INT,
AVG FLOAT,
Centuries INT,
HalfCenturies INT
);
sqlite>

Following statement retrieves data combining the values in these two tables:

sqlite> SELECT

Cricketers.First_Name, Cricketers.Last_Name, Cricketers.Country,

OdiStats.matches, OdiStats.runs, OdiStats.centuries, OdiStats.halfcenturies

from Cricketers INNER JOIN OdiStats ON Cricketers.First_Name = OdiStats.First_Name;

First_Name Last_Name Country Matches Runs Centuries HalfCenturies

---------- ---------- ---- ---------- ------------- ---------- ----------


Shikhar Dhawan Indi 133 5518 17 27

34
Python SQLite

Jonathan Trott Sout 68 2819 4 22


Kumara Sangakkara Sril 404 14234 25 93
Virat Kohli Indi 239 11520 43 54
Rohit Sharma Indi 218 8686 24 42
sqlite>

Join clause using python


Following SQLite example, demonstrates the JOIN clause using python:

import sqlite3

#Connecting to sqlite
conn = sqlite3.connect('example.db')

#Creating a cursor object using the cursor() method


cursor = conn.cursor()

#Retrieving data
sql = '''SELECT * from EMP INNER JOIN CONTACT ON EMP.CONTACT = CONTACT.ID'''

#Executing the query


cursor.execute(sql)

#Fetching 1st row from the table


result = cursor.fetchall();

print(result)

#Commit your changes in the database


conn.commit()

#Closing the connection


conn.close()

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

'Raja@mymail.com', 'Vishakhapatnam'), ('Sharukh', 'Sheik', 25, 'M', 8300.0,


103, 103, 'Krishna@mymail.com', 'Pune'), ('Sarmista', 'Sharma', 26, 'F',
10000.0, 104, 104, 'Raja@mymail.com', 'Mumbai')]

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')

#Creating a cursor object using the cursor() method


cursor = conn.cursor()

Methods
Following are the various methods provided by the Cursor class/object.

Method Description

This routine executes an SQL statement. The SQL statement


may be parameterized (i.e., placeholders instead of SQL
literals). The psycopg2 module supports placeholder using %s
execute() sign

For example:cursor.execute("insert into people values (%s,


%s)", (who, age))

This routine executes an SQL command against all parameter


executemany()
sequences or mappings found in the sequence sql.

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.

fetchall() This routine fetches all (remaining) rows of a query result,


returning a list. An empty list is returned when no rows are
available.

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.

lastrowid This is a read only property, if there are any auto-incremented


columns in the table, this returns the value generated for that column
in the last INSERT or, UPDATE operation.

rowcount This returns the number of rows returned/updated in case of SELECT


and UPDATE operations.

connection This read-only attribute provides the SQLite database Connection


used by the Cursor object.

38

You might also like