S11BLH21 PROGRAMMING IN PYTHON - 4
COURSE OBJECTIVES
 To learn about data structures lists, tuples, and dictionaries in Python.
 To build packages with Python modules for reusability and handle user/custom exceptions.
 To create real world GUI applications, establish Database connectivity and Networking
UNIT 1 INTRODUCTION TO PYTHON 12 Hrs.
History of Python- Introduction to the IDLE interpreter (shell) - Data Types - Built-in function – Conditional
statements - Iterative statements- Input/output functions - Python Database Communication - data analysis and
visualization using python.
Practical:
 Implement built-in functions and trace the type of data items.
 Implement concepts of Conditional and Iterative Statements.
 Use the built-in csv module to read and write from a CSV file in Python.
 Perform data analysis and visualization on a given dataset using Python libraries like pandas, numpy, matplotlib
and display charts, graphs, and plots.
07/26/2025 K.Abinaya Assistant Professor SBU 1
History of Python
• Python was developed by Guido van Rossum in the late eighties and
early nineties at the National Research Institute for Mathematics and
Computer Science in the Netherlands.
Major Python Releases
Python 0.9.0
• Python's first published version is 0.9. It was released in February 1991.
It consisted of support for core object-oriented programming
principles.
Python 1.0
• In January 1994, version 1.0 was released, armed with functional
programming tools, features like support for complex numbers etc.
07/26/2025 K.Abinaya Assistant Professor SBU 2
Python 2.0
 Next major version − Python 2.0 was launched in October 2000. Many new features
such as list comprehension, garbage collection and Unicode support were included with
it.
Python 3.0
 Python 3.0, a completely revamped version of Python was released in December 2008.
The primary objective of this revamp was to remove a lot of discrepancies that had crept
in Python 2.x versions.
 Python 3 was backported to Python 2.6. It also included a utility named
as python2to3 to facilitate automatic translation of Python 2 code to Python 3.
Current Version
 Meanwhile, more and more features have been incorporated into Python's 3.x branch.
As of date, Python 3.11.2 is the current stable version, released in February 2023.
07/26/2025 K.Abinaya Assistant Professor SBU 3
IDLE Software in Python
 IDLE stands for Integrated Development and Learning Environment.
 The lightweight and user-friendly Python IDLE (Integrated Development and
Learning Environment) is a tool for Python programming.
 Since version 1.5.2b1, the standard Python implementation has included IDLE, an
integrated development environment.
 Many Linux distributions include it in the Python packaging as an optional
component.
 The Tkinter GUI toolkit and Python are used throughout.
07/26/2025 K.Abinaya Assistant Professor SBU 4
Python Syntax Rules
 -Python is case sensitive. Hence a variable with
name “python” is not same as pYThon.
 -For path specification, python uses forward slashes.
Hence if you are working with a file, the default path for the
file in case of Windows OS will have backward slashes, which
you will have to convert to forward slashes to make them work
in your python script
 -Eg: For window's path C:folderAfolderB relative python
program path should be C:/folderA/folderB
07/26/2025 K.Abinaya Assistant Professor SBU 5
• In python, there is no command terminator, which means no
semicolon ; or anything. So if you want to print something as
output, all you have to do is:
In one line only a single executable statement should be written and the line change act
as command terminator in python.
To write two separate executable statements in a single line, you should use
a semicolon ;
to separate the commands.
For example,
07/26/2025 K.Abinaya Assistant Professor SBU 6
Execute Python Syntax
• As we learned in the previous page, Python syntax can
be executed by writing directly in the Command Line:
Or by creating a python file on the server, using
the .py file extension, and running it in the
Command Line:
07/26/2025 K.Abinaya Assistant Professor SBU 7
Python Indentation
• Indentation refers to the spaces at the beginning of
a code line.
• Where in other programming languages the
indentation in code is for readability only, the
indentation in Python is very important.
• Python uses indentation to indicate a block of
code.
Example
if 5 > 2:
print("Five is greater than two!")
07/26/2025 K.Abinaya Assistant Professor SBU 8
• Python will give you an error if you skip the indentation:
Example
Syntax Error:
if 5 > 2:
print("Five is greater than two!")
07/26/2025 K.Abinaya Assistant Professor SBU 9
Points to Remember while Writing a Python Program

