0% found this document useful (0 votes)
9 views

Module 1 Materials

The document discusses Python programming and SQL. It covers topics like introduction to data science and Python, Python basic constructs like variables, operators, input/output statements. It also covers chapters on Python data types, conditional and iterative statements, functions, object oriented programming, file handling, exception handling and databases/SQL.

Uploaded by

Suresh Golla
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Module 1 Materials

The document discusses Python programming and SQL. It covers topics like introduction to data science and Python, Python basic constructs like variables, operators, input/output statements. It also covers chapters on Python data types, conditional and iterative statements, functions, object oriented programming, file handling, exception handling and databases/SQL.

Uploaded by

Suresh Golla
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 131

Data Science

Module Name: Python Programming & SQL

1
Python Programming & SQL

Chapters
1. Introduction Data Science and Python
2. Python Basic Constructs
3. Python Data Types
4. Conditional Statements
5. Iterative Statements
6. Functions in Python
7. Object Oriented Programming in Python
8. File Handling
9. Exception Handling
10. Databases and SQL
2
Chapter 1

Introduction to Data Science and Python

3
1. Introduction to Data Science and Python

Objectives
• What is Data Science?
• Application of Data Science
• Data Science Career Options
• Skills Required for Data Scientist
• Data Scientist Salaries
• Python Introduction
• Features of Python
• Python - Environment Setup

4
1. Introduction to Data Science and Python

What is Data Science?


• Data Science is a multi-disciplinary field to extract knowledge and insights from raw data

5
1. Introduction to Data Science and Python

Application of Data Science


• Finance Industry
• Healthcare Industry
• E-Commerce
• Image Recognition
• Language Translation
• and more

6
1. Introduction to Data Science and Python

Data Science Career Options


• Data Analyst
• Machine Learning Engineer
• NLP Engineer
• Computer Vision Engineer
• Data Scientist
• And many more

7
1. Introduction to Data Science and Python

Skills Required for Data Scientist


• Probability and Statistics
• Python / R Programming
• Data Visualization Techniques
• Machine Learning
• Deep Learning
• NLP
• Computer Vision

8
1. Introduction to Data Science and Python

Data Scientist Salaries


• Beginner level salary for a Data Scientist ranges form 5 lpa to 8 lpa
• Intermediate(3 to 7 years) level salary for a Data Scientist ranges form 8 lpa to 16 lpa
• Expert(8+ years) level salary for a Data Scientist ranges form 16 lpa to 24+ lpa

• Pay hike ranges from 30% to 100+%

9
1. Introduction to Data Science and Python

Introduction to Python
• Python is a popular programming language.
• It was created by Guido van Rossum, and released in 1991.
• It is used for:
• Software development
• Data Science
• Web application development
• System scripting
• etc

10
1. Introduction to Data Science and Python

Features of Python
• Free and Open Source
• Easy to Learn
• Interpreted Language
• Platform Independent
• High-Level Language
• Object-Oriented Language
• Large Packages/Libraries
• Dynamically Typed Language
• Integrated Language
• GUI and Web Programming
11
1. Introduction to Data Science and Python

Python - Environment Setup


• Python is available on a wide variety of platforms including Linux, Windows and Mac OS X.

• The most up-to-date and current source code, binaries, documentation, news, etc., is available on
the official website of Python https://www.python.org/

• The version of Python are:


• Python 1.x
• Python 2.x
• Python 3.x

12
1. Introduction to Data Science and Python

Python - Environment Setup


Step 1. Open your web browser and Go to https://www.python.org/downloads. The recent version
of Python will always appear to download on this page.

13
1. Introduction to Data Science and Python

Python - Environment Setup


Step 2. Now check the box Add Python 3.10.8 to PATH .If you have not added path, then you have to
add it later and click on Install Now.

14
1. Introduction to Data Science and Python

Python - Environment Setup


Step 4 - The installation is in progress. After the progress completes, python is successfully installed.

15
1. Introduction to Data Science and Python

Python - Environment Setup


Step 4 – To check if you have python installed on a Windows PC, search in the start bar for Python or
run the following on the Command Line.
• C:\Users\Your Name>python –version
• Displays the python version installed in the system

• C:\Users\Your Name>python
• Opens the python interactive shell, to execute python commands in form REPL

16
1. Introduction to Data Science and Python

IDLE

17
1. Introduction to Data Science and Python

Python Script File

