0% found this document useful (0 votes)
39 views37 pages

Unit 4

The document discusses Python functions. It explains what functions are, the different types of functions in Python including built-in and user-defined functions. It covers creating functions, calling functions, functions with parameters, function arguments, and other topics like nested functions and file handling.

Uploaded by

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

Unit 4

The document discusses Python functions. It explains what functions are, the different types of functions in Python including built-in and user-defined functions. It covers creating functions, calling functions, functions with parameters, function arguments, and other topics like nested functions and file handling.

Uploaded by

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

Python Functions

Python Functions is a block of statements that return the specific task.


The idea is to put some commonly or repeatedly done tasks together and make a function so
that instead of writing the same code again and again for different inputs, we can do the
function calls to reuse code contained in it over and over again. Some Benefits of Using
Functions
 Increase Code Readability 
 Increase Code Reusable

Python Function Declaration


The syntax to declare a function is:

Types of Functions in Python

There are mainly two types of functions in Python.


 Built-in library function: These are Standard functions in Python that are
available to use.
 User-defined function: We can create our own functions based on our
requirements.

Creating a function in Python


We can create a Python function using the def keyword.

# A simple Python function 


  
def fun():
  print("Welcome to GFG")
Calling a  Python Function

After creating a function we can call it by using the name of the function followed by
parenthesis containing parameters of that particular function.

# A simple Python function


def fun():
    print("Welcome to GFG")
  
# Driver code to call a function
fun()

Output:
Welcome to GFG

Python Function with parameters

If you have experience in C/C++ or Java then you must be thinking about the return type of
the function and data type of arguments. That is possible in Python as well (specifically for
Python 3.5 and above).
Defining and calling a function with parameters
def function_name(parameter: data_type) -> return_type:
"""Docstring"""
# body of the function
return expression
The following example uses arguments and parameters that you will learn later in this article
so you can come back to it again if not understood.

def add(num1: int, num2: int) -> int:


    """Add two numbers"""
    num3 = num1 + num2
  
    return num3
  
# Driver code
num1, num2 = 5, 15
ans = add(num1, num2)
print(f"The addition of {num1} and {num2} results {ans}.")

Output:
The addition of 5 and 15 results 20.
Note: The following examples are defined using syntax 1, try to convert them in syntax 2 for
practice.

# some more functions


def is_prime(n):
    if n in [2, 3]:
        return True
    if (n == 1) or (n % 2 == 0):
        return False
    r = 3
    while r * r <= n:
        if n % r == 0:
            return False
        r += 2
    return True
print(is_prime(78), is_prime(79))

Output:
False True

Python Function Arguments

Arguments are the values passed inside the parenthesis of the function. A function can have
any number of arguments separated by a comma.
In this example, we will create a simple function to check whether the number passed as an
argument to the function is even or odd.

# A simple Python function to check


# whether x is even or odd
def evenOdd(x):
    if (x % 2 == 0):
        print("even")
    else:
        print("odd")
# Driver code to call the function
evenOdd(2)
evenOdd(3)

Output:
even
odd

Types of Python Function Arguments


Python supports various types of arguments that can be passed at the time of the function call.
In Python, we have the following 4 types of function arguments.
 Default argument
 Keyword arguments (named arguments)
 Positional arguments
 Arbitrary arguments (variable-length arguments *args and **kwargs)
Let’s discuss each type in detail. 

Default Arguments
A default argument is a parameter that assumes a default value if a value is not provided in
the function call for that argument. The following example illustrates Default arguments. 

# Python program to demonstrate


# default arguments
def myFun(x, y=50):
    print("x: ", x)
    print("y: ", y)
  
# Driver code (We call myFun() with only
# argument)
myFun(10)

Output
x: 10
y: 50
Like C++ default arguments, any number of arguments in a function can have a default value.
But once we have a default argument, all the arguments to its right must also have default
values.

Keyword Arguments
The idea is to allow the caller to specify the argument name with values so that the caller
does not need to remember the order of parameters.

# Python program to demonstrate Keyword Arguments


def student(firstname, lastname):
    print(firstname, lastname)
  
  
# Keyword arguments
student(firstname='Geeks', lastname='Practice')
student(lastname='Practice', firstname='Geeks')

Output
Geeks Practice
Geeks Practice

Positional Arguments

We used the Position argument during the function call so that the first argument (or value) is
assigned to name and the second argument (or value) is assigned to age. By changing the
position, or if you forget the order of the positions, the values can be used in the wrong
places, as shown in the Case-2 example below, where 27 is assigned to the name and Suraj is
assigned to the age.