• Case sensitive
• Punctuation is not required at end of the statement
• In case of string use single or double quotes i.e. ‘ ’
or “ ”
• Must use proper indentation
• Python Program can be executed in two different
modes:
• Interactive Mode Programming
• Script mode programming
07/26/2025 K.Abinaya Assistant Professor SBU 10
Expressions
• In Python, operators are special symbols that designate that some
sort of computation should be performed. The values that an operator
acts on are called operands.
>>> a = 10
>>> b = 20
>>> a + b
30
07/26/2025 K.Abinaya Assistant Professor SBU 11
In this case, the + operator adds the
operands a and b together. An operand can be either a literal
value or a variable that references an object:
>>> a = 10
>>> b = 20
>>> a + b - 5
25
07/26/2025 K.Abinaya Assistant Professor SBU 12
Python Data Types
• Variables can hold values, and every value has a data-type. Python is a
dynamically typed language; hence we do not need to define the type of the
variable while declaring it. The interpreter implicitly binds the value with its
type.
a = 5
• The variable a holds integer value five and we did not define its type. Python
interpreter will automatically interpret variables a as an integer type.
• Python enables us to check the type of the variable used in the program. Python
provides us the type() function, which returns the type of the variable passed.
07/26/2025 K.Abinaya Assistant Professor SBU 13
07/26/2025 K.Abinaya Assistant Professor SBU 14
07/26/2025 K.Abinaya Assistant Professor SBU 15
07/26/2025 K.Abinaya Assistant Professor SBU 16
Numbers:
Number stores numeric values. The integer, float, and complex values belong to a Python
Numbers data-type.
Python provides the type() function to know the data-type of the variable.
1.Int - 10, 2, 29, -20, -150 etc.
2.Float - 1.9, 9.902, 15.2, etc.
3.complex - x + iy where x and y denote the real and imaginary parts, respectively. The
complex numbers like 2.14j, 2.0 + 2.3j, etc.
07/26/2025 K.Abinaya Assistant Professor SBU 17
Slicing
07/26/2025 K.Abinaya Assistant Professor SBU 18
Slicing Example
07/26/2025 K.Abinaya Assistant Professor SBU 19
Sequence Type
1.String
The string can be defined as the sequence of characters represented in the quotation
marks. In Python, we can use single, double, or triple quotes to define a string.
operator + is used to concatenate two strings as the operation "hello"+"
python" returns "hello python".
The operator * is known as a repetition operator as the operation "Python" *2 returns
'Python Python’.
07/26/2025 K.Abinaya Assistant Professor SBU 20
07/26/2025 K.Abinaya Assistant Professor SBU 21
2.List
Python Lists are similar to arrays in C. However, the list can contain data of different
types. The items stored in the list are separated with a comma (,) and enclosed within
square brackets [].
We can use slice [:] operators to access the data of the list. The concatenation operator
(+) and repetition operator (*) works with the list in the same way as they were working
with the strings.
07/26/2025 K.Abinaya Assistant Professor SBU 22
3.Python Tuple Data Type
Python tuple is another sequence data type that is similar to a list. A Python tuple
consists of a number of values separated by commas. Unlike lists, however, tuples are
enclosed within parentheses.
The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] )
and their elements and size can be changed, while tuples are enclosed in parentheses
( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists.
07/26/2025 K.Abinaya Assistant Professor SBU 23
Python Ranges
Python range() is an in-built function in Python which returns a sequence of
numbers starting from 0 and increments to 1 until it reaches a specified number.
We use range() function with for and while loop to generate a sequence of numbers.
Following is the syntax of the function:
07/26/2025 K.Abinaya Assistant Professor SBU 24
07/26/2025 K.Abinaya Assistant Professor SBU 25
Python Dictionary
 Dictionaries are enclosed by curly braces ({ }) and values can be assigned and
accessed using square braces ([]).
07/26/2025 K.Abinaya Assistant Professor SBU 26
Boolean
Boolean type provides two built-in values, True and False. These values are used to
determine the given statement true or false.
It denotes by the class bool. True can be represented by any non-zero value or 'T'
whereas false can be represented by the 0 or 'F'.
07/26/2025 K.Abinaya Assistant Professor SBU 27
07/26/2025 K.Abinaya Assistant Professor SBU 28
Python Data Type Conversion
1. Conversion to int
2. Conversion of Float
07/26/2025 K.Abinaya Assistant Professor SBU 29
Data Type Conversion Functions
Sr.No. Function & Description
1 int(x [,base])
Converts x to an integer. base specifies the base if x is a string.
2 long(x [,base] )
Converts x to a long integer. base specifies the base if x is a string.
3 float(x)
Converts x to a floating-point number.
4 complex(real [,imag])
Creates a complex number.
5 str(x)
Converts object x to a string representation.
6 repr(x)
Converts object x to an expression string.
7 eval(str)
Evaluates a string and returns an object.
8 tuple(s)
Converts s to a tuple.
07/26/2025 K.Abinaya Assistant Professor SBU 30
9 list(s)
Converts s to a list.
10 set(s)
Converts s to a set.
11 dict(d)
Creates a dictionary. d must be a sequence of (key,value) tuples.
12 frozenset(s)
Converts s to a frozen set.
13 chr(x)
Converts an integer to a character.
14 unichr(x)
Converts an integer to a Unicode character.
15 ord(x)
Converts a single character to its integer value.
16 hex(x)
Converts an integer to a hexadecimal string.
17 oct(x)
Converts an integer to an octal string.
07/26/2025 K.Abinaya Assistant Professor SBU 31
Set
 Python Set is the unordered collection of the data type. It is iterable, mutable(can
modify after creation), and has unique elements.
 In set, the order of the elements is undefined; it may return the changed sequence
of the element. The set is created by using a built-in function set(), or a sequence of
elements is passed in the curly braces and separated by the comma. It can contain
various types of values.
07/26/2025 K.Abinaya Assistant Professor SBU 32
Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
None Type: NoneType
Built-in Data Types
07/26/2025 K.Abinaya Assistant Professor SBU 33
Example Data Type
x = "Hello World" str
x = 20 int
x = 20.5 float
x = 1j complex
x = ["apple", "banana", "cherry"] list
x = ("apple", "banana", "cherry") tuple
x = range(6) range
07/26/2025 K.Abinaya Assistant Professor SBU 34
x = {"name" : "John", "age" : 36} dict
x = {"apple", "banana", "cherry"} set
x = frozenset({"apple", "banana",
"cherry"})
frozenset
x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
x = None NoneType
07/26/2025 K.Abinaya Assistant Professor SBU 35
Setting the Specific Data Type
Example Data Type
x = str("Hello World") str
x = int(20) int
x = float(20.5) float
x = complex(1j) complex
x = list(("apple", "banana", "cherry")) list
x = tuple(("apple", "banana", "cherry")) tuple
x = range(6) range
07/26/2025 K.Abinaya Assistant Professor SBU 36
x = dict(name="John", age=36) dict
x = set(("apple", "banana", "cherry")) set
x = frozenset(("apple", "banana", "cherry")) frozenset
x = bool(5) bool
x = bytes(5) bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
07/26/2025 K.Abinaya Assistant Professor SBU 37
07/26/2025 K.Abinaya Assistant Professor SBU 38
Maximum of two
numbers in Python
07/26/2025 K.Abinaya Assistant Professor SBU 39
07/26/2025 K.Abinaya Assistant Professor SBU 40
Data Conversion
int(x)
Converts x into integer
whole number
float(x)
Converts x into floating point
number
str(x)
Converts x into a string
representation
07/26/2025 K.Abinaya Assistant Professor SBU 41
chr(x)
Converts integer x into a
character
07/26/2025 K.Abinaya Assistant Professor SBU 42
07/26/2025 K.Abinaya Assistant Professor SBU 43
07/26/2025 K.Abinaya Assistant Professor SBU 44
Variable Names in Python
A variable can have a short name (like x and y) or a more descriptive name
(age, carname, total_volume). Rules for Python variables:
 A variable name must start with a letter or the underscore character
 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and underscores (A-z,
0-9, and _ )
 Variable names are case-sensitive (age, Age and AGE are three different variables)
07/26/2025 K.Abinaya Assistant Professor SBU 45
Many Values to Multiple Variables
One Value to Multiple Variables
07/26/2025 K.Abinaya Assistant Professor SBU 46
Unpack a Collection
07/26/2025 K.Abinaya Assistant Professor SBU 47
Output Variables
07/26/2025 K.Abinaya Assistant Professor SBU 48
07/26/2025 K.Abinaya Assistant Professor SBU 49
Python Casting
Specify a Variable Type
There may be times when you want to specify a type on to a variable. This can be
done with casting. Python is an object-orientated language, and as such it uses classes
to define data types, including its primitive types.
Casting in python is therefore done using constructor functions:
•int() - constructs an integer number from an integer literal, a float literal (by
removing all decimals), or a string literal (providing the string represents a whole
number)
•float() - constructs a float number from an integer literal, a float literal or a string
literal (providing the string represents a float or an integer)
•str() - constructs a string from a wide variety of data types, including strings, integer
literals and float literals
07/26/2025 K.Abinaya Assistant Professor SBU 50
Python Strings-Strings are Arrays
07/26/2025 K.Abinaya Assistant Professor SBU 51
String Length
Check String
07/26/2025 K.Abinaya Assistant Professor SBU 52
Check if NOT
07/26/2025 K.Abinaya Assistant Professor SBU 53
Python - Modify Strings
Remove Whitespace
-strip() method removes any whitespace from the beginning or the end:
07/26/2025 K.Abinaya Assistant Professor SBU 54
Replace String
The replace() method replaces a string with another string:
Split String
The split() method returns a list where the text between the specified separator becomes
the list items.
07/26/2025 K.Abinaya Assistant Professor SBU 55
String Concatenation
To add a space between them, add a " ":
07/26/2025 K.Abinaya Assistant Professor SBU 56
Input/Output
07/26/2025 K.Abinaya Assistant Professor SBU 57
07/26/2025 K.Abinaya Assistant Professor SBU 58
Python Operators
Python divides the operators in the following groups:
•Arithmetic operators
•Assignment operators
•Comparison operators
•Logical operators
•Identity operators
•Membership operators
•Bitwise operators
07/26/2025 K.Abinaya Assistant Professor SBU 59
Python Arithmetic Operators
Operator Name Example
+ Addition x + y
- Subtraction x - y
* Multiplication x * y
/ Division x / y
% Modulus x % y
** Exponentiation x ** y
// Floor division x // y
07/26/2025 K.Abinaya Assistant Professor SBU 60
Operator Example Same As
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x = x & 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x ^ 3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
Python Assignment Operators
07/26/2025 K.Abinaya Assistant Professor SBU 61
Python Comparison Operators
Operator Name Example
== Equal x == y
!= Not equal x != y
> Greater than x > y
< Less than x < y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
07/26/2025 K.Abinaya Assistant Professor SBU 62
Python Logical Operators
Operator Description Example
and Returns True if both
statements are true
x < 5 and x < 10
or Returns True if one of
the statements is true
x < 5 or x < 4
not Reverse the result,
returns False if the result
is true
not(x < 5 and x < 10)
07/26/2025 K.Abinaya Assistant Professor SBU 63
Python Identity Operators
Python Membership Operators
Operator Description Example
is Returns True if both variables are the same object x is y
is not Returns True if both variables are not the same
object
x is not y
Operator Description Example
in Returns True if a sequence with the specified value is present in the
object
x in y
not in Returns True if a sequence with the specified value is not present in
the object
x not in y
07/26/2025 K.Abinaya Assistant Professor SBU 64
07/26/2025 K.Abinaya Assistant Professor SBU 65
Python Conditions and If statements
Elif
The elif keyword is Python's way of saying "if the previous conditions were not true,
then try this condition".
07/26/2025 K.Abinaya Assistant Professor SBU 66
Else
The else keyword catches anything which isn't caught by the preceding conditions.
07/26/2025 K.Abinaya Assistant Professor SBU 67
Short Hand If
One line if else statement, with 3 conditions
07/26/2025 K.Abinaya Assistant Professor SBU 68
AND NOT
OR
07/26/2025 K.Abinaya Assistant Professor SBU 69
The pass Statement
if statements cannot be empty, but if you for some reason have an if statement
with no content, put in the pass statement to avoid getting an error.
07/26/2025 K.Abinaya Assistant Professor SBU 70
Python Loops
Python has two primitive loop commands:
•while loops
•for loops
while Loop
With the while loop we can execute a set of statements as long as a condition is true.
07/26/2025 K.Abinaya Assistant Professor SBU 71
Break Statement
With the break statement we can stop the loop even if the while condition is true:
Continue Statement
With the continue statement we can stop the current iteration, and continue with the
next:Continue to the next iteration if i is 3:
07/26/2025 K.Abinaya Assistant Professor SBU 72
Else Statement
With the else statement we can run a block of code once when the condition no longer is
true:
07/26/2025 K.Abinaya Assistant Professor SBU 73
Python For Loops
 A for loop is used for iterating over a sequence (that is either a list, a tuple, a
dictionary, a set, or a string).
 This is less like the for keyword in other programming languages, and works more like
an iterator method as found in other object-orientated programming languages.
 With the for loop we can execute a set of statements, once for each item in a list, tuple,
set etc.
07/26/2025 K.Abinaya Assistant Professor SBU 74
Looping Through a String
• Even strings are iterable objects, they contain a sequence of characters:
Break Statement
• With the break statement we can stop the loop before it has looped through all the
items:
07/26/2025 K.Abinaya Assistant Professor SBU 75
 Exit the loop when x is "banana", but this time the break comes before the print:
Continue Statement:
 With the continue statement we can stop the current iteration of the loop, and continue
with the next:
07/26/2025 K.Abinaya Assistant Professor SBU 76
The range() Function
 To loop through a set of code a specified number of times, we can use
the range() function,
 The range() function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a specified number.
07/26/2025 K.Abinaya Assistant Professor SBU 77
Else in For Loop
The else keyword in a for loop specifies a block of code to be executed when the loop is
finished:
Break the loop when x is 3, and see what happens with the else block:
07/26/2025 K.Abinaya Assistant Professor SBU 78
Nested Loops
The "inner loop" will be executed one time for each iteration of the
"outer loop":
07/26/2025 K.Abinaya Assistant Professor SBU 79
PYTHON FUNCTIONS
 A function is a block of code which only runs when it is called.
 You can pass data, known as parameters, into a function.
 A function can return data as a result.
Creating a Function
In Python a function is defined using the def keyword:
Calling a Function
To call a function, use the function name followed by parenthesis:
07/26/2025 K.Abinaya Assistant Professor SBU 80
Arguments
 Information can be passed into functions as arguments.
 Arguments are specified after the function name, inside the parentheses. You can
add as many arguments as you want, just separate them with a comma.
 The following example has a function with one argument (fname). When the function
is called, we pass along a first name, which is used inside the function to print the full
name:
07/26/2025 K.Abinaya Assistant Professor SBU 81
 A parameter is the variable listed inside the parentheses in the function
definition.
 An argument is the value that is sent to the function when it is called.
Number of Arguments
 By default, a function must be called with the correct number of arguments.
Meaning that if your function expects 2 arguments, you have to call the function
with 2 arguments, not more, and not less.
07/26/2025 K.Abinaya Assistant Professor SBU 82
Arbitrary Arguments, *args
 If you do not know how many arguments that will be passed into your function, add a
* before the parameter name in the function definition.
 This way the function will receive a tuple of arguments, and can access the items
accordingly:
 If the number of arguments is unknown, add a * before the parameter name:
07/26/2025 K.Abinaya Assistant Professor SBU 83
Keyword Arguments
You can also send arguments with the key = value syntax.
This way the order of the arguments does not matter.
07/26/2025 K.Abinaya Assistant Professor SBU 84
Arbitrary Keyword Arguments, **kwargs
 If you do not know how many keyword arguments that will be passed into your
function, add two asterisk: ** before the parameter name in the function
definition.
 This way the function will receive a dictionary of arguments, and can access the
items accordingly:
 If the number of keyword arguments is unknown, add a double ** before the
parameter name:
07/26/2025 K.Abinaya Assistant Professor SBU 85
Default Parameter Value
 If we call the function without argument, it uses the default value:
07/26/2025 K.Abinaya Assistant Professor SBU 86
Passing a List as an Argument
 You can send any data types of argument to a function (string, number, list, dictionary etc.), and it
will be treated as the same data type inside the function.
 E.g. if you send a List as an argument, it will still be a List when it reaches the function:
07/26/2025 K.Abinaya Assistant Professor SBU 87
Return Values
To let a function return a value, use the return statement:
The pass Statement
function definitions cannot be empty, but if you for some reason have a function definition
with no content, put in the pass statement to avoid getting an error.
07/26/2025 K.Abinaya Assistant Professor SBU 88
Python program to find the largest number among the three input numbers
07/26/2025 K.Abinaya Assistant Professor SBU 89
07/26/2025 K.Abinaya Assistant Professor SBU 90
Input & Output Statements
Input – to read values from the user
Syntax:
Variable=input()
Input() – function used to read values
Output- to display the result
Syntax:
print(“hello students”)
print(“welcome”)
Print(“value is”,x)
07/26/2025 K.Abinaya Assistant Professor SBU 91
Input from User in Python
Sometimes a developer might want to take user input at some point in the program. To
do this Python provides an input() function.
Syntax:
input('prompt’)
Example 1: Python get user input with a message
07/26/2025 K.Abinaya Assistant Professor SBU 92
Example 2: Integer input in Python
How to take Multiple Inputs in Python :
we can take multiple inputs of the same data type at a time in python, using map()
method in python.
07/26/2025 K.Abinaya Assistant Professor SBU 93
Inputs for the Sequence Data Types like List, Set, Tuple, etc.
In the case of List and Set the input can be taken from the user in two ways.
1.Taking List/Set elements one by one by using the append()/add() methods.
2.Using map() and list() / set() methods.
07/26/2025 K.Abinaya Assistant Professor SBU 94
Using map() and list() / set() Methods
Output using print() function
Python print() function prints the message to the screen or any other standard output device.
Parameters:
object - value(s) to be printed
sep (optional) - allows us to separate multiple objects inside print().
end (optional) - allows us to add add specific values like new line "n", tab "t"
file (optional) - where the values are printed. It's default value is sys.stdout (screen)
flush (optional) - boolean specifying if the output is flushed or buffered. Default: False
07/26/2025 K.Abinaya Assistant Professor SBU 95
07/26/2025 K.Abinaya Assistant Professor SBU 96
07/26/2025 K.Abinaya Assistant Professor SBU 97
07/26/2025 K.Abinaya Assistant Professor SBU 98
Separator
The print() function can accept any number of positional arguments. To separate these
positional arguments , keyword argument “sep” is used.
07/26/2025 K.Abinaya Assistant Professor SBU 99
07/26/2025 K.Abinaya Assistant Professor SBU 100
07/26/2025 K.Abinaya Assistant Professor SBU 101
07/26/2025 K.Abinaya Assistant Professor SBU 102
Python Database
Communication
07/26/2025 K.Abinaya Assistant Professor SBU 103
Introduction to Databases
As said above, a database is the collection of data in a structured manner for easy
access and management. We have various database management systems which include:
1. MySQL
2. Oracle Database
3. SQL server
4. Sybase
5. Informix
6. IBM db2
7. NO SQL
We will be using the MySQL database system since it is easier and convenient to use.
It uses the SQL (Structured Query Language) to do operations like creating, accessing,
manipulating, deleting, etc., on the databases.
07/26/2025 K.Abinaya Assistant Professor SBU 104
Python Modules to Connect to MySQL
To communicate with MySQL Python provides the below modules:
1. MySQL Connector Python
2. PyMySQL
3. MySQLDB
4. MySqlClient
5. OurSQL
All the above modules have almost the same syntax and methods to handle the
databases.
07/26/2025 K.Abinaya Assistant Professor SBU 105
Communication Between Python and MySQL
Python communicates with MySQL by forming a connection with it. The process of
communication happens in the following steps:
3. Then we use the connect() method to send the connection request to Mysql.
This function returns an MYSQL Connection object on a successful connection.
4. After this, we call the cursor() method to further do various operations on the
database.
07/26/2025 K.Abinaya Assistant Professor SBU 106
5. Now we can execute various operations and get the
results by giving the query to the execute the () function.
6. We can also read the result by using the functions
cursor.fetchall() or fetchone() or fetchmany().
7. When we are done working with the database we can
close the cursor and the connection using the functions
cursor.close() and connection.close().
07/26/2025 K.Abinaya Assistant Professor SBU 107
Connecting to the MySQL
the first step after importing the module is to send the connection request using the
connect() method. This function takes the following arguments:
1. Username: It is the username that one uses to work with MySQL server. The default
username is root.
2. Password: This is the password given by the user when one is installing the MySQL
database.
3. Host Name: This is the server name or IP address on which MySQL is running. We
can either give it as ‘localhost’ or 127.0.0.0
4. Database name: This is the name of the database to which one wants to connect.
This is an optional parameter.
07/26/2025 K.Abinaya Assistant Professor SBU 108
07/26/2025 K.Abinaya Assistant Professor SBU 109
07/26/2025 K.Abinaya Assistant Professor SBU 110

Python Conditional and Looping statements.pptx

  • 1.
    S11BLH21 PROGRAMMING INPYTHON - 4 COURSE OBJECTIVES  To learn about data structures lists, tuples, and dictionaries in Python.  To build packages with Python modules for reusability and handle user/custom exceptions.  To create real world GUI applications, establish Database connectivity and Networking UNIT 1 INTRODUCTION TO PYTHON 12 Hrs. History of Python- Introduction to the IDLE interpreter (shell) - Data Types - Built-in function – Conditional statements - Iterative statements- Input/output functions - Python Database Communication - data analysis and visualization using python. Practical:  Implement built-in functions and trace the type of data items.  Implement concepts of Conditional and Iterative Statements.  Use the built-in csv module to read and write from a CSV file in Python.  Perform data analysis and visualization on a given dataset using Python libraries like pandas, numpy, matplotlib and display charts, graphs, and plots. 07/26/2025 K.Abinaya Assistant Professor SBU 1
  • 2.
    History of Python •Python was developed by Guido van Rossum in the late eighties and early nineties at the National Research Institute for Mathematics and Computer Science in the Netherlands. Major Python Releases Python 0.9.0 • Python's first published version is 0.9. It was released in February 1991. It consisted of support for core object-oriented programming principles. Python 1.0 • In January 1994, version 1.0 was released, armed with functional programming tools, features like support for complex numbers etc. 07/26/2025 K.Abinaya Assistant Professor SBU 2
  • 3.
    Python 2.0  Nextmajor version − Python 2.0 was launched in October 2000. Many new features such as list comprehension, garbage collection and Unicode support were included with it. Python 3.0  Python 3.0, a completely revamped version of Python was released in December 2008. The primary objective of this revamp was to remove a lot of discrepancies that had crept in Python 2.x versions.  Python 3 was backported to Python 2.6. It also included a utility named as python2to3 to facilitate automatic translation of Python 2 code to Python 3. Current Version  Meanwhile, more and more features have been incorporated into Python's 3.x branch. As of date, Python 3.11.2 is the current stable version, released in February 2023. 07/26/2025 K.Abinaya Assistant Professor SBU 3
  • 4.
    IDLE Software inPython  IDLE stands for Integrated Development and Learning Environment.  The lightweight and user-friendly Python IDLE (Integrated Development and Learning Environment) is a tool for Python programming.  Since version 1.5.2b1, the standard Python implementation has included IDLE, an integrated development environment.  Many Linux distributions include it in the Python packaging as an optional component.  The Tkinter GUI toolkit and Python are used throughout. 07/26/2025 K.Abinaya Assistant Professor SBU 4
  • 5.
    Python Syntax Rules -Python is case sensitive. Hence a variable with name “python” is not same as pYThon.  -For path specification, python uses forward slashes. Hence if you are working with a file, the default path for the file in case of Windows OS will have backward slashes, which you will have to convert to forward slashes to make them work in your python script  -Eg: For window's path C:folderAfolderB relative python program path should be C:/folderA/folderB 07/26/2025 K.Abinaya Assistant Professor SBU 5
  • 6.
    • In python,there is no command terminator, which means no semicolon ; or anything. So if you want to print something as output, all you have to do is: In one line only a single executable statement should be written and the line change act as command terminator in python. To write two separate executable statements in a single line, you should use a semicolon ; to separate the commands. For example, 07/26/2025 K.Abinaya Assistant Professor SBU 6
  • 7.
    Execute Python Syntax •As we learned in the previous page, Python syntax can be executed by writing directly in the Command Line: Or by creating a python file on the server, using the .py file extension, and running it in the Command Line: 07/26/2025 K.Abinaya Assistant Professor SBU 7
  • 8.
    Python Indentation • Indentationrefers to the spaces at the beginning of a code line. • Where in other programming languages the indentation in code is for readability only, the indentation in Python is very important. • Python uses indentation to indicate a block of code. Example if 5 > 2: print("Five is greater than two!") 07/26/2025 K.Abinaya Assistant Professor SBU 8
  • 9.
    • Python willgive you an error if you skip the indentation: Example Syntax Error: if 5 > 2: print("Five is greater than two!") 07/26/2025 K.Abinaya Assistant Professor SBU 9
  • 10.
    Points to Rememberwhile Writing a Python Program  • Case sensitive • Punctuation is not required at end of the statement • In case of string use single or double quotes i.e. ‘ ’ or “ ” • Must use proper indentation • Python Program can be executed in two different modes: • Interactive Mode Programming • Script mode programming 07/26/2025 K.Abinaya Assistant Professor SBU 10
  • 11.
    Expressions • In Python,operators are special symbols that designate that some sort of computation should be performed. The values that an operator acts on are called operands. >>> a = 10 >>> b = 20 >>> a + b 30 07/26/2025 K.Abinaya Assistant Professor SBU 11
  • 12.
    In this case,the + operator adds the operands a and b together. An operand can be either a literal value or a variable that references an object: >>> a = 10 >>> b = 20 >>> a + b - 5 25 07/26/2025 K.Abinaya Assistant Professor SBU 12
  • 13.
    Python Data Types •Variables can hold values, and every value has a data-type. Python is a dynamically typed language; hence we do not need to define the type of the variable while declaring it. The interpreter implicitly binds the value with its type. a = 5 • The variable a holds integer value five and we did not define its type. Python interpreter will automatically interpret variables a as an integer type. • Python enables us to check the type of the variable used in the program. Python provides us the type() function, which returns the type of the variable passed. 07/26/2025 K.Abinaya Assistant Professor SBU 13
  • 14.
  • 15.
  • 16.
  • 17.
    Numbers: Number stores numericvalues. The integer, float, and complex values belong to a Python Numbers data-type. Python provides the type() function to know the data-type of the variable. 1.Int - 10, 2, 29, -20, -150 etc. 2.Float - 1.9, 9.902, 15.2, etc. 3.complex - x + iy where x and y denote the real and imaginary parts, respectively. The complex numbers like 2.14j, 2.0 + 2.3j, etc. 07/26/2025 K.Abinaya Assistant Professor SBU 17
  • 18.
  • 19.
    Slicing Example 07/26/2025 K.AbinayaAssistant Professor SBU 19
  • 20.
    Sequence Type 1.String The stringcan be defined as the sequence of characters represented in the quotation marks. In Python, we can use single, double, or triple quotes to define a string. operator + is used to concatenate two strings as the operation "hello"+" python" returns "hello python". The operator * is known as a repetition operator as the operation "Python" *2 returns 'Python Python’. 07/26/2025 K.Abinaya Assistant Professor SBU 20
  • 21.
  • 22.
    2.List Python Lists aresimilar to arrays in C. However, the list can contain data of different types. The items stored in the list are separated with a comma (,) and enclosed within square brackets []. We can use slice [:] operators to access the data of the list. The concatenation operator (+) and repetition operator (*) works with the list in the same way as they were working with the strings. 07/26/2025 K.Abinaya Assistant Professor SBU 22
  • 23.
    3.Python Tuple DataType Python tuple is another sequence data type that is similar to a list. A Python tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses. The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists. 07/26/2025 K.Abinaya Assistant Professor SBU 23
  • 24.
    Python Ranges Python range()is an in-built function in Python which returns a sequence of numbers starting from 0 and increments to 1 until it reaches a specified number. We use range() function with for and while loop to generate a sequence of numbers. Following is the syntax of the function: 07/26/2025 K.Abinaya Assistant Professor SBU 24
  • 25.
  • 26.
    Python Dictionary  Dictionariesare enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]). 07/26/2025 K.Abinaya Assistant Professor SBU 26
  • 27.
    Boolean Boolean type providestwo built-in values, True and False. These values are used to determine the given statement true or false. It denotes by the class bool. True can be represented by any non-zero value or 'T' whereas false can be represented by the 0 or 'F'. 07/26/2025 K.Abinaya Assistant Professor SBU 27
  • 28.
  • 29.
    Python Data TypeConversion 1. Conversion to int 2. Conversion of Float 07/26/2025 K.Abinaya Assistant Professor SBU 29
  • 30.
    Data Type ConversionFunctions Sr.No. Function & Description 1 int(x [,base]) Converts x to an integer. base specifies the base if x is a string. 2 long(x [,base] ) Converts x to a long integer. base specifies the base if x is a string. 3 float(x) Converts x to a floating-point number. 4 complex(real [,imag]) Creates a complex number. 5 str(x) Converts object x to a string representation. 6 repr(x) Converts object x to an expression string. 7 eval(str) Evaluates a string and returns an object. 8 tuple(s) Converts s to a tuple. 07/26/2025 K.Abinaya Assistant Professor SBU 30
  • 31.
    9 list(s) Converts sto a list. 10 set(s) Converts s to a set. 11 dict(d) Creates a dictionary. d must be a sequence of (key,value) tuples. 12 frozenset(s) Converts s to a frozen set. 13 chr(x) Converts an integer to a character. 14 unichr(x) Converts an integer to a Unicode character. 15 ord(x) Converts a single character to its integer value. 16 hex(x) Converts an integer to a hexadecimal string. 17 oct(x) Converts an integer to an octal string. 07/26/2025 K.Abinaya Assistant Professor SBU 31
  • 32.
    Set  Python Setis the unordered collection of the data type. It is iterable, mutable(can modify after creation), and has unique elements.  In set, the order of the elements is undefined; it may return the changed sequence of the element. The set is created by using a built-in function set(), or a sequence of elements is passed in the curly braces and separated by the comma. It can contain various types of values. 07/26/2025 K.Abinaya Assistant Professor SBU 32
  • 33.
    Text Type: str NumericTypes: int, float, complex Sequence Types: list, tuple, range Mapping Type: dict Set Types: set, frozenset Boolean Type: bool Binary Types: bytes, bytearray, memoryview None Type: NoneType Built-in Data Types 07/26/2025 K.Abinaya Assistant Professor SBU 33
  • 34.
    Example Data Type x= "Hello World" str x = 20 int x = 20.5 float x = 1j complex x = ["apple", "banana", "cherry"] list x = ("apple", "banana", "cherry") tuple x = range(6) range 07/26/2025 K.Abinaya Assistant Professor SBU 34
  • 35.
    x = {"name": "John", "age" : 36} dict x = {"apple", "banana", "cherry"} set x = frozenset({"apple", "banana", "cherry"}) frozenset x = True bool x = b"Hello" bytes x = bytearray(5) bytearray x = memoryview(bytes(5)) memoryview x = None NoneType 07/26/2025 K.Abinaya Assistant Professor SBU 35
  • 36.
    Setting the SpecificData Type Example Data Type x = str("Hello World") str x = int(20) int x = float(20.5) float x = complex(1j) complex x = list(("apple", "banana", "cherry")) list x = tuple(("apple", "banana", "cherry")) tuple x = range(6) range 07/26/2025 K.Abinaya Assistant Professor SBU 36
  • 37.
    x = dict(name="John",age=36) dict x = set(("apple", "banana", "cherry")) set x = frozenset(("apple", "banana", "cherry")) frozenset x = bool(5) bool x = bytes(5) bytes x = bytearray(5) bytearray x = memoryview(bytes(5)) memoryview 07/26/2025 K.Abinaya Assistant Professor SBU 37
  • 38.
  • 39.
    Maximum of two numbersin Python 07/26/2025 K.Abinaya Assistant Professor SBU 39
  • 40.
  • 41.
    Data Conversion int(x) Converts xinto integer whole number float(x) Converts x into floating point number str(x) Converts x into a string representation 07/26/2025 K.Abinaya Assistant Professor SBU 41
  • 42.
    chr(x) Converts integer xinto a character 07/26/2025 K.Abinaya Assistant Professor SBU 42
  • 43.
  • 44.
  • 45.
    Variable Names inPython A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules for Python variables:  A variable name must start with a letter or the underscore character  A variable name cannot start with a number  A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )  Variable names are case-sensitive (age, Age and AGE are three different variables) 07/26/2025 K.Abinaya Assistant Professor SBU 45
  • 46.
    Many Values toMultiple Variables One Value to Multiple Variables 07/26/2025 K.Abinaya Assistant Professor SBU 46
  • 47.
    Unpack a Collection 07/26/2025K.Abinaya Assistant Professor SBU 47
  • 48.
    Output Variables 07/26/2025 K.AbinayaAssistant Professor SBU 48
  • 49.
  • 50.
    Python Casting Specify aVariable Type There may be times when you want to specify a type on to a variable. This can be done with casting. Python is an object-orientated language, and as such it uses classes to define data types, including its primitive types. Casting in python is therefore done using constructor functions: •int() - constructs an integer number from an integer literal, a float literal (by removing all decimals), or a string literal (providing the string represents a whole number) •float() - constructs a float number from an integer literal, a float literal or a string literal (providing the string represents a float or an integer) •str() - constructs a string from a wide variety of data types, including strings, integer literals and float literals 07/26/2025 K.Abinaya Assistant Professor SBU 50
  • 51.
    Python Strings-Strings areArrays 07/26/2025 K.Abinaya Assistant Professor SBU 51
  • 52.
    String Length Check String 07/26/2025K.Abinaya Assistant Professor SBU 52
  • 53.
    Check if NOT 07/26/2025K.Abinaya Assistant Professor SBU 53
  • 54.
    Python - ModifyStrings Remove Whitespace -strip() method removes any whitespace from the beginning or the end: 07/26/2025 K.Abinaya Assistant Professor SBU 54
  • 55.
    Replace String The replace()method replaces a string with another string: Split String The split() method returns a list where the text between the specified separator becomes the list items. 07/26/2025 K.Abinaya Assistant Professor SBU 55
  • 56.
    String Concatenation To adda space between them, add a " ": 07/26/2025 K.Abinaya Assistant Professor SBU 56
  • 57.
  • 58.
  • 59.
    Python Operators Python dividesthe operators in the following groups: •Arithmetic operators •Assignment operators •Comparison operators •Logical operators •Identity operators •Membership operators •Bitwise operators 07/26/2025 K.Abinaya Assistant Professor SBU 59
  • 60.
    Python Arithmetic Operators OperatorName Example + Addition x + y - Subtraction x - y * Multiplication x * y / Division x / y % Modulus x % y ** Exponentiation x ** y // Floor division x // y 07/26/2025 K.Abinaya Assistant Professor SBU 60
  • 61.
    Operator Example SameAs = x = 5 x = 5 += x += 3 x = x + 3 -= x -= 3 x = x - 3 *= x *= 3 x = x * 3 /= x /= 3 x = x / 3 %= x %= 3 x = x % 3 //= x //= 3 x = x // 3 **= x **= 3 x = x ** 3 &= x &= 3 x = x & 3 |= x |= 3 x = x | 3 ^= x ^= 3 x = x ^ 3 >>= x >>= 3 x = x >> 3 <<= x <<= 3 x = x << 3 Python Assignment Operators 07/26/2025 K.Abinaya Assistant Professor SBU 61
  • 62.
    Python Comparison Operators OperatorName Example == Equal x == y != Not equal x != y > Greater than x > y < Less than x < y >= Greater than or equal to x >= y <= Less than or equal to x <= y 07/26/2025 K.Abinaya Assistant Professor SBU 62
  • 63.
    Python Logical Operators OperatorDescription Example and Returns True if both statements are true x < 5 and x < 10 or Returns True if one of the statements is true x < 5 or x < 4 not Reverse the result, returns False if the result is true not(x < 5 and x < 10) 07/26/2025 K.Abinaya Assistant Professor SBU 63
  • 64.
    Python Identity Operators PythonMembership Operators Operator Description Example is Returns True if both variables are the same object x is y is not Returns True if both variables are not the same object x is not y Operator Description Example in Returns True if a sequence with the specified value is present in the object x in y not in Returns True if a sequence with the specified value is not present in the object x not in y 07/26/2025 K.Abinaya Assistant Professor SBU 64
  • 65.
  • 66.
    Python Conditions andIf statements Elif The elif keyword is Python's way of saying "if the previous conditions were not true, then try this condition". 07/26/2025 K.Abinaya Assistant Professor SBU 66
  • 67.
    Else The else keywordcatches anything which isn't caught by the preceding conditions. 07/26/2025 K.Abinaya Assistant Professor SBU 67
  • 68.
    Short Hand If Oneline if else statement, with 3 conditions 07/26/2025 K.Abinaya Assistant Professor SBU 68
  • 69.
    AND NOT OR 07/26/2025 K.AbinayaAssistant Professor SBU 69
  • 70.
    The pass Statement ifstatements cannot be empty, but if you for some reason have an if statement with no content, put in the pass statement to avoid getting an error. 07/26/2025 K.Abinaya Assistant Professor SBU 70
  • 71.
    Python Loops Python hastwo primitive loop commands: •while loops •for loops while Loop With the while loop we can execute a set of statements as long as a condition is true. 07/26/2025 K.Abinaya Assistant Professor SBU 71
  • 72.
    Break Statement With thebreak statement we can stop the loop even if the while condition is true: Continue Statement With the continue statement we can stop the current iteration, and continue with the next:Continue to the next iteration if i is 3: 07/26/2025 K.Abinaya Assistant Professor SBU 72
  • 73.
    Else Statement With theelse statement we can run a block of code once when the condition no longer is true: 07/26/2025 K.Abinaya Assistant Professor SBU 73
  • 74.
    Python For Loops A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).  This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.  With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc. 07/26/2025 K.Abinaya Assistant Professor SBU 74
  • 75.
    Looping Through aString • Even strings are iterable objects, they contain a sequence of characters: Break Statement • With the break statement we can stop the loop before it has looped through all the items: 07/26/2025 K.Abinaya Assistant Professor SBU 75
  • 76.
     Exit theloop when x is "banana", but this time the break comes before the print: Continue Statement:  With the continue statement we can stop the current iteration of the loop, and continue with the next: 07/26/2025 K.Abinaya Assistant Professor SBU 76
  • 77.
    The range() Function To loop through a set of code a specified number of times, we can use the range() function,  The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number. 07/26/2025 K.Abinaya Assistant Professor SBU 77
  • 78.
    Else in ForLoop The else keyword in a for loop specifies a block of code to be executed when the loop is finished: Break the loop when x is 3, and see what happens with the else block: 07/26/2025 K.Abinaya Assistant Professor SBU 78
  • 79.
    Nested Loops The "innerloop" will be executed one time for each iteration of the "outer loop": 07/26/2025 K.Abinaya Assistant Professor SBU 79
  • 80.
    PYTHON FUNCTIONS  Afunction is a block of code which only runs when it is called.  You can pass data, known as parameters, into a function.  A function can return data as a result. Creating a Function In Python a function is defined using the def keyword: Calling a Function To call a function, use the function name followed by parenthesis: 07/26/2025 K.Abinaya Assistant Professor SBU 80
  • 81.
    Arguments  Information canbe passed into functions as arguments.  Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.  The following example has a function with one argument (fname). When the function is called, we pass along a first name, which is used inside the function to print the full name: 07/26/2025 K.Abinaya Assistant Professor SBU 81
  • 82.
     A parameteris the variable listed inside the parentheses in the function definition.  An argument is the value that is sent to the function when it is called. Number of Arguments  By default, a function must be called with the correct number of arguments. Meaning that if your function expects 2 arguments, you have to call the function with 2 arguments, not more, and not less. 07/26/2025 K.Abinaya Assistant Professor SBU 82
  • 83.
    Arbitrary Arguments, *args If you do not know how many arguments that will be passed into your function, add a * before the parameter name in the function definition.  This way the function will receive a tuple of arguments, and can access the items accordingly:  If the number of arguments is unknown, add a * before the parameter name: 07/26/2025 K.Abinaya Assistant Professor SBU 83
  • 84.
    Keyword Arguments You canalso send arguments with the key = value syntax. This way the order of the arguments does not matter. 07/26/2025 K.Abinaya Assistant Professor SBU 84
  • 85.
    Arbitrary Keyword Arguments,**kwargs  If you do not know how many keyword arguments that will be passed into your function, add two asterisk: ** before the parameter name in the function definition.  This way the function will receive a dictionary of arguments, and can access the items accordingly:  If the number of keyword arguments is unknown, add a double ** before the parameter name: 07/26/2025 K.Abinaya Assistant Professor SBU 85
  • 86.
    Default Parameter Value If we call the function without argument, it uses the default value: 07/26/2025 K.Abinaya Assistant Professor SBU 86
  • 87.
    Passing a Listas an Argument  You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.  E.g. if you send a List as an argument, it will still be a List when it reaches the function: 07/26/2025 K.Abinaya Assistant Professor SBU 87
  • 88.
    Return Values To leta function return a value, use the return statement: The pass Statement function definitions cannot be empty, but if you for some reason have a function definition with no content, put in the pass statement to avoid getting an error. 07/26/2025 K.Abinaya Assistant Professor SBU 88
  • 89.
    Python program tofind the largest number among the three input numbers 07/26/2025 K.Abinaya Assistant Professor SBU 89
  • 90.
  • 91.
    Input & OutputStatements Input – to read values from the user Syntax: Variable=input() Input() – function used to read values Output- to display the result Syntax: print(“hello students”) print(“welcome”) Print(“value is”,x) 07/26/2025 K.Abinaya Assistant Professor SBU 91
  • 92.
    Input from Userin Python Sometimes a developer might want to take user input at some point in the program. To do this Python provides an input() function. Syntax: input('prompt’) Example 1: Python get user input with a message 07/26/2025 K.Abinaya Assistant Professor SBU 92
  • 93.
    Example 2: Integerinput in Python How to take Multiple Inputs in Python : we can take multiple inputs of the same data type at a time in python, using map() method in python. 07/26/2025 K.Abinaya Assistant Professor SBU 93
  • 94.
    Inputs for theSequence Data Types like List, Set, Tuple, etc. In the case of List and Set the input can be taken from the user in two ways. 1.Taking List/Set elements one by one by using the append()/add() methods. 2.Using map() and list() / set() methods. 07/26/2025 K.Abinaya Assistant Professor SBU 94
  • 95.
    Using map() andlist() / set() Methods Output using print() function Python print() function prints the message to the screen or any other standard output device. Parameters: object - value(s) to be printed sep (optional) - allows us to separate multiple objects inside print(). end (optional) - allows us to add add specific values like new line "n", tab "t" file (optional) - where the values are printed. It's default value is sys.stdout (screen) flush (optional) - boolean specifying if the output is flushed or buffered. Default: False 07/26/2025 K.Abinaya Assistant Professor SBU 95
  • 96.
  • 97.
  • 98.
  • 99.
    Separator The print() functioncan accept any number of positional arguments. To separate these positional arguments , keyword argument “sep” is used. 07/26/2025 K.Abinaya Assistant Professor SBU 99
  • 100.
  • 101.
  • 102.
  • 103.
  • 104.
    Introduction to Databases Assaid above, a database is the collection of data in a structured manner for easy access and management. We have various database management systems which include: 1. MySQL 2. Oracle Database 3. SQL server 4. Sybase 5. Informix 6. IBM db2 7. NO SQL We will be using the MySQL database system since it is easier and convenient to use. It uses the SQL (Structured Query Language) to do operations like creating, accessing, manipulating, deleting, etc., on the databases. 07/26/2025 K.Abinaya Assistant Professor SBU 104
  • 105.
    Python Modules toConnect to MySQL To communicate with MySQL Python provides the below modules: 1. MySQL Connector Python 2. PyMySQL 3. MySQLDB 4. MySqlClient 5. OurSQL All the above modules have almost the same syntax and methods to handle the databases. 07/26/2025 K.Abinaya Assistant Professor SBU 105
  • 106.
    Communication Between Pythonand MySQL Python communicates with MySQL by forming a connection with it. The process of communication happens in the following steps: 3. Then we use the connect() method to send the connection request to Mysql. This function returns an MYSQL Connection object on a successful connection. 4. After this, we call the cursor() method to further do various operations on the database. 07/26/2025 K.Abinaya Assistant Professor SBU 106
  • 107.
    5. Now wecan execute various operations and get the results by giving the query to the execute the () function. 6. We can also read the result by using the functions cursor.fetchall() or fetchone() or fetchmany(). 7. When we are done working with the database we can close the cursor and the connection using the functions cursor.close() and connection.close(). 07/26/2025 K.Abinaya Assistant Professor SBU 107
  • 108.
    Connecting to theMySQL the first step after importing the module is to send the connection request using the connect() method. This function takes the following arguments: 1. Username: It is the username that one uses to work with MySQL server. The default username is root. 2. Password: This is the password given by the user when one is installing the MySQL database. 3. Host Name: This is the server name or IP address on which MySQL is running. We can either give it as ‘localhost’ or 127.0.0.0 4. Database name: This is the name of the database to which one wants to connect. This is an optional parameter. 07/26/2025 K.Abinaya Assistant Professor SBU 108
  • 109.
  • 110.