18
1. Introduction to Data Science and Python

IDEs and Tools for Python

https://www.jetbrains.com/pycharm/download/#se https://www.anaconda.com/
ction=windows products/distribution

https://colab.research.google.com/
19
1. Introduction to Data Science and Python

Jupyter Notebook

20
Chapter 2

Python Basic Constructs

21
2. Python Basic Constructs

Objectives
• Output Statements
• Variables
• Operators
• Type Casting
• Input Statement

22
2. Python Basic Constructs

Output Statement
• We use print() function or statement to print content on to the console(output)

• print(‘Welcome to Python’)
• print(“Welcome to Python”)

Note: We can use single or double quote for strings, both are similar, if we start with single
quote then end with single quote only

23
2. Python Basic Constructs

Output Statement
• Print Examples

• print(‘Welcome to Python’)
• print(‘Hi’, ‘Hello’)
• print(‘Hi’, “Hello”)
• print(‘Hi’, “Hello”, ‘World’)
• print(“Python’s Script”)

24
2. Python Basic Constructs

Variables
• Variables are names to the memory location to store and manipulate data or information in a
program
• Following statements create various kinds of variables

a = 10
b = 20.45
name = ‘Bangalore’

print(“a=“,a)
print(“b=“,b)
print(“Name=“, name)
25
2. Python Basic Constructs

Variables
• Guidelines to define a variable name:
• A variable name must start with a letter or the underscore character.
• age and _age are valid variable names
• A variable name cannot start with a number.
• 1age not a valid variable name
• A variable name can only contain alpha-numeric characters and underscores
• full_name1
• Variable names are case-sensitive
• For example name and Name two different variables

26
2. Python Basic Constructs

Comments
• Comments are used to hide the statement from the interpreter
• We use # character to comment the statement
• #print(“This is comment”)
• It is a single line comment, used for multiline as well
• Comments mainly used to describe the code
• #code to perform addition of two numbers
• #created on 12-Oct-22 by Kumar

27
2. Python Basic Constructs

Operators
• Operators are special symbols to perform specific task, for example + is used to perform addition
of two numbers
• Type of Operators:
• Arithmetic Operators
• Comparison Operators
• Logical Operators
• Assignment Operators
• Identity Operators
• Membership Operators

28
2. Python Basic Constructs

Arithmetic Operators

Operator Description
+ Performs addition
- Performs subtraction
* Performs multiplication
/ Performs division
% Performs modulus
** Performs power to a number
// Performs floor division

29
2. Python Basic Constructs

Comparison Operators

Operator Description
== Checks equal
!= Checks not equal
< Checks lesser than
<= Checks lesser than or equals
> Checks greater than
>= Checks greater than or equals

30
2. Python Basic Constructs

Logical Operators

Operator Description
and Returns true, if both values are true otherwise false
or Returns false, if both values are false otherwise true
not Returns opposite, if values true returns false vice
versa

31
2. Python Basic Constructs

Assignment Operators

Operator Description
= Assigns a value to the variable
+= Performs operations and assigns result to the same
-= variable
*=
/=
%=
**=
&=
|=

32
2. Python Basic Constructs

Identity Operators

Operator Description
is Returns true if two variables refer same memory
location
is not Returns true if two variables refer different memory
locations

33
2. Python Basic Constructs

Membership Operators

Operator Description
in Returns true if a value in a collection otherwise
false
not in Returns true if a value not in a collection otherwise
false

34
2. Python Basic Constructs

Accepting Input from a User


• We can use input() built-in function to accept input from standard input device(keyboard)
• It takes data always in string format

a = input(‘Enter a value : ‘) #waits for input from user, if enter 10

print(a) #a (‘10’) is string not a integer value

35
2. Python Basic Constructs

Type Casting
• Converting data from one format to other, for example string to integer
• Bellow are the some function to convert into specific format

Function Description
int() Converts string/float to integer
float() Converts string/int to float
str() Converts numeric to string

36
Chapter 3

Data Types in Python

37
3. Data Types in Python

Objectives
• What is Data Type?
• Various Data Types

38
3. Data Types in Python

Data Types
• Data type represents type of value stored in a variable.
• Integer
• For example • Float
Numeric • Complex
• x = 20
• Where x is integer type
Boolean

• type()
• It is a function to find type of a variable String

• List
• Tuple
Collections • Set
• Dictionary

39
3. Data Types in Python

Numeric Data Types