def nameAge(name, age):


    print("Hi, I am", name)
    print("My age is ", age)
  
  
# You will get correct output because 
# argument is given in order
print("Case-1:")
nameAge("Suraj", 27)
# You will get incorrect output because
# argument is not in order
print("\nCase-2:")
nameAge(27, "Suraj")

Output:
Case-1:
Hi, I am Suraj
My age is 27
Case-2:
Hi, I am 27
My age is Suraj

Arbitrary Keyword  Arguments

In Python Arbitrary Keyword Arguments, *args, and **kwargs can pass a variable number of


arguments to a function using special symbols. There are two special symbols:
 *args in Python (Non-Keyword Arguments)
 **kwargs in Python (Keyword Arguments)

example 1: Variable length non-keywords argument

# Python program to illustrate


# *args for variable number of arguments
def myFun(*argv):
    for arg in argv:
        print(arg)
  
  
myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')

Output
Hello
Welcome
to
GeeksforGeeks
Example 2: Variable length keyword arguments

# Python program to illustrate


# *kwargs for variable number of keyword arguments
  
  
def myFun(**kwargs):
    for key, value in kwargs.items():
        print("%s == %s" % (key, value))
  
  
# Driver code
myFun(first='Geeks', mid='for', last='Geeks')

Output
first == Geeks
mid == for
last == Geeks

Python Function within Functions


A function that is defined inside another function is known as the inner function or nested
function. Nested functions are able to access variables of the enclosing scope. Inner functions
are used so that they can be protected from everything happening outside the function.

# Python program to
# demonstrate accessing of
# variables of nested functions
  
def f1():
    s = 'I love GeeksforGeeks'
      
    def f2():
        print(s)
          
    f2()
  
# Driver's code
f1()

Output
I love GeeksforGeeks

Anonymous functions in Python Function


In Python, an anonymous function means that a function is without a name. As we already
know the def keyword is used to define the normal functions and the lambda keyword is used
to create anonymous functions.

# Python code to illustrate the cube of a number


# using lambda function
def cube(x): return x*x*x
  
cube_v2 = lambda x : x*x*x
  
print(cube(7))
print(cube_v2(7))

Output
343
343

Return statement in Python function


The function return statement is used to exit from a function and go back to the function
caller and return the specified value or data item to the caller. The syntax for the return
statement is:
return [expression_list]
The return statement can consist of a variable, an expression, or a constant which is returned
at the end of the function execution. If none of the above is present with the return statement
a None object is returned
Example: Python Function Return Statement

def square_value(num):
    """This function returns the square
    value of the entered number"""
    return num**2
  
  
print(square_value(2))
print(square_value(-4))

Output
4
16
Python File Handling

Sometimes, it is not enough to only display the data on the console. The data to be displayed
may be very large, and only a limited amount of data can be displayed on the console since
the memory is volatile, it is impossible to recover the programmatically generated data again
and again.
The file handling plays an important role when the data needs to be stored permanently into
the file. A file is a named location on disk to store related information. We can access the
stored information (non-volatile) after the program termination.

The file-handling implementation is slightly lengthy or complicated in the other


programming language, but it is easier and shorter in Python.

In Python, files are treated in two modes as text or binary. The file may be in the text or
binary format, and each line of a file is ended with the special character.

Hence, a file operation can be done in the following order.

o Open a file
o Read or write - Performing operation
o Close the file

Opening a file

Python provides an open() function that accepts two arguments, file name and access mode
in which the file is accessed. The function returns a file object which can be used to perform
various operations like reading, writing, etc.

Syntax:

file object = open(<file-name>, <access-mode>, <buffering>)     

The files can be accessed using various modes like read, write, or append. The following are
the details about the access mode to open a file.

S Access Description
N mode

1 r It opens the file to read-only mode. The file pointer exists at the
beginning. The file is by default open in this mode if no access mode is
passed.

2 rb It opens the file to read-only in binary format. The file pointer exists at
the beginning of the file.

3 r+ It opens the file to read and write both. The file pointer exists at the
beginning of the file.

4 rb+ It opens the file to read and write both in binary format. The file pointer
exists at the beginning of the file.

5 w It opens the file to write only. It overwrites the file if previously exists
or creates a new one if no file exists with the same name. The file
pointer exists at the beginning of the file.

6 wb It opens the file to write only in binary format. It overwrites the file if it
exists previously or creates a new one if no file exists. The file pointer
exists at the beginning of the file.

