Python PPT
Python PPT
It supports Object
Oriented programming approach to develop applications.
Applications
Software development.
Mathematics.
System scripting.
Automation testing.
Advantages of Python
Python has syntax that allows developers to write code in fewer lines compared to other
programming languages.
Keywords - Python keywords are reserved words that have a special meaning associated
with them and can’t be used for anything but those specific purposes.
Escape Sequence - An escape sequence is a sequence of characters that, when used inside a character or
string, does not represent itself but is converted into another character .
print(2 ** 3 ** 2) a = 20
L b = 10
R
c = 15
d=5
e=0
e = (a + b) * c / d #( 30 * 15 ) / 5
print ("Value of (a + b) * c / d is ", e) # 90.0
e = ((a + b) * c) / d # (30 * 15 ) / 5
print ("Value of ((a + b) * c) / d is ", e) # 90.0
e = a + (b * c) / d; # 20 + (150/5)
print ("Value of a + (b * c) / d is ", e) # 50.0
Python Data types - Data types specify the different sizes and values that can be stored in the variable.
Type Casting – Converting variables declared in specific data type to the different data type is called
type casting.
Python performs two types of casting
• Implicit – The python interpreter automatically performs an implicit type conversion, which avoids loss
of data.
• Explicit – The explicit type conversion is performed by the user, using built – in function.
• To do type casting following built – in function are used.
Int – Convert any type variable to the integer type.
Float – Convert any type variable to the float type.
Complex – Convert any type variable to the complex type.
Bool – Convert any type variable to the bool type.
Str – Convert any type variable to the string type.
Program 4
pi = 3.14
print(pi)
print(type(pi))
num = int(pi)
print(num)
print(type(num))
num = 314
print(num)
print(type(num))
num1 = float(num)
print(num1)
print(type(num1))
Variables - A variable is a reserved memory area (memory address) to store value.
x=y=z = "Orange"
print("The value of x:",x)
print("The value of y: “,y)
print("The value of z:",z)
Unpack a Collection
If you have a collection of values in a list, tuple etc. Python allows to extract the values into variables. This is
called unpacking.
# Unpacking a collection
The bool() function allows to evaluate any value, and gives True or False in return.
There are not many values that evaluate to False, except empty values, such as (), [ ], { }, “ “, the number 0,
and the value none, and the false value evaluates to False.
Logical Operators - Logical operators are used to combine conditional statements:
Identity Operators - Identity operators are used to compare the objects, not if they
are equal, but if they are actually the same object, with the
same memory location.
Membership Operators – It is used to check if a sequence is present in an object.
Bitwise Operators – Bitwise operators are used to compare binary numbers
Bitwise & - It performs logical AND operation on the integer value after converting an integer to a binary value
and gives the result as a decimal value. It returns True only if both operands are True. Otherwise
False.
Bitwise | - It performs logical OR operation on the integer value after converting an integer to a binary value
and gives the result as a decimal value. It returns False if one of the operand is False/ True.
Otherwise True.
Bitwise xor ^ - It performs logical XOR operation on the integer value after converting an integer to a binary
value and gives the result as a decimal value.
Bitwise left – shift << - It shifts the bit by a given number of place towards left and fill’s zeros to new position.
Bitwise right – shift >> - It shifts the bit by a given number of place towards right and here some bits are lost.
Python Control Flow
Syntax
Nested – if statement - The nested if – else statement is an if statement inside another if – else statement.
Indentation is the only way to differentiate the level of nesting.
Syntax :
For loop - A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
Syntax :
Python allows to nest one or more loops within another loop. This is known as a nested for loop.
Syntax :
Break and Continue statement
Note - The else block will not be executed if the loop is stopped by a break statement.
While Loop in Python – The while loop is an entry controlled loop, and for loop is a count controlled loop.
Syntax :
while condition:
statement
Using list( ) constructor – Created a list by passing the , separated values inside the [ ].
Using [ ] – Create a list simply by enclosing the items inside the square bracket.
Negative indexing
Using in keyword
Change list items
Change a single item value
Syntax
Add list items
Append Variable name.append(value), it takes exactly one argument
Clear
If position not given,
Index value Removes the last item
Variable name.clear( )
Loop list – Using for( ) and while( ) loop, we can loop through the list using range( ) & len( ) function
List Comprehension offers the shortest syntax for looping through lists:
Syntax :
newlist = [x for x in fruits if "a" in x] The condition is like a filter that only accepts the items that valuate
to True
Python - Sort Lists
Reverse() – This method reverses the current sorting order of the elements.
Syntax
Python copy list
Using copy( ) method newlist = variable name.copy()
Using tuple( ) constructor – Creating a tuple by passing the , separated values inside the ().
Using () – Create a tuple simply by enclosing the items inside the () bracket.
Negative indexing
Using in keyword
Update a Tuple: Tuples cannot be changed as they are immutable, by converting a tuple to list the values
can be changed.
Append
Adding to tuples
Remove tuple items Convert tuple to list and use remove() method,
Variable name.remove(“Value”)
Unpacking a tuple
In Python, the values can be extracted back into the variables. This is called "unpacking"
Note: The number of variables must match the number of values in the tuple, if not, you must use an
asterisk to collect the remaining values as a list.
If the number of variables is less than the number of values, add an * to the variable name and the values
Will be assigned to the variable as a list.
Loop tuple – Using for( ) and while( ) loop, we can loop through the list using range( ) & len( ) function
Tuple copy - Create a copy of a tuple using the assignment operator “ = “. This operation will create
only a reference copy and not a deep copy because tuples are immutable.
Sets
Sets are used to store multiple values in a single variable.
Sets are unordered, unchangeable, does not allow duplicate value, heterogeneous.
Sets are created using two ways:
Using set{} constructor – Created a list by passing the , separated values inside the { }.
Using () – Create a set simply by enclosing the items inside the { } bracket.
Once a set is created, items cannot be changed, but new items can be
added.
Add set items
To add items from another set into the current set, use the update() method.
The object in the update() method does not have to be a set, it can be any iterable object
(tuples, lists, dictionaries etc.).
Remove set items
Remove Variable name.remove(“value”)
Loop Set – Using for( ) and while( ) loop, we can loop through the list using range( ) & len( ) function
set1 = {"apple", "banana", "cherry"}
for x in set1:
print(x)
Stack
A Stack is a data structure that follows the LIFO(Last In First Out) principle.
Append
Dictionaries are written with curly brackets, and have keys and values.
The update() method will update the dictionary with the items from the given
argument.
The argument must be a dictionary, or an iterable object with key:value pairs.
Add dictionary items
Adding an item to the dictionary is done by using a new index key and assigning a value to it.
The update() method will update the dictionary with the items from a given argument. If the
item does not exist, the item will be added.
Syntax : Variable name.update({“Key name": “Value"})
Remove dictionary items The pop() method removes the item with the specified key name
Pop Syntax : variable name.pop(“Key name”)
Variable name.clear( )
Print all key names in the dictionary, one by one. Syntax : for i in variable name
print(i)
Cannot copy a dictionary simply by typing dict2 = dict1, dict2 will only be a reference to dict1, and changes made in dict1 will
automatically also be made in dict2.
Dictionary Unpack
Unpack any number of dictionary and add their contents to another dictionary using **kwargs. In this way, we can add
multiple length arguments to one dictionary in a single statement.
Syntax : New Variable name = {**Variable name1, **Variable name2, **Variable name3,…………}
Functions
Functions are used whenever we need to perform the same task multiple times without writing the same code again.
Types of Functions
Syntax
Note: While defining a function, we use two keywords, def (mandatory) and return (optional).
Q1 Creating a function without a parameter.
Calling a function
Once a function is defined or finalized structure, call the function by using its name. We can also call that
function from another function or program by importing it.
To call a function, use the name of the function with the parenthesis, and if the function accepts
parameters, then pass those parameters in the parenthesis.
Docstrings
In Python, the documentation string is also called a docstring. It is a descriptive text (like a comment)
written by a programmer to let others know what block of code does.
We write docstring in source code and define it immediately after module, class, function, or method
definition.
Difference between Docstring and Comment
Comment Docstring
Visibility in the code Comments are not visible while executing Doc string of certain method, class, function
the code, they are always ignored. can be viewed with the help of __doc__.
Eg. Print(len.__doc__)
print(max.__doc__)
Usage Comments are useful for explaining the Docstrings are only used to describe the
working of a code and can be used for functions and classes, show that what
excluding a bit of code without having the parameters they accept and what they return.
need to remove it.
Syntax Comments are preceded by a # for a single Docstrings in python are contained by the ‘’’ or
line and “ ”, ‘ ‘, for a multiline. “”” i.e the triple quotation symbol and should be
inside a function, package or module.
Return Value From a Function
In Python, to return value from the function, a return statement is used. It returns the value of the expression following the return keyword.
Syntax of return statement
When a function is defined with variable, then those variables’ scope is limited to that function.
In Python, the scope of a variable is an area where a variable is declared. It is called the variable’s local
scope.
We cannot access the local variables from outside of the function. Because the scope is local, those
variables are not visible from the outside of the function.
Note: The inner function does have access to the outer function’s local scope.
When we are executing a function, the life of the variables is up to running time. Once we return from the
function, those variables get destroyed. (Code 8)
Local Variable in function
A local variable is a variable declared inside the function that is not accessible from outside of the function. The
scope of the local variable is limited to that function only where it is declared. If we try to access the local
variable from the outside of the function, will get the error as NameError. (Code 8)
In Python, global is the keyword used to access the actual global variable from outside the function. we use the
global keyword for two purposes:
To declare a global variable inside the function.
Declaring a variable as global, which makes it available to function to perform the modification.
Nonlocal Variable in Function
In Python, nonlocal is the keyword used to declare a variable that acts as a global variable for a nested
function (i.e., function within another function).
We can use a nonlocal keyword when we want to declare a variable in the local scope but act as a global
scope.
Python Function Arguments
The argument is a value, a variable, or an object that we pass to a function or method call. In Python,
there are four types of arguments allowed.
1.Positional arguments
2.keyword arguments
3.Default arguments
4.Variable-length arguments *arg
5. Arbitrary keyword arguments **kwarg
Positional Arguments
Positional arguments are arguments that are pass to function in proper positional order. That is, the 1st
positional argument needs to be 1st when the function is called. The 2nd positional argument needs to be
2nd when the function is called, etc.
In the positional argument number and position of arguments must be matched. If we change the order,
then the result may change. Also, If we change the number of arguments, then we will get an error.
Keyword Arguments
A keyword argument is an argument value, passed to function preceded by the variable name and an equals
sign.
In keyword arguments order of argument is not matter, but the number of arguments must match. Otherwise,
we will get an error.
While using keyword and positional argument simultaneously, we need to pass 1st arguments as positional
arguments and then keyword arguments. Otherwise, will get SyntaxError.
Default Arguments
Default arguments take the default value during the function call if we do not pass them. We can assign a
default value to an argument in function definition using the = assignment operator.
Variable-length Arguments * arg
In Python, sometimes, there is a situation where we need to pass multiple numbers of arguments to the function.
Such types of arguments are called variable-length arguments. We can declare a variable-length argument
with the * (asterisk) symbol.
Syntax def fun(*var):
function body
Arbitrary keyword arguments **kwarg – To pass multiple keyword arguments use **kwargs
Syntax def fun(**var):
function body
Recursive Function
A recursive function is a function that calls itself, again and again.
The advantages of the recursive function are:
1.By using recursive, we can reduce the length of the code.
2.The readability of code improves due to code reduction.
3.Useful for solving a complex problem
The disadvantage of the recursive function:
1.The recursive function takes more memory and time for execution.
2.Debugging is not easy for the recursive function.
Python Anonymous/Lambda Function
Sometimes we need to declare a function without any name. The nameless property function is called
an anonymous function or lambda function.
The reason behind using anonymous function is for instant use, that is, one-time usage. Normal function is
declared using the def function. Whereas the anonymous function is declared using the lambda keyword.
In opposite to a normal function, a Python lambda function is a single expression. But, in a lambda body, we
can expand with expressions over multiple lines using parentheses or a multiline string.
ex : lambda n:n+n
Syntax of lambda function:
lambda: argument_list:expression
When we define a function using the lambda keyword, the code is very concise so that there is more
readability in the code. A lambda function can have any number of arguments but return only one value after
expression evaluation.
It is not required to write explicitly return statements in the lambda function because the lambda internally
returns expression value.
Lambda functions are more useful when we pass a function as an argument to another function. We can also
use the lambda function with built-in functions such as filter, map, reduce because this function requires
another function as an argument
filter() function in Python
In Python, the filter() function is used to return the filtered value. We use this function to filter values based on
some conditions.
Syntax of filter() function:
filter(function, sequence)
In Python, large code is divided into small modules. The benefit of modules is, it provides a way to share reusable functions.
Built-in modules come with default Python installation. One of The modules which the user defines or create are called a
Python’s most significant advantages is its rich library support user-defined module. We can create our own module,
that contains lots of built-in modules. Hence, it provides a lot of which contains classes, functions, variables, etc.,
reusable code. as per our requirements.
Some commonly used Python built-in modules
are datetime, os, math, sys, random, etc.
How to import modules?
In Python, the ”import” statement is used to import the whole module. Also, we can import specific classes and functions
from a module. With the help of the import keyword, both the built-in and user-defined modules are imported.
Syntax import module name
When the interpreter finds an import statement, it imports the module presented in a search path. The module is loaded only
once, even we import multiple times. Using import keyword multiple modules can be imported.
randint(x , y) returns a number x<=n<=y where n is an integer value and x, y are user defined limits.
In Python, to create a module, write Python code in the file, and save that file with the .py extension.
Variables in Module
In Python, the module contains Python code like classes, functions, methods, but it also has variables. A variable
can list, tuple, dict, etc.
Reloading a module
In Python, when we import a module in the program using the import statement, the module is loaded. By default, the
module loaded only once, even if we import it multiple times. Sometimes we update the loaded module with new
changes, then an updated version of the module is not available to the program. In such case, use the reload() function
to reload a module again.
The main difference between a module and a function is that a module is a collection of functions
that are imported in multiple programs and can do various tasks. A function is a small block of code
and separates itself from the entire code and have a fixed functionality.
sys.path
sys.path is a built-in variable within the sys module. It contains a list of directories that the interpreter will
search in for the required module.
When a module(a module is a python file) is imported within a Python file, the interpreter first searches for
the specified module among its built-in modules. If not found it looks through the list of directories(a
directory is a folder that contains related modules) defined by sys.path.
dir() Function
There is a built-in function to list all the function names (or variable names) in a module.
dir() is a built-in function. This function is used to list all members of the current module. When we use this function
with any object (an object can be sequence like list, tuple, set, dict or can be class, function, module, etc. ), it returns
properties, attributes, and method.
For Class Objects, it returns a list of names of all the valid attributes and base attributes.
In Python, a decorator is a design pattern that allows to modify the functionality of a function by wrapping it in
another function.
The outer function is called the decorator, which takes the original function as an argument and returns a
modified version of it.
@ syntactic sugar is syntax within a programming language that is designed to make things easier
to read or to express.
Iterable and Iterators
Map in Python is a function that works as an iterator to return a result after applying a function to every
item of an iterable (tuple, list etc.). It is used when you want to apply a single transformation function to all the
iterable elements. The iterable and function are passed as arguments to the map in Python.
Python Generators
In Python, a generator is a function that returns an iterator that produces a sequence of values when iterated over.
.
Generators are useful when we want to produce a large sequence of values, but we don't want to store all of them in
memory at once.
Encapsulation in Python describes the concept of bundling data and methods within a single unit. When a class is
created, it means encapsulation is implemented. A class is an example of encapsulation as it binds all the data members
(instance variables) and methods into a single unit.
Using encapsulation, hide an object’s internal representation from the outside. This is called information hiding.
Also, encapsulation allows restrict accessing variables and methods directly and prevent data modification by creating
private data members and methods within a class.
Encapsulation is a way to restrict access to methods and variables from outside of class. Whenever working with the
class and dealing with sensitive data, providing access to all variables used within the class is not a good choice.
To implement proper encapsulation in Python, we need to use setters and getters. The primary purpose of
using getters and setters in object-oriented programs is to ensure data encapsulation. Use the getter
method to access data members and the setter methods to modify the data members.
In Python, private variables are not hidden fields like in other programming languages. The getters and
setters methods are often used when:
• When we want to avoid direct access to private variables.
Polymorphism
Polymorphism in Python is the ability of an object to take many forms. In simple words, polymorphism allows us
to perform the same action in many different ways.
XYZ
Employee
Sports Player
Student
The process of inheriting the properties of the parent class into a child class is called inheritance. The existing
class is called a base class or parent class and the new class is called a subclass or child class or derived class.
The main purpose of inheritance is the reusability of code because we can use the existing class to create a new class
instead of creating it from scratch.
In inheritance, the child class acquires all the data members, properties, and functions from the parent class. Also, a
child class can also provide its specific implementation to the methods of the parent class.
Car is a sub-class of a Vehicle class. We can create a Car by inheriting the properties of a Vehicle such as Wheels,
Colors, Fuel tank, engine, and add extra properties in Car as required.
Types Of Inheritance
In Python, based upon the number of child and parent classes involved, there are five types of inheritance.
1. Single inheritance
2. Multiple Inheritance
3. Multilevel inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance
Single Inheritance
In single inheritance, a child class inherits from a single-parent class. Here is one child class and one parent
class.
Multiple Inheritance
In multiple inheritance, one child class can inherit from multiple parent classes. So here is one child class and
multiple parent classes.
Multilevel inheritance
In multilevel inheritance, a class inherits from a child class or derived class. Suppose three classes A, B, C. A
is the superclass, B is the child class of A, C is the child class of B. In other words, we can say a chain of
classes is called multilevel inheritance.
Hierarchical Inheritance
In Hierarchical inheritance, more than one child class is derived from a single parent class. In other words, we
can say one parent class and multiple child classes.
Hybrid Inheritance
When inheritance is consists of multiple types or a combination of different inheritance is called hybrid
inheritance.
Note: In the above example, hierarchical and multiple inheritance exists. Here we created, parent class Vehicle and two
child classes named Car and Truck this is hierarchical inheritance.
Another is Sports Car inherit from two parent classes named Car and Vehicle. This is multiple inheritance.
Python super() function
When a class inherits all properties and behavior from the parent class is called inheritance. In such a case, the inherited
class is a subclass and the latter class is the parent class.
In child class, we can refer to parent class by using the super() function. The super function returns a temporary object of
the parent class that allows us to call a parent class method inside a child class method.
issubclass()
In Python, we can verify whether a particular class is a subclass of another class. For this purpose, we can use Python
built-in function issubclass(). This function returns True if the given class is the subclass of the specified class. Otherwise, it
returns False.
Syntax - issubclass(class, classinfo)
Where,
o class: class to be checked.
o classinfo: a class, type, or a tuple of classes or data types.
Method Overriding
In inheritance, all members available in the parent class are by default available in the child class. If the child
class does not satisfy with parent class implementation, then the child class is allowed to redefine that method
by extending additional functions in the child class. This concept is called method overriding.
When a child class method has the same name, same parameters, and same return type as a method in its
superclass, then the method in the child is said to override the method in the parent class.
Read Only (‘r’)
Read and Write (‘r+’)
Write Only (‘w’)
Write and Read (‘w+’)
Append Only (‘a’)
Append and Read (‘a+’)
n is an integer
Paths in file handling :
1) Relative path - Interpreted from the current working directory. Eg : fh = open('File 2.txt','r')
2) Absolute path - Accesses the given file using the path starting from the root of the file
system.
--------------------------------------------------------------------------------------------------------------------
To check whether the file existed in the current directory using relative path........ Use code
File handling 3_6
3) Use the os.listdir(directory_path) function to list all files from a folder before and after
creating a file.
4) Use the os.path.isfile(file_path) function to verify if a newly created file exists in a directory.
Q Why closing a file is important in file handling ?
Closing a file after use is important because it frees up system resources that are being used by the file.
When a file is open, the operating system allocates memory and other resources to the file,
which can potentially impact the performance of the system if too many files are open at the same time.
Note : Using the “with” statement a file is closed automatically it ensures that all the resources that are tied up with the file are
released.
-----------------------------------------------------------------------------------------------------------------------------
To create a text file with the current date as its name.
Use the datetime module to get the current date and time and assign it to the file name to create a file with the date and time in
its name.
Python provides a datetime module that has several classes to access and manipulate the date and timestamp value.
1) The seek() method is used to move the file cursor ahead or backward from the current position.
3) To move the file pointer backward from the end of the file.
The seek() function sets the position of a file pointer and the tell() function returns the current position of a
file pointer.
A file handle or pointer denotes the position from which the file contents will be read or written. File handle is also called as file pointer or cursor.
When a file is opened in write mode, the file pointer is placed at the 0th position, i.e., at the start of the file. However, it changes (increments) its
position as we start writing content into it.
Or, while reading a file line by line, the file pointer move one line at a time.
Sometimes it is required to read only a specific portion of the file, in such cases use the seek() method to move the file pointer to that position.
For example, use the seek() function to do the file operations like: –
2) Directly jump to the 5th character from the end of the file.
How many points the pointer will move is computed from adding offset to a reference point.
3) A whence value of 2 uses the end of the file as the reference point.
Rename file in Python
To rename a file
To rename a file, we need its path. The path is the location of the file on the disk.
---> An absolute path contains the complete directory list required to locate the file.
---> A relative path contains the current directory and then the file name.
Pass both the old and new names to the os.rename(old_name, new_name) function to rename a file.
os.rename()
We can rename a file in Python using the rename() method available in the os module. The os module
provides functionalities for interacting with the operating systems. This module comes under Python’s
standard utility modules.
Use the isfile(‘path’) function before renaming a file. It returns true if the destination file name already exists.
Python provides strong support for file handling. We can delete files using different methods and the most commonly used
one is the os.remove() method. Below are the steps to delete a file.
1.Find the path of a file
We can delete a file using both relative path and absolute path. The path is the location of the file on the disk.
An absolute path contains the complete directory list required to locate the file. And a relative path includes the current
directory and then the file name.
2. Use os.remove() function to delete File
The OS module in Python provides methods to interact with the Operating System in Python. The remove() method in this
module is used to remove/delete a file path.
First, import the os module and Pass a file path to the os.remove('file_path') function to delete a file from a disk
3.Use the rmtree() function of shutil module to delete a directory
Import the shutil module and pass the directory path to shutil.rmtree('path') function to delete a directory and all files
contained in it.
Delete all Files from a Directory
To delete all files from a directory without deleting a directory. Follow the below steps to delete all files from
a directory.
Get the list of files in a folder using os.listdir(path) function. It returns a list containing the names of the files
and folders in the given directory.
Iterate over the list using a for loop to access each file one by one
Delete each file using the os.remove()
While it is always the case that a directory has some files, sometimes there are empty folders or directories that no longer
needed. We can delete them using the rmdir() method available in both the os module and the pathlib module.
Using os.rmdir() method
In order to delete empty folders, use the rmdir() function from the os module.
Use pathlib.Path.rmdir()
The rmdir() method in the pathlib module is also used to remove or delete an empty directory.
First set the path for the directory
Next, call the rmdir() method on that path
One such module is Shutil, which stands for "shell utilities," providing a comprehensive set of functions for
file and directory operations. Whether you need to copy, move, rename, or delete files and directories, the
Shutil module in Python comes to the rescue with its user−friendly and efficient functionalities.
The Shutil module allows you to do high-level operations on a file, such as copy, create, and remote
operations. It falls within the umbrella of Python's basic utility modules. This module aids in the automation
of the copying and deleting of files and folders.
Multithread
A core is a physical component of the CPU that can execute instructions, while a thread is a virtual
sequence of instructions that can be executed by a core.
Cores can be visualized as the workers, while threads are the tasks they perform.
Working:
The thread is created by a process. Every time when an
application is open, it itself creates a thread which will handle all
the tasks of that specific application. Like-wise the more
application is open more threads will be created.
The threads are always created by the operating system for
performing a task of a specific application.
There is single thread (code of that core which performs the
computations also known as primary thread) on the core which
when gets the information from the user, creates another thread
and allocates the task to it. Similarly, if it gets another instruction
it forms second thread and allocates the task to it. Making a total
of two threads.
Example:
The smartphone application is an example of this, when you open a app it shows a circle which spins
continuously, this process is done by a thread created for this purpose only, and the second thread loads
the information and presents it in the Graphical User Interface.
The only fact that will limit the creation of the threads will be the number of the threads provided by the
physical CPU, and it varies from CPU to CPU. The 1st image is the loading spinner by the first thread and
the second one is the GUI loading by the second thread.
What is MySQL?
MySQL is an open-source relational database management system offered by Oracle. Structured query
language (SQL) is a standard language for database creation and manipulation. MySQL is a relational
database program that uses SQL queries.
A table is an organized set of data that is arranged into rows and columns in a Database Management System
(DBMS), while a database is a collection of related tables.
How to install MySQL
MySQL
Downloads
MySQL Community GPL Downloads
Environment variable In the window, type Environment Go to bin folder, copy the path
variable
Double click on the path, select new, paste the bin path Open cmd, mysql – version (to check the version)
To connect mysql with database, type mysql –u root –p, and enter the password created during
installation, show databases;
MySQL Driver
MySQL driver creates connection between Python and MySQL.
3) MySQL driver installation Before installing MySQL driver, check the available drivers using pip list.
4) Go to PyCharm, create a new file MySQL.py, under MySQL.py create a new python file driver.py.
5) Connect Python and MySQL by using the command “pip install mysql-connector-python”. Before
pressing enter check for internet connectivity. Check the installed driver by typing pip list.
• Creating the object of the driver i.e mydb = myConn.connect(host, user, password, database are the parameters)
• connect() method. Connects to a MySQL server. connect() supports the following arguments: host , user ,
password , database , port , unix_socket , client_flags , ssl_ca , ssl_cert , ssl_key , ssl_verify_cert , compress .
• mysql.connector, myConn.connect A driver, or device driver, is a set of files that tells a piece
of hardware how to function by communicating with a
Package Method computer's operating system.
Class
Creating Database
Creating Database
MySQL Python
• Any changes in the database through front end can be done using any of the languages like Python
or Java, direct changes in the database through front end cannot be done.
• Cursor () method is available in connector object and execute() method is available in cursor object
• To check the created database, type mysql –u root –p, and enter the password created during installation,
show databases;
Data Manipulation Language Transaction Control Language
• To check the table select query is used in cmd prompt. Syntax – select * from database name.table name;
To insert multiple values
IPv4 network standards reserve the entire address block 127.0.0.0/8 (more than 16 million addresses) for
loopback purposes. That means any packet sent to any of those addresses is looped back. The
address 127.0.0.1 is the standard address for IPv4 loopback traffic; the rest are not supported by all
operating systems.
Exceptions and Error Handling
• Run time error will not give syntax or logical errors, these are the errors generated
by the users while using the software.
Errors and exceptions come into play when the user enters
a wrong input but still the software should work by giving the
error/exception message.