• These types holds only numeric values, such as 10, 20.35 and 3+5j
• Numeric data types are categorized into 3 as follows:
• Integer Type
• x=40
• Float Type
• y=456.78
• Complex Type
• z=10+20j

Note: We must use ‘j’ character only for complex type declaration
40
3. Data Types in Python

Boolean Data Types


• Boolean Type as follows:
• is_male = True
• is_female = False

41
3. Data Types in Python

Boolean Data Types


• Boolean Type as follows:
• is_male = True
• is_female = False

42
3. Data Types in Python

String Data Types


• String is a collection of character, usually referred as a data type
• Values enclosed between ‘ or “ are called strings
• x1 = ‘Bangalore’
• x2 = ‘B’

• Here x1 and x2 both are strings

• We can use len() function to find number of characters in a string


• len(x1) #returns 9

43
3. Data Types in Python

String Data Types


• we can use [] to access elements at specified location
• city = ‘Bangalore’

• city[0] #retruns B
• city[1] #retruns a
• Here 0, 1 are called index

• city[0] = ‘b’ #it gives error

Note: Strings are immutable


44
3. Data Types in Python

String Data Types


• we can use –ve index to access characters from end, -ve index always start from -1

• city[-1] #retruns e
• city[-2] #retruns r

45
3. Data Types in Python

String Data Types


• we can use : (x1:x2) range operator to access characters from position x1 to x2-1

• city[1:3] #retruns an
• city[:3] #retruns Ban
• city[3:] #returns galore

46
3. Data Types in Python

String Data Types


• We can use following operations on strings

• +, which combines two string


• ‘ab’+’cd’ #’abcd’
• *, which appends the same string numbers of times
• ‘ab’*3 #’ababab’
• in and not in, which checks part of string existence
• ‘a’ in ‘ab’ #returns True
• ‘a’ not in ‘ab’ #return False

47
3. Data Types in Python

String Data Types


• Few string important methods

• find()
• split()
• replace()
• upper()/lower()/capitalize()
• count()
• isalph()/isalnum()/isdigit()
• startswith()/endswith()

48
3. Data Types in Python

String Data Types


• We can use for statement to iterate character by character in a string

city = 'Bangalore'

for x in city:
print(x))

for i in range(len(city)):
print(city[i])

49
3. Data Types in Python

Collection Types
• Collection is object, which contains more than one value
• Collection are categorized as follows:
• List
• Tuple
• Set
• Dictionary

50
3. Data Types in Python

List Data Type


• List is a collection which is ordered, indexed and changeable.
• It allows duplicate members.
• Lists are represented using square brackets [ ].
• Example:- nos=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
• To access the items from the list, index is used. It always starts with 0
• Example: print(nos[0])
• We can update using index
• Example: nos[1] = 100

51
3. Data Types in Python

List Item Selection and Slicing


• We can use negative index to access elements from end of the list, it always starts with -1
• Example: print(nos[-1])

• We can use range (:) operator to access range of elements from the list
• Example: print(nos[2:7])

• We can also use range(::) operator to access range of elements from the list, with specified step
• Example: print(nos[1:9:2])

52
3. Data Types in Python

List Methods
• Some of the list methods are listed below :-

List Operation Description

len() The len() method returns the length of a set

append() To add an item at the end


insert() To add an item at the specified index

remove() To remove the specified item

To remove the specified index, (or the last item if


pop()
index is not specified)
53
3. Data Types in Python

List Methods
List Operation Description

The del keyword removes the specified index.


del
The del keyword can also delete the list completely.

clear() The clear() method empties the list

extend() This adds the contents of sequence to existing list

This returns the index of the specified element in


index()
the list

reverse() Reverses objects of list in place


54
3. Data Types in Python

Tuple Data Type


• A tuple is a collection which is ordered, indexed and unchangeable.
• Tuples are written with round brackets ().
• Once a tuple is created, you cannot change its values. Tuples are unchangeable.
• Example : fruit =(“Mango”,Grapes”)
• We can access tuple items by referring to the index number, inside square brackets
• Example: print(fruit[1])
• Allows duplicate members like list.
• Selecting and slicing a tuple is same as list

55
3. Data Types in Python

Tuple Methods

Tuple Operation Description

len() The len() method returns the length of a string.

Returns the number of times a specified value


count()
occurs in a tuple.
Searches the tuple for a specified value and returns
index()
the position of where it was found.