7 w+ It opens the file to write and read both. It is different from r+ in the
sense that it overwrites the previous file if one exists whereas r+ doesn't
overwrite the previously written file. It creates a new file if no file
exists. The file pointer exists at the beginning of the file.

8 wb+ It opens the file to write and read both in binary format. The file pointer
exists at the beginning of the file.

9 a It opens the file in the append mode. The file pointer exists at the end of
the previously written file if exists any. It creates a new file if no file
exists with the same name.

10 ab It opens the file in the append mode in binary format. The pointer exists
at the end of the previously written file. It creates a new file in binary
format if no file exists with the same name.

11 a+ It opens a file to append and read both. The file pointer remains at the
end of the file if a file exists. It creates a new file if no file exists with
the same name.

12 ab+ It opens a file to append and read both in binary format. The file pointer
remains at the end of the file.

Let's look at the simple example to open a file named "file.txt" (stored in the same directory)
in read mode and printing its content on the console.

Example

#opens the file file.txt in read mode    
fileptr = open("file.txt","r")       
if fileptr:    
    print("file is opened successfully")    

Output:

<class '_io.TextIOWrapper'>
file is opened successfully

In the above code, we have passed filename as a first argument and opened file in read mode
as we mentioned r as the second argument. The fileptr holds the file object and if the file is
opened successfully, it will execute the print statement
The close() method

Once all the operations are done on the file, we must close it through our Python script using
the close() method. Any unwritten information gets destroyed once the close() method is
called on a file object.

We can perform any operation on the file externally using the file system which is the
currently opened in Python; hence it is good practice to close the file once all the operations
are done.

The syntax to use the close() method is given below.

Syntax

fileobject.close()   

Consider the following example.

# opens the file file.txt in read mode    
fileptr = open("file.txt","r")    
if fileptr:    
print("file is opened successfully")    
#closes the opened file    
fileptr.close()  

After closing the file, we cannot perform any operation in the file. The file needs to be
properly closed. If any exception occurs while performing some operations in the file then the
program terminates without closing the file.

We should use the following method to overcome such type of problem.

try:  
   fileptr = open("file.txt")  
   # perform file operations  
finally:  
   fileptr.close()  

The with statement

The with statement was introduced in python 2.5. The with statement is useful in the case of
manipulating the files. It is used in the scenario where a pair of statements is to be executed
with a block of code in between.

The syntax to open a file using with the statement is given below.
1. with open(<file name>, <access mode>) as <file-pointer>:    
2.     #statement suite     

The advantage of using with statement is that it provides the guarantee to close the file
regardless of how the nested block exits.

It is always suggestible to use the with statement in the case of files because, if the break,
return, or exception occurs in the nested block of code then it automatically closes the file, we
don't need to write the close() function. It doesn't let the file to corrupt.

Consider the following example.

Example

with open("file.txt",'r') as f:    
content = f.read();    
print(content)    

Writing the file

To write some text to a file, we need to open the file using the open method with one of the
following access modes.

w: It will overwrite the file if any file exists. The file pointer is at the beginning of the file.

a: It will append the existing file. The file pointer is at the end of the file. It creates a new file
if no file exists.

Consider the following example.

Example

# open the file.txt in append mode. Create a new file if no such file exists.  
fileptr = open("file2.txt", "w")  
# appending the content to the file  
fileptr.write('''''Python is the modern day language. It makes things so simple. 
It is the fastest-growing programing language''')  

# closing the opened the file  
fileptr.close()  

Output:

File2.txt
Python is the modern-day language. It makes things so simple. It is the fastest growing
programming language.

Snapshot of the file2.txt

We have opened the file in w mode. The file1.txt file doesn't exist, it created a new file and
we have written the content in the file using the write() function.

Example 2

