Module 1 Materials
Module 1 Materials
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
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
5
1. Introduction to Data Science and Python
6
1. Introduction to Data Science and Python
7
1. Introduction to Data Science and Python
8
1. Introduction to Data Science and Python
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
• 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/
12
1. Introduction to Data Science and Python
13
1. Introduction to Data Science and Python
14
1. Introduction to Data Science and Python
15
1. Introduction to Data Science and Python
• 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
18
1. Introduction to Data Science and 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
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
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
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
Note: We must use ‘j’ character only for complex type declaration
40
3. Data Types in Python
41
3. Data Types in Python
42
3. Data Types in Python
43
3. Data Types in Python
• city[0] #retruns B
• city[1] #retruns a
• Here 0, 1 are called index
• city[-1] #retruns e
• city[-2] #retruns r
45
3. Data Types in Python
• city[1:3] #retruns an
• city[:3] #retruns Ban
• city[3:] #returns galore
46
3. Data Types in Python
47
3. Data Types in Python
• find()
• split()
• replace()
• upper()/lower()/capitalize()
• count()
• isalph()/isalnum()/isdigit()
• startswith()/endswith()
48
3. Data Types in Python
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
51
3. Data Types in Python
• 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 Methods
List Operation Description
55
3. Data Types in Python
Tuple Methods
56
3. Data Types in Python
57
3. Data Types in Python
• Example :
• fruit = {"apple", "banana", "cherry"}
for x in fruit:
print(x)
58
3. Data Types in Python
Set Methods
59
3. Data Types in Python
Set Methods
60
3. Data Types in Python
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.
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
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
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:
78
6. Functions in Python
Functions Call
add(10, 20)
add(5, 6)
79
6. Functions in Python
Parameters / Arguments
80
6. Functions in Python
Function Types
81
6. Functions in Python
82
6. Functions in Python
84
6. Functions in Python
def display_all(*args):
for arg in args:
print(arg)
def display_all(**kwargs):
for key in kwargs:
print(key, ‘:’, kwargs[key])
display_all(sno=100, sname=‘kumar’)
display_all(sno=2000)
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 :
print(add(2,3))
88
Chapter 7
89
7. Object Oriented Programming in Python
Objectives
• Classes and Objects
• Initializers
• Inheritance
90
7. Object Oriented Programming in Python
91
7. Object Oriented Programming in Python
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
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)
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
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.
103
8. File Handling
File Methods
Mothod Description
write(s) Writes the string s to the file.
tell() Returns an integer that represents the current position of the file's object. 104
8. File Handling
Writing to a File
105
8. File Handling
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
111
Chapter 10
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
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)
117
10. Databases and SQL
• 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
Note: Column names are not required, if we provide all column values
120
10. Databases and SQL
Note: if where is not specified, then all rows will be deleted from the
table
121
10. Databases and SQL
Note: if where is not specified, then all rows will be deleted from the
table
122
10. Databases and SQL
123
10. Databases and SQL
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
126
10. Databases and SQL
db = mysql.connector.connect(host="localhost",
user="root",
password="",
database="test")
128
10. Databases and SQL
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)
129
10. Databases and SQL
cursor = db.cursor()
cursor = db.cursor()
Note: fetchall() method returns list with tuple, tuple contains column values 131