56
3. Data Types in Python

Set Data Type


• A set is a collection which is unordered and unindexed.
• Sets are written with curly {} brackets.
• Sets are unordered, so the items will appear in a random order.
• No duplicate members are allowed in set.
• Since it is unordered, so on popping elements of a set, any element can be removed from the set.
• Example :- fruit={“mango”,”apple”}
• Once a set is created, you cannot change its items, but you can add new items.

57
3. Data Types in Python

Set Data Type


• You cannot access items in a set by referring to an index, since sets are unordered the items have
no index.
• But you can loop through the set items using a for loop.

• Example :
• fruit = {"apple", "banana", "cherry"}
for x in fruit:
print(x)

58
3. Data Types in Python

Set Methods

Set Operation Description

add() To add one item to a set use the add() method.

To add more than one item to a set use


update()
the update() method.
This method removes the specified item from the
remove()
set.
This method removes the item from the set as set is
pop() unordered hence any item can be removed from the
set.

59
3. Data Types in Python

Set Methods

Set Operation Description


Returns a set that contains all items from both sets,
union()
duplicates are excluded.
Returns a set that contains the items that exist in
intersection()
both set x, and set y.
Returns a set that contains the items that only exist
difference()
in set x, and not in set y.

60
3. Data Types in Python

Dictionary Data Type


• A dictionary is a collection which is unordered, changeable and indexed.
• Dictionaries are written with curly{} brackets, and they have keys and values.
• vehicle ={“brand”:”ford”,”model”:”Mustang”,”year”:1991}
• Items in the dictionaries can be accessed using key
• x=vehicle[“model”] or x =vehicle.get("model")
• You can change the value of a specific item by referring to its key name
• vehicle["year"] = 2018

61
3. Data Types in Python

Dictionary Methods

Dictionary Description
Operation
Determines how many items (key-value pairs) a
len()
dictionary has.
pop() This method removes the item with the specified
key name.
popitem() This method removes the last inserted item.

clear() This method empties the dictionary

62
Chapter 4

Conditional Statements

63
4. Conditional Statements

Objectives
• If statement
• If-else statement
• If-elif-elif-else statement

64
4. Conditional Statements

Objectives
• If statement
• If-else statement
• If-elif-elif-else statement

65
4. Conditional Statements

If statement
• The statements under if clause are only executed if and only if the condition prescribed becomes
true, else the statements are ignored.

Syntax:-

if (condition):
statement1
statement2
…..
statement n

66
4. Conditional Statements

If - else statements
• An else statement can be combined with an if statement. Syntax:-
• The block of code under the if statements are executed if the
if ( condition ):
condition given for if becomes true.
statement1
• The else statements are optional. statement2
…..
• There could be at most one else statement followed by the if
statement n
statement and is executed when the if condition is false. else:
statement1
statement2
…..
statement n
Note: The values except 0 are considered as true and
0 is considered as false.
67
4. Conditional Statements

If – elif-else statements
• The elif statement allows you to check multiple expressions Syntax:-
for TRUE and execute a block of code as soon as one of the
conditions evaluates to TRUE. if expression1:
statement(s)
• Similar to the else, the elif statement is optional. However, elif expression2:
unlike else, for which there can be at most one statement. statement(s)
elif expression3:
• There can be an arbitrary number of elif statements statement(s)
following an if. else:
statement(s)
68
Chapter 5

Iterative Statements

69
5. Iterative Statements

Objectives
• While
• For
• Break and Continue

70
5. Iterative Statements

While
• The statements under the while loop are executed until the Syntax:
condition remains true.
while expression:
• When the condition becomes false, program control passes to statement(s)
the line immediately following the loop.
• The loop statement is mandatory to be incremented or
decremented, or else the statements would be executed to
infinite times.

71
5. Iterative Statements

While

Example of While loop Example of While loop