#open the file.txt in write mode.    
fileptr = open("file2.txt","a")  
#overwriting the content of the file    
fileptr.write(" Python has an easy syntax and user-friendly interaction."
#closing the opened file     
fileptr.close()  

Output:

Python is the modern day language. It makes things so simple.


It is the fastest growing programing language Python has an easy syntax and user-friendly
interaction.

Snapshot of the file2.txt

We can see that the content of the file is modified. We have opened the file in a mode and it
appended the content in the existing file2.txt.

To read a file using the Python script, the Python provides the read() method.
The read() method reads a string from the file. It can read the data in the text as well as a
binary format.
The syntax of the read() method is given below.

Syntax:

fileobj.read(<count>)    

Here, the count is the number of bytes to be read from the file starting from the beginning of
the file. If the count is not specified, then it may read the content of the file until the end.

Consider the following example.

Example

#open the file.txt in read mode. causes error if no such file exists.    
fileptr = open("file2.txt","r")  
#stores all the data of the file into the variable content    
content = fileptr.read(10)   
# prints the type of the data stored in the file    
print(type(content))      
#prints the content of the file    
print(content)       
#closes the opened file    
fileptr.close()    

Output:

<class 'str'>
Python is

In the above code, we have read the content of file2.txt by using the read() function. We
have passed count value as ten which means it will read the first ten characters from the file.

If we use the following line, then it will print all content of the file.

1. content = fileptr.read()  
2. print(content)   

Output:

Python is the modern-day language. It makes things so simple.


It is the fastest-growing programing language Python has easy an syntax and user-friendly
interaction.
Read file through for loop

We can read the file using for loop. Consider the following example.

#open the file.txt in read mode. causes an error if no such file exists.    
fileptr = open("file2.txt","r");     
#running a for loop     
for i in fileptr:    
    print(i) # i contains each line of the file     

Output:

Python is the modern day language.

It makes things so simple.

Python has easy syntax and user-friendly interaction.

Read Lines of the file

Python facilitates to read the file line by line by using a function readline() method.


The readline() method reads the lines of the file from the beginning, i.e., if we use the
readline() method two times, then we can get the first two lines of the file.

Consider the following example which contains a function readline() that reads the first line
of our file "file2.txt" containing three lines. Consider the following example.

Example 1: Reading lines using readline() function

#open the file.txt in read mode. causes error if no such file exists.    
fileptr = open("file2.txt","r");     
#stores all the data of the file into the variable content    
content = fileptr.readline()     
content1 = fileptr.readline()  
#prints the content of the file    
print(content)     
print(content1)  
#closes the opened file    
fileptr.close()    
Output:

Python is the modern day language.

It makes things so simple.

We called the readline() function two times that's why it read two lines from the file.

Python provides also the readlines() method which is used for the reading lines. It returns the
list of the lines till the end of file(EOF) is reached.

Example 2: Reading Lines Using readlines() function

#open the file.txt in read mode. causes error if no such file exists.    
fileptr = open("file2.txt","r");     
    
#stores all the data of the file into the variable content    
content = fileptr.readlines()     
  
#prints the content of the file    
print(content)     
    
#closes the opened file    
fileptr.close()    

Output:

['Python is the modern day language.\n', 'It makes things so simple.\n', 'Python has easy
syntax and user-friendly interaction.']

Creating a new file

The new file can be created by using one of the following access

modes with the function open().

x: it creates a new file with the specified name. It causes an error a file exists with the same
name.

a: It creates a new file with the specified name if no such file exists. It appends the content to
the file if the file already exists with the specified name.
w: It creates a new file with the specified name if no such file exists. It overwrites the
existing file.

Consider the following example.

Example 1

#open the file.txt in read mode. causes error if no such file exists.    
fileptr = open("file2.txt","x")   
print(fileptr)    
if fileptr:    
    print("File created successfully")  

Output:

<_io.TextIOWrapper name='file2.txt' mode='x' encoding='cp1252'>


File created successfully

File Pointer positions

Python provides the tell() method which is used to print the byte number at which the file
pointer currently exists. Consider the following example.

# open the file file2.txt in read mode    
fileptr = open("file2.txt","r")    
#initially the filepointer is at 0     
print("The filepointer is at byte :",fileptr.tell())   
#reading the content of the file    
content = fileptr.read();    
    
#after the read operation file pointer modifies. tell() returns the location of the fileptr.
print("After reading, the filepointer is at:",fileptr.tell())    

Output:

The filepointer is at byte : 0


After reading, the filepointer is at: 117

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.

For example, when you open a file 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 you started writing
content into it.

Or, when you read a file line by line, the file pointer moves one line at a time.

Sometimes we may have to read only a specific portion of the file, in such cases use
the seek() method to move the file pointer to that position.

File handle is like a cursor, which defines from where the data has to be read or written in
the file. Sometimes it becomes important for us to know the position of the File Handle.
tell() method can be used to get the position of File Handle. tell() method returns current
position of file object. This method takes no parameters and returns an integer value.
Initially file pointer points to the beginning of the file(if not opened in append mode). So,
the initial value of tell() is zero.

Python seek() function

The concept of file handling is used to preserve the data or information generated after
running the program. Like other programming languages like C, C++, Java, Python also
support file handling.
 
 
 
 
seek() method
In Python, seek() function is used to change the position of the File Handle to a given
specific position. File handle is like a cursor, which defines from where the data has to be
read or written in the file. 
 
Syntax:
  f.seek(offset, from_what)

where f is file pointer


Parameters: 
Offset:  Number of positions to move forward 
from_what:  It defines point of reference.

The reference point is selected by the from_what argument. It accepts three values: 


 
 0: sets the reference point at the beginning of the file 
 
 1: sets the reference point at the current file position 
 
 2: sets the reference point at the end of the file 
 
By default from_what argument is set to 0.
Note: Reference point at current position / end of file cannot be set in text mode except when
offset is equal to 0.
Example 1: Let’s suppose we have to read a file named “GfG.txt” which contains the
following text: 
 
"Code is like humor. When you have to explain it, it’s bad."
 

# Python program to demonstrate


# seek() method
# Opening "GfG.txt" text file
f = open("GfG.txt", "r")
 
# Second parameter is by default 0
# sets Reference point to twentieth
# index position from the beginning
f.seek(20)
# prints current position
print(f.tell())
print(f.readline())
f.close()

 
Example 2: Seek() function with negative offset only works when file is opened in binary
mode. Let’s suppose the binary file contains the following text.
 
b'Code is like humor. When you have to explain it, its bad.'
 

# Python code to demonstrate


# use of seek() function
# Opening "GfG.txt" text file
# in binary mode
f = open("data.txt", "rb")
# sets Reference point to tenth
# position to the left from end
f.seek(-10, 2)
# prints current position
print(f.tell())
# Converting binary to string and
# printing
print(f.readline().decode('utf-8'))
f.close()

Example 1: Position of File Handle before reading or writing to file. 


 

# Python program to demonstrate


# tell() method
  
  
# Open the file in read mode
fp = open("myfile.txt", "r")
  
# Print the position of handle
print(fp.tell())
  
#Closing file
fp.close()

output : 
 
0
# Example 2: Position of File Handle after reading data from file.
 

# Python program to demonstrate


# tell() method
  
# Opening file
fp = open("sample.txt", "r")
fp.read(8)
  
# Print the position of handle
print(fp.tell())
  
# Closing file
fp.close()

Output : 
 
8
# Example 3: For binary files. Let’s create a binary file and we will notice the position of
handle before writing and after writing to binary file.
 
# Python program to demonstrate
# tell() method
  
# for reading binary file we
# have to use "wb" in file mode.
fp = open("sample2.txt", "wb")
print(fp.tell())
  
# Writing to file
fp.write(b'1010101')
  
print(fp.tell())
  
# Closing file
fp.close()

Output : 
 
0
7

write() and writelines() function in Python

In Python, there are many functions for reading and writing files. Both reading and writing
functions work on open files (files opened and linked via a file object). In this section, we are
going to discuss the write functions to manipulate our data through files.

write() function

The write() function will write the content in the file without adding any extra characters.
Syntax: 
# Writes string content referenced by file object.
file_name.write(content)
As per the syntax, the string that is passed to the write() function is written into the opened
file. The string may include numbers, special characters, or symbols. While writing data to a
file, we must know that the write function does not add a newline character(\n) to the end of
the string. The write() function returns None.
Example: 
 Python3

file = open("Employees.txt", "w")


  

for i in range(3):

   name = input("Enter the name of the employee: ")

   file.write(name)

   file.write("\n")

     

file.close()

  

print("Data is written into the file.")

Output:
Data is written into the file.
Sample Run:
Enter the name of the employee: Aditya
Enter the name of the employee: Aditi
Enter the name of the employee: Anil

writelines() function

This function writes the content of a list to a file.


Syntax:   
# write all the strings present in the list "list_of_lines"
# referenced by file object.
file_name.writelines(list_of_lines)
As per the syntax, the list of strings that is passed to the writelines() function is written into
the opened file. Similar to the write() function, the writelines() function does not add a
newline character(\n) to the end of the string.
Example:

file1 = open("Employees.txt", "w")

lst = []

for i in range(3):
    name = input("Enter the name of the employee: ")

    lst.append(name + '\n')

      

file1.writelines(lst)

file1.close()

print("Data is written into the file.") 

Output:
Data is written into the file.
Sample Run:
Enter the name of the employee: Rhea
Enter the name of the employee: Rohan
Enter the name of the employee: Rahul
The only difference between the write() and writelines() is that write() is used to write a
string to an already opened file while writelines() method is used to write a list of strings in
an opened file.

Open a file using the with statement

The with  keyword in Python is used as a context manager. As in any programming language,


the usage of resources like file operations or database connections is very common. But these
resources are limited in supply. Therefore, the main problem lies in making sure to release
these resources after usage. If they are not released, then it will lead to resource leakage and
may cause the system to either slow down or crash.
As we know, the open() function is generally used for file handling in Python. But it is a
standard practice to use context managers like with keywords to handle files as it will
automatically release files once its usage is complete.

Python with open() Syntax:


Syntax: 
with open(file_path, mode, encoding) as file:
    …
file_path:  It is the path to the file to open
mode: mode of operation on the file. ex.: read, write etc. (represented by r, w, r+, w+, rb,
wb etc.)
encoding: read the file in correct encoding format.
Example 1: Simple Example Using The with Statement
We already have a file name geeksforgeeks.txt in our system, and it has the following data:
geeksforgeeks,txt

Now we will open the file and read the contents of the file using with open() statement:

with open("geeksforgeeks.txt","r") as gfg_file:


   file_content = gfg_file.read()
   print(file_content)

Output:
GeeksForGeeks is best for DSA
Note: Here we have used mode as “r” to read the data, because the target file has text data.
In case we are reading some binary file, we need to use “rb” as the mode.

Example 2: We can also use the with statement to append or write data to the file.
We will append the string “Hello geeks!” to our geeksforgeeks.txt file.

# appending string to file


with open("geeksforgeeks.txt","a") as gfg_file:
   gfg_file.write("\nHello Geeks!")
     
# reading the file contents
# to verify if successfully appended the data
with open("geeksforgeeks.txt","r") as gfg_file:
    content = gfg_file.read()
    print(content)

Connect Python with SQL Database

Python is a high-level, general-purpose, and very popular programming language. Basically,


it was designed with an emphasis on code readability, and programmers can express their
concepts in fewer lines of code. We can also use Python with SQL. In this article, we will
learn how to connect SQL with Python using the ‘MySQL Connector Python module. The
diagram given below illustrates how a connection request is sent to MySQL connector
Python, how it gets accepted from the database and how the cursor is executed with result
data.

SQL connection with PythoN

Database Connection

There are the following steps to connect a python application to our database.

1. Import mysql.connector module


2. Create the connection object.
3. Create the cursor object
4. Execute the query

Creating the connection

To create a connection between the MySQL database and the python application, the
connect() method of mysql.connector module is used.

Pass the database details like HostName, username, and the database password in the method
call. The method returns the connection object.

Creating a cursor object

The cursor object can be defined as an abstraction specified in the Python DB-API 2.0. It
facilitates us to have multiple separate working environments through the same connection to
the database. We can create the cursor object by calling the 'cursor' function of the connection
object. The cursor object is an important aspect of executing queries to the databases.

Connecting MySQL with Python


To create a connection between the MySQL database and Python, the connect() method
of mysql.connector module is used. We pass the database details like HostName, username,
and the password in the method call, and then the method returns the connection object.

The following steps are required to connect SQL with Python:


Step 1: Download and Install the free MySQL database. 
Step 2: After installing the MySQL database, open your Command prompt.
Step 3: Navigate your Command prompt to the location of PIP.
Step 4: Now run the commands given below to download and install “MySQL Connector”.
Here, mysql.connector statement will help you to communicate with the MySQL database.
Download and install “MySQL Connector”
pip install mysql-connector-python

Step 5: Test MySQL Connector


To check if the installation was successful, or if you already installed “MySQL Connector”,
go to your IDE and run the given below code :
import mysql.connector
If the above code gets executed with no errors, “MySQL Connector” is ready to be used.
Step 6: Create Connection
Now to connect SQL with Python, run the code given below in your IDE.

# Importing module
import mysql.connector
# Creating connection object
mydb = mysql.connector.connect(
    host = "localhost",
    user = "yourusername",
    password = "your_password"
)
# Printing the connection object
print(mydb)

Output:

Here, in the above code:


Code Info

Creating MySQL Database


To create a database, we will use CREATE DATABASE database_name statement and we
will execute this statement by creating an instance of the ‘cursor’ class.

import mysql.connector
 
mydb = mysql.connector.connect(
    host = "localhost",
    user = "yourusername",
    password = "your_password"
)
 
# Creating an instance of 'cursor' class
# which is used to execute the 'SQL'
# statements in 'Python'
cursor = mydb.cursor()
 
# Creating a database with a name
# 'geeksforgeeks' execute() method
# is used to compile a SQL statement
# below statement is used to create
# the 'geeksforgeeks' database
cursor.execute("CREATE DATABASE geeksforgeeks")

Output:
If the database with the name ‘geeksforgeeks’ already exists then you will get an error,
otherwise no error. So make sure that the new database that you are creating does not have
the same name as the database already you created or exists previously. Now to check the
databases that you created, use “SHOW DATABASES” – SQL statement i.e.
cursor.execute(“SHOW DATABASES”)

import mysql.connector
mydb = mysql.connector.connect(
    host = "localhost",
    user = "root",
    password = "1234"
)
# Creating an instance of 'cursor' class
# which is used to execute the 'SQL'
# statements in 'Python'
cursor = mydb.cursor()
# Show database
cursor.execute("SHOW DATABASE")
 
for x in cursor:
  print(x)

Output:
Creating Tables
first, select a
database and for that, database =
“NameofDatabase” as your fourth parameter in connect()
Function.We will use CREATE TABLE gfg (variableName1
datatype,
variableName2 datatype) statement to create our table
with the name ‘gfg’.

import mysql.connector
mydb = mysql.connector.connect(
    host = "localhost",
    user = "yourusername",
    password = "your_password",
    database = "geeksforgeeks"
)
cursor = mydb.cursor()
# Creating a table called 'gfg' in the
# 'geeksforgeeks' database
cursor.execute("CREATE TABLE gfg (name VARCHAR(255)

, user_name VARCHAR(255))")

Output:

If the table with the name ‘gfg’ already exists, you will get an error, otherwise no error. So
make sure that the new table that you are creating does not have the same name as the table
already you created or exists previously. Now to check tables that you created, use “SHOW
TABLES” – SQL statement i.e. cursor.execute(“SHOW TABLES”).

import mysql.connector
 
mydb = mysql.connector.connect(
    host = "localhost",
    user = "root
    password = "1234",
    database = "geeksforgeeks"
)
 
cursor = mydb.cursor()
 
# Show existing tables
cursor.execute("SHOW TABLES")
 
for x in cursor:
  print(x)

Output:

Notes:
 mysql.connector allows Python programs to access MySQL databases.
 connect() method of the MySQL Connector class with the arguments will connect
to MySQL and would return a MySQLConnection object if the connection is
established successfully.
 user = “yourusername”, here “yourusername” should be the same username as
you set during MySQL installation.
 password = “your_password”, here “your_password” should be the same
password as you set during MySQL installation.
 cursor() is used to execute the SQL statements in Python.
 execute() method is used to compile a SQL statement.

Example
Following program deletes all the records from EMPLOYEE whose AGE is more than 20 −
import mysql.connector

#establishing the connection


conn = mysql.connector.connect(
user='root', password='password', host='127.0.0.1', database='mydb')

#Creating a cursor object using the cursor() method


cursor = conn.cursor()

#Retrieving single row


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

#Preparing the query to delete records


sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (25)

try:
# Execute the SQL command
cursor.execute(sql)

# Commit your changes in the database


conn.commit()
except:
# Roll back in case there is any error
conn.rollback()

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

#Closing the connection


conn.close()

Removing a table using python

You can drop a table whenever you need to, using the DROP statement of MYSQL, but you
need to be very careful while deleting any existing table because the data lost will not be
recovered after deleting a table.
To drop a table from a MYSQL database using python invoke the execute() method on the
cursor object and pass the drop statement as a parameter to it.
Example
Following table drops a table named EMPLOYEE from the database.
import mysql.connector

#establishing the connection conn = mysql.connector.connect(


user='root', password='password', host='127.0.0.1', database='mydb'
)

#Creating a cursor object using the cursor() method


cursor = conn.cursor()

#Retrieving the list of tables print("List of tables in the database: ")


cursor.execute("SHOW Tables") print(cursor.fetchall())
#Doping EMPLOYEE table if already exists cursor.execute
("DROP TABLE EMPLOYEE") print("Table dropped... ")

#Retrieving the list of tables print(


"List of tables after dropping the EMPLOYEE table: ")
cursor.execute("SHOW Tables") print(cursor.fetchall())

