Unit 3
Unit 3
After creating a function we can call it by using the name of the function followed by
parenthesis containing parameters of that particular function.
Output:
Welcome to GFG
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.
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.
Output:
False True
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.
Output:
even
odd
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.
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.
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.
Output:
Case-1:
Hi, I am Suraj
My age is 27
Case-2:
Hi, I am 27
My age is Suraj
Output
Hello
Welcome
to
GeeksforGeeks
Example 2: Variable length keyword arguments
Output
first == Geeks
mid == for
last == Geeks
# 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
Output
343
343
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.
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.
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.
Syntax
fileobject.close()
# 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.
try:
fileptr = open("file.txt")
# perform file operations
finally:
fileptr.close()
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.
Example
with open("file.txt",'r') as f:
content = f.read();
print(content)
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.
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.
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:
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.
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:
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:
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.
#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:
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.
#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.']
The new file can be created by using one of the following access
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.
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:
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:
Database Connection
There are the following steps to connect a python application to our database.
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.
# 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:
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.