count = 0 count = 0
while (count < 9): while (count < 9):
print ('The count is:', count) print ('The count is:', count)
count = count + 1 count = count + 1
print ("Good bye!“) else:
print (“else“)

Note:- Python supports to have an else statement associated with a loop statement. The else
statement is executed when the condition becomes false.
72
5. Iterative Statements

For
• for loop is used for iterating over a sequence (i.e., either
Syntax:
a list, a tuple, a dictionary, a set, or a string).
• The range() function returns a sequence of numbers,
for item in sequence:
starting from 0 by default, and increments by 1 (by
statements(s)
default), and ends at a specified number.
• For also supports else like while
Example:

fruits = ["Apple","Banana","Cherry"]
for x in fruits:
print(x)
73
5. Iterative Statements

Break and Continue


• Break statement is used to exit from the loop in between
• Where as continue statement skips only one iteration

Example: Example:

i=1 i=1
while(i<6): while(i<6):
print(i) print(i)
if(i==3): if(i==3):
break continue
i+=1 i+=1 74
Chapter 6

Functions in Python

75
6. Functions in Python

Objectives
• Function
• Function Types

76
6. Functions in Python

Functions
• It is a block of code with name, which can perform a task
• Functions mainly used for code reuse and modular programming

• Function Types:
• Built-in functions
• print(), len() and etc
• User defined functions
• User can define for his project

77
6. Functions in Python

Functions Declaration

Syntax: Example:

def fun_name(params): def add(a, b):


[“function document "function to add two numbers”
string“]
c=a+b
function_body print(‘Sum of {0} and {1} is
[return value/expression] {2}’.format(a, b, c))
#print('Sum of %f and %f is %f'%(a, b, c))

78
6. Functions in Python

Functions Call

add(10, 20)

add(5, 6)

79
6. Functions in Python

Parameters / Arguments

Variables inside function declaration are called Parameters

Variables inside function call are called Arguments

80
6. Functions in Python

Function Types

1. Function with required arguments


2. Function with keyword arguments
3. Function with default argument
4. Function with variable length arguments
5. Function with variable length keyword arguments
6. Function with return type
7. Lambda Function

81
6. Functions in Python

Function with required arguments

def add(a, b, c):


s = a + b +c
print(‘Sum : ‘,s)

add(10, 20, 30)


add(10, 1) #error 3rd argument is missing

82
6. Functions in Python

Function with keyword arguments

def add(a, b, c):


s = a + b +c
print(‘Sum : ‘,s)

#calling function with parameter names


add(a=10, b=20, c=30)
add(b=1, c=2, a=3)

Note: arguments can be passed in any order


83
6. Functions in Python

Function with default argument

def add(a=0, b=0, c=0):


s = a + b +c
print(‘Sum : ‘,s)

add(10, 20, 30)


add(10, 1) #no error, c is 0 now
add() #all values are 0 now

84
6. Functions in Python

Function with variable length arguments

def display_all(*args):
for arg in args:
print(arg)

display_all(10, 20, 30)


display_all(10, 100)

Note: *args is treated as a tuple


85
6. Functions in Python

Function with variable length keyword arguments

def display_all(**kwargs):
for key in kwargs:
print(key, ‘:’, kwargs[key])

display_all(sno=100, sname=‘kumar’)
display_all(sno=2000)

Note: **kwargs is treated as a dictionary


86
6. Functions in Python

Function with return value

def add(a, b, c):


s = a + b +c
return s

r = add(10, 20, 30)


print(add(1, 2, 3))

Note: assign function call to a variable to hold


returned value from a function
87
6. Functions in Python

Lambda Function
• Anonymous function is a function that is defined without a name.
• Anonymous functions are defined using the lambda keyword. So they are called lambda
functions
• A lambda function can take any number of arguments, but can have only one expression.

Syntax : Example :

lambda arguments : expression add = lambda a, b : a+b

print(add(2,3))
88
Chapter 7

Object Oriented Programming in Python

89
7. Object Oriented Programming in Python

Objectives
• Classes and Objects
• Initializers
• Inheritance

90
7. Object Oriented Programming in Python

Classes and Objects


• Any real world entity is called and object, such as
Employee, Student, Book and more
• Class is an blueprint of an object
• In programming terms class is a user defined data type
which contains related variable(attributes) and
methods(functionalities) together
• The main advantage is object centric programming and
code reuse

91
7. Object Oriented Programming in Python

Classes and Objects


• Class syntax as follows class Stud:
sno = 0
sname = None
class class_name:
[attributes]
def set_details(self, sno, sname):
[functions]
self.sno = sno
self.sname = sname

def print_details(self):
print('sno’,self.sno,’\nName’,self.sname')

Note: self referred to current object. It could be any string, like s, this. As standard
in python everyone uses self 92
7. Object Oriented Programming in Python

Classes and Objects


• Creating object
s = Stud()

obj_var = class_name() s.print_details()


s.set_details(100, 'Kumar')
s.print_details()

93
7. Object Oriented Programming in Python

Initializers
• Initializer is a special method declared in a class to initialize properties (variables) while creating
an object
• These are called automatically when object declared/created
• __init__() method can be used to define initializers in a class

94
7. Object Oriented Programming in Python

Initializers

class Stud:
s1 = Stud(100, ‘Shiva’)
def __init__(self, sno, sname):
s1.print_details()
self.sno = sno
self.sname = sname
s2 = Stud(200, ‘Gopi’)
s2.print_details()
def print_details(self):
print(f'sno={self.sno}\nName={self.sname}')

95
7. Object Oriented Programming in Python

Inheritance
• Extending properties from existing class to the new class
• Main use of inheritance is code reuse
• Types of inheritance
• Simple
• Hierarchical
• Multilevel
• Multiple

96
7. Object Oriented Programming in Python

Inheritance
• Benefits of Python inheritance are listed below:
• Less code repetition, as the code which is common can be placed in the parent class, hence
making it available to all the child classes.
• Structured Code: By dividing the code into classes, we can structure our software better by
dividing functionality into classes.
• Make the code more scalable.

97
7. Object Oriented Programming in Python

Inheritance

class Person:
class Student(Person):
def __init__(self, fname, lname):
def __init__(self, fname, lname, course):
self.firstname = fname
super().__init__(fname, lname)
self.lastname = lname
self.course = course

def full_name(self):
def print_details (self):
print(‘Name ‘, self.firstname, self.lastname)
super().full_name()
print(‘Course : ’, self.course)

s = Student(100, ‘Shiva’) Note: super() reference to the parent


s1.print_details() class
98
Chapter 8

File Handling

99
8. File Handling

Objectives
• Files
• Writing content to a file
• Reading content from a file

100
8. File Handling

Files
• Files are named locations on disk to store related information
• They serve as a permanent data storage device in non-volatile memory
• File operations as follows:
• Open a file
• Read or write (perform operation)
• Close the file

101
8. File Handling

Opening a File
• We use open() function to open a file, which returns file descripter/reference

• open(file_name, mode, [buffer])

file = open(‘myfile.txt’, ‘w’)

102
8. File Handling

File Modes
Mode Description
r Opens a file for reading. (default)
Opens a file for writing. Creates a new file if it does not exist or truncates the
w
file if it exists.
Opens a file for appending at the end of the file without truncating it. Creates
a
a new file if it does not exist.

t Opens in text mode. (default)

b Opens in binary mode.

103
8. File Handling

File Methods
Mothod Description
write(s) Writes the string s to the file.

writelines(lines) Writes a list of lines to the file.

read(n) Reads at most n characters from the file.

readline() Reads and returns one line from the file

readlines() Reads and returns a list of lines from the file.

Changes the file position to offset bytes, in reference to from (start,


seek()
current, end).

tell() Returns an integer that represents the current position of the file's object. 104
8. File Handling

Writing to a File

file = open(‘myfile.txt’, ‘w’)


file.write(‘File created using Python Script’)
file.write(‘\nCan be used to write content to the new line’)
file.flush()
file.close()

105
8. File Handling

Reading from a File

file = open(‘myfile.txt’, ‘r’)

for line in file.readlines():


print(line)

file.close()

106
Chapter 9

Exception Handling

107
9. Exception Handling

Objectives
• Exceptions
• Try-Except-Finally block

108
9. Exception Handling

Exceptions
• Error occurred during code execution is called exception
• If runtime error occurs, program terminated abnormally
• Python handles runtime errors via exception handling method with the help of try-except-finally.
• Some of the standard exceptions which are the most frequent include:
• IndexError
• ImportError
• IOError
• ZeroDivisionError
• TypeError
• and many more

109
9. Exception Handling

Try-Except-Finally block
• Hence, most exceptions are handled by programs by using try and exccept clause.

• First, the try clause, the statement(s) between the try and except keyword is executed.

• If no exception occurs, the except clause is skipped and the execution of the try statement is
finished.

• If an exception occurs during execution of the try clause, the rest of the clause is skipped.

Note: Finally block is optional, but some situations we can not avoid it

110
9. Exception Handling

Try-Except-Finally block

def divider(a , b): divider(2, 3)


try: divider(2, 2)
c = ((a+b) / (a-b))
except ZeroDivisionError:
print ("a/b result in 0")
except Exception:
print (“some other error")
finally:
print (“this will execute always")

111
Chapter 10

Databases and SQL

112
10. Databases and SQL

Objectives
• Database Introduction
• Creating and Manipulating Database Objects
• Connecting to Database using Python
• Manipulating Rows in a Table
• Listing/Retrieving Rows from a Table

113
10. Databases and SQL

Databases

114
10. Databases and SQL

Databases
• Database is a collecting raw data into meaningful format
• To manipulate database, we use RDBMS software
• Most popular RDBMS are:
• MySQL
• Oracle
• MS SQL Server

115
10. Databases and SQL

MySQL
• It is a very fast, multithreaded, multi-user, and robust database
server.
• It is a free and open source software under GNU General Public
License
• We can use SQL (Structured Query Language) to create and
manipulate database objects

Note: SQL is not a case sensitive language

116
10. Databases and SQL

MySQL Setup
• Download mysql installer from following url:
• https://dev.mysql.com/downloads/installer/ (mysql-installer-community-8.0.31.0.msi)

• Double click on mysql-installer-community-8.0.31.0.msi and keep all default options from


installer

• Once installation is success, open MySQL Workbench

117
10. Databases and SQL

Creating and Manipulating Database


• Create a database
Create database db1;

• Displaying existing databases


Show databases;

• Connecting to a database
Use db1;

• Removing a database
Drop database db1; 118
10. Databases and SQL

Creating a Table
create table Product(
pid int primary key,
pname varchar(30) not null,
price numeric(6,0),
vendor varchar(30) not null
)
Where
Product is table name
pid, pname, price, vendor are columns
int, varchar, numeric are data types
primary key makes each row unique 119
10. Databases and SQL

Inserting Rows into a Table

insert into Product values(100, ‘Mac Book’, 98000, ‘Apple’)

insert into Product(pid, pname) values(200, ‘iPhone’)

Note: Column names are not required, if we provide all column values

120
10. Databases and SQL

Deleting Rows from a Table


delete from Product

delete from Product where pid=100

Note: if where is not specified, then all rows will be deleted from the
table

121
10. Databases and SQL

Updating Rows from a Table


update Product set price=98000

update Product set price=98000 where pid=100

Note: if where is not specified, then all rows will be deleted from the
table

122
10. Databases and SQL

Retrieving Rows from a Table


select * from product

select pname, price from product

select * from product where pid<1000

Note: * means all columns

123
10. Databases and SQL

Retrieving Rows in Sorting Order by Column


select * from product order by price;

select * from product order by price desc;

124
10. Databases and SQL

Summary Functions
• count()
select conut(*) from product
• max()
select max(price) from product
• min()
select min(price) from product
• sum()
select sum(price) from product
• avg()
select avg(price) from product
125
10. Databases and SQL

Group By
• Group by performs operations on groups

• Finding number of products from vendors

select vendor, count(*) from product group by vendor

126
10. Databases and SQL

Connecting to MySQL from Python


• We can connect to any database using python script
• To connect to database we need database driver (simply api/library)
• We need to install driver, before connecting to the database
• Database driver is specific to the database

• To connect to MySQL, we need to install following driver using pip


• pip install mysql-connector-python

• Use following to import connector


• import mysql.connector
127
10. Databases and SQL

Connecting to MySQL from Python


• Getting reference to the test database

db = mysql.connector.connect(host="localhost",
user="root",
password="",
database="test")

128
10. Databases and SQL

Connecting to MySQL from Python


• Executing SQL statements, such as create table, insert and more

cursor = db.cursor()

sql_statement = "create table if not exists student(sid int primary key, sname varchar(30), course
varchar(30))"
cursor.execute(sql_statement)

Note: we can use insert, update and delete commands as sql_statement

129
10. Databases and SQL

Connecting to MySQL from Python


• Executing SQL statements, such as create table, insert and more

cursor = db.cursor()

sql_statement = “insert into student values(1000, ‘Rahul H’, ‘Data Science’)"


cursor.execute(sql_statement)
db.commit()

Note: we must call commit() method to make changes permanently to the


database tables, this is only for insert, update and delete commands
130
10. Databases and SQL

Connecting to MySQL from Python


• Selecting rows from a table

cursor = db.cursor()

sql_statement = "select * from student"


cursor.execute(sql_statement)
rows = cursor.fetchall()
for row in rows:
print(row)

Note: fetchall() method returns list with tuple, tuple contains column values 131

You might also like