#Closing the connection conn.close()

Reference:

https://www.tutorialspoint.com/python_data_access/python_sqlite_order_by.htm

What is an Exception Handling in Python?

An exception is an error which happens at the time of execution of a program.

Common Examples of Exception:

 Division by Zero
 Accessing a file which does not exist.
 Addition of two incompatible types
 Trying to access a nonexistent index of a sequence
 Removing the table from the disconnected database server.
 ATM withdrawal of more than the available amount

Different types of exceptions in python:

In Python, there are several built-in exceptions that can be raised when an error occurs
during the execution of a program. Here are some of the most common types of exceptions
in Python:
 SyntaxError: This exception is raised when the interpreter encounters a syntax
error in the code, such as a misspelled keyword, a missing colon, or an
unbalanced parenthesis.
 TypeError: This exception is raised when an operation or function is applied to
an object of the wrong type, such as adding a string to an integer.
 NameError: This exception is raised when a variable or function name is not
found in the current scope.
 IndexError: This exception is raised when an index is out of range for a list,
tuple, or other sequence types.
 KeyError: This exception is raised when a key is not found in a dictionary.
 ValueError: This exception is raised when a function or method is called with
an invalid argument or input, such as trying to convert a string to an integer
when the string does not represent a valid integer.
 AttributeError: This exception is raised when an attribute or method is not
