0% found this document useful (0 votes)
29 views24 pages

Unit 3

This document discusses Python functions. It defines what functions are in Python and their benefits, such as increased code readability and reusability. It covers the syntax for defining functions, different types of functions including built-in and user-defined, and how to call functions. It also discusses function parameters, return values, nested functions, anonymous functions, and file handling in Python.

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)
29 views24 pages

Unit 3

This document discusses Python functions. It defines what functions are in Python and their benefits, such as increased code readability and reusability. It covers the syntax for defining functions, different types of functions including built-in and user-defined, and how to call functions. It also discusses function parameters, return values, nested functions, anonymous functions, and file handling in Python.

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/ 24

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

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.

You might also like