found on an object, such as trying to access a non-existent attribute of a class
instance.
 IOError: This exception is raised when an I/O operation, such as reading or
writing a file, fails due to an input/output error.
 ZeroDivisionError: This exception is raised when an attempt is made to divide
a number by zero.
 ImportError: This exception is raised when an import statement fails to find or
load a module.

Why should you use Exceptions?


Here are the reasons for using exceptions in Python:

 Exception handling allows you to separate error-handling code from normal code.
 An exception is a Python object which represents an error.
 As with code comments, exceptions helps you to remind yourself of what the program
expects.
 It clarifies the code and enhances readability.
 Allows you to stimulate consequences as the error-handling takes place at one place
and in one manner.
 An exception is a convenient method for handling error messages.
 In Python, you can raise an exception in the program by using the raise exception
method.
 Raising an exception helps you to break the current code execution and returns the
exception back to expection until it is handled.
 Processing exceptions for components which can’t handle them directly.

Python Exception Handling Mechanism


Exception handling is managed by the following 5 keywords:

1. try
2. catch
3. finally
4. throw

Python Try Statement


A try statement includes keyword try, followed by a colon (:) and a suite of code in which
exceptions may occur. It has one or more clauses.

During the execution of the try statement, if no exceptions occurred then, the interpreter
ignores the exception handlers for that specific try statement.
In case, if any exception occurs in a try suite, the try suite expires and program control
transfers to the matching except handler following the try suite.

Syntax:
try:
statement(s)

try:
numerator = 10
denominator = 0

result = numerator/denominator

print(result)
except:
print("Error: Denominator cannot be 0.")

# Output: Error: Denominator cannot be 0.


Run Code

In the example, we are trying to divide a number by 0. Here, this code generates an
exception.
To handle the exception, we have put the code, result = numerator/denominator inside
the try block. Now when an exception occurs, the rest of the code inside the try block is
skipped.
The except block catches the exception and statements inside the except block are executed.
If none of the statements in the try block generates an exception, the except block is skipped.

Catching Specific Exceptions in Python

For each try block, there can be zero or more except blocks. Multiple except blocks allow us


to handle each exception differently.
The argument type of each except block indicates the type of exception that can be handled
by it. For example,
try:

even_numbers = [2,4,6,8]
print(even_numbers[5])
except ZeroDivisionError:
print("Denominator cannot be 0.")

except IndexError:
print("Index Out of Bound.")

# Output: Index Out of Bound

# Program to handle multiple errors with one


# except statement
# Python 3
 
def fun(a):
    if a < 4:
 
        # throws ZeroDivisionError for a = 3
        b = a/(a-3)
 
    # throws NameError if a >= 4
    print("Value of b = ", b)
     
try:
    fun(3)
    fun(5)
 
# note that braces () are necessary here for
# multiple exceptions
except ZeroDivisionError:
    print("ZeroDivisionError Occurred and Handled")
except NameError:
    print("NameError Occurred and Handled")

}
Finally Statement in Python
Finally block always executes irrespective of an exception being thrown or not. The final
keyword allows you to create a block of code that follows a try-catch block.

Finally, clause is optional. It is intended to define clean-up actions which should be that
executed in all conditions.

try:
numerator = 10
denominator = 0
result = numerator/denominator

print(result)
except:
print("Error: Denominator cannot be 0.")

finally:
print("This is finally block.")

# Python program to demonstrate finally


 
# No exception Exception raised in try block
try:
    k = 5//0  # raises divide by zero exception.
    print(k)
 
# handles zerodivision exception
except ZeroDivisionError:
    print("Can't divide by zero")
 
finally:
    # this block is always executed
    # regardless of exception generation.
    print('This is always executed')

Raise Statement in Python


The raise statement specifies an argument which initializes the exception object. Here, a
comma follows the exception name, and argument or tuple of the argument that follows the
comma.

You might also like