UNIT I
UNIT I
UNIT I
Features of Python
● Python is a general purpose, dynamic, high-level, and interpreted programming language.
It supports Object Oriented programming approach to develop applications. It is simple
and easy to learn and provides lots of high-level data structures.
● Python is easy to learn yet powerful and versatile scripting language, which makes it
attractive for Application Development.
● Python's syntax and dynamic typing with its interpreted nature make it an ideal language
for scripting and rapid application development.
● Python supports multiple programming pattern, including object-oriented, imperative,
and functional or procedural programming styles.
● Python is not intended to work in a particular area, such as web programming. That is
why it is known as multipurpose programming language because it can be used with web,
enterprise, 3D CAD, etc.
● We don't need to use data types to declare variable because it is dynamically typed so we
can write a=10 to assign an integer value in an integer variable.
● Python makes the development and debugging fast because there is no compilation step
included in Python development, and edit-test-debug cycle is very fast.
23
● Computer Vision or Image Processing Applications.
● Speech Recognitions
24
Keywords
Python keywords are unique words reserved with defined meanings and functions that we can only
apply for those functions.Python contains thirty-five keywords in the version, Python 3.9.
Identifiers
In programming languages, identifiers are names used to identify a variable, function, or other
entities in a program. The rules for naming an identifier in Python are as follows:
● The name should begin with an uppercase or lowercase alphabet or an underscore sign (_).
● This may be followed by any combination of characters a-z, A-Z, 0-9 or underscore (_).
Thus, an identifier cannot start with a digit.
● It can be of any length. (However, it is preferred to keep it short and meaningful).
● It should not be a keyword or reserved word.
● We cannot use special symbols like !, @, #, $, %, etc. in identifiers.
Legal Identifier Names Example:
Myvar my_var _my_var myVar myvar2
Illegal Identifier Names Example:-
2myvar my-var my var= 9salary
Literals or Values:
Literals are the fixed values or data items used in a source code. Python supports different types
of literals such as:
a. String literals - “Rishaan”
b. Numeric literals – 10, 13.5, 3+5i
c. Boolean literals – True or False
d. Special Literal None
e. Literal collections
Literal collections
Literals collections in python includes list, tuple, dictionary, and sets.
● List: It is a list of elements represented in square brackets with commas in between.
These variables can be of any data type and can be changed as well.
● Tuple: It is also a list of comma-separated elements or values in round brackets. The
values can be of any data type but can’t be changed.
● Dictionary: It is the unordered set of key-value pairs.
● Set: It is the unordered collection of elements in curly braces ‘{}’.
Operators
An operator is used to perform specific mathematical or logical operation on values. The values
that the operator works on are called operands.
● Arithmetic operators
● Assignment operators
● Comparison operators
● Logical operators
25
● Identity operators
● Membership operators
● Bitwise operators
Arithmetic operators: used with numeric values to perform common mathematical operations.
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
26
<= Less than or equal to x <= y
Identity Operators: used to compare the objects, not if they are equal, but if they are actually the
27
same object, with the same memory location.
is Returns True if both variables are the same object x is y
is not Returns True if both variables are not the same object x is not y
Punctuators
Punctuators are symbols that are used in programming languages to organize sentence
structure, and indicate the rhythm and emphasis of expressions, statements, and program
structure. Common punctuators are: „ “ # $ @ []{}=:;(),
Python Variables
Variables are nothing but reserved memory locations to store values. This means that when
you create a variable you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and decides what can be
stored in the reserved memory. Therefore, by assigning different data types to variables, you
can store integers, decimals or characters in these variables.
● Variables are containers for storing data values.
● Unlike other programming languages, Python has no command for declaring a variable.
● A variable is created the moment you first assign a value to it.
Example:
x=5
y = "John"
print(x)
print(y)
● Variables do not need to be declared with any particular type and can even change
type after they have been set.
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
● String variables can be declared either by using single or double quotes:
x = "John"
# is the same as
x = 'John'
Output Variable:
The Python print statement is often used to output variables. To combine both text and a
variable, Python uses the, character:
x = "awesome"
28
print("Python is " , x)
Display Multiple variable:-
x = "awesome“
y=56
print(“Value of x and y is=" , x, y)
print
(counter)
print (miles)
print (name)
a=b=c=
1
a,b,c = 1,2,"john"
Data Types
The data stored in memory can be of many types, i.e., Every value belongs to a specific data type
in Python. Data type identifies the type of data which a variable can hold and the operations that
can be performed on those data.Python has various standard data types that are used to define the
operations possible on them and the storage method for each of them.
29
The different standard data types −
● Numbers
30
● String
● List
● Tuple
● Dictionary
● Boolean
● Set
Numbers
Number data types store numeric values. Number objects are created when you assign a value to
them. For example −
var1 = 1
var2 = 10
You can also delete the reference to a number object by using the del statement. The syntax
of the del statement is −
Strings
31
Strings in Python are identified as a contiguous set of characters represented in the quotation
marks. Python allows for either pairs of single or double quotes. Subsets of strings can be taken
using the slice operator ([ ] and [:] ).
str = 'Hello World!'
32
print str[2:5] # Prints characters starting from 3rd to 5th llo
print str[2:] # Prints string starting from 3rd character llo World!
print str * 2 # Prints string two times Hello World!Hello World!
print str + "TEST" # Prints concatenated string Hello World!TEST
Lists
Lists are the most versatile of Python's compound data types. A list contains items separated by
commas and enclosed within square brackets ([]).
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting
at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is the list
concatenation operator, and the asterisk (*) is the repetition operator.
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print list # Prints complete list ['abcd', 786, 2.23, 'john', 70.2]
print list[0] # Prints first element of the list- abcd
print list[1:3] # Prints elements starting from 2nd till 3rd - [786, 2.23]
print list[2:] # Prints elements starting from 3rd element -[2.23, 'john', 70.2]
print tinylist * 2 # Prints list two times-[123, 'john', 123, 'john']
print list + tinylist # Prints concatenated lists-['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
Tuples
A tuple is another sequence data type that is similar to the list. A tuple consists of a number of
values separated by commas. Lists are enclosed in brackets ( [ ] ) and their elements and size can
be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated.
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print tuple # Prints the complete tuple--('abcd', 786, 2.23, 'john', 70.2)
print tuple[0] # Prints first element of the tuple-- abcd
print tuple[1:3] # Prints elements of the tuple starting from 2nd till 3rd--(786, 2.23)
print tuple[2:] # Prints elements of the tuple starting from 3rd element--(2.23, 'john', 70.2)
print tinytuple * 2 # Prints the contents of the tuple twice--(123, 'john', 123, 'john')
print tuple + tinytuple # Prints concatenated tuples-- ('abcd', 786, 2.23, 'john', 70.2, 123, 'john')
Dictionary
Python's dictionaries are kind of hash table type. They consist of key-value pairs. A dictionary
key can be almost any Python type, but are usually numbers or strings. Values, on the other
hand, can be any arbitrary Python object.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square
braces ([]). For example −
33
dict = {}
34
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print dict['one'] # Prints value for 'one' key This is one
print dict[2] # Prints value for 2 key This is two
print tinydict # Prints complete dictionary {'dept': 'sales', 'code': 6734, 'name': 'john'}
print tinydict.keys() # Prints all the keys ['dept', 'code', 'name']
print tinydict.values() # Prints all the values ['sales', 6734, 'john']
Boolean
Boolean represent one of two values: True or False. When you compare two values, the
expression is evaluated and Python returns the Boolean answer.Also, almost any value is
evaluated to True if it has some sort of content.
print(10 > 9) True bool(None) Fal
se
print(10 == 9) False bool(0) Fals
e
print(10 < 9) False bool("") False
bool("abc") True bool(()) False
bool(123) True bool([]) False
bool(["apple", "cherry"])True bool({}) False
bool(False) False
Mutable objects
Mutability means the ability to modify or edit a value. Mutable objects in Python enable the
programmers to have objects that can change their values. They generally are utilized to store
a collection of data. It can be regarded as something that has mutated, and the internal state
applicable within an object has changed.
35
In mutable data types, we can modify the already existing values of the data types (such as lists,
dictionaries, etc.). Or, we may add new values or remove the existing values from our data types.
Basically, we may perform any operation with our data without having to create a new copy of
our data type. Hence, the value assigned to any variable can be changed.
e.g.color = ["red", "blue", "green"]
print(color) color[0] = Output:
"pink" ['red', 'blue', 'green']
color[-1] = "orange" print(color) ['pink', 'blue', 'orange']
Immutable Objects
Immutable objects in Python are objects wherein the instances do not change over the period.
Immutable instances of a specific type, once created, do not change, and this can be verified
using the id method of Python
e.g.message = "Welcome to GeeksforGeeks"
message[0] = 'p'
print(message)
Output
Traceback (most recent call last):
File "/home/ff856d3c5411909530c4d328eeca165b.py", line 3,
in message[0] = 'p'
TypeError: 'str' object does not support item assignment
36
Consider a tuple
tup = ([3, 4, 5], 'myname')
The tuple consists of a string and a list. Strings are immutable so we can’t change its value. But the
contents of the list can change. The tuple itself isn’t mutable but contain items that are mutable.
Expression in python:
A combination of constants, operands and operators is called an expression. The expression in
Python produces some value or result after being interpreted by the Python interpreter. The
expression in Python can be considered as a logical line of code that is evaluated to obtain some
result. If there are various operators in an expression then the operators are resolved based on
their precedence.
E.g. Expression 6-3*2+7-1 evaluated as 6
37
# Python automatically converts
# a to int
a=7
print(type(a))
# Python automatically converts
# b to float
b = 3.0
print(type(b))
# Python automatically converts
# c to float as it is a float addition
c=a+b
print(c)
print(type(c))
# Python automatically converts
# d to float as it is a float multiplication
d=a*b
print(d)
print(type(d))
int() : int() function take float or string as an argument and return int type object.
float() : float() function take int or string as an argument and return float type object.
str() : str() function take float or int as an argument and return string type object.
38
Operator Associativity: If an expression contains two or more operators with the same precedence
then Operator Associativity is used to determine. It can either be Left to Right or from Right to
Left.
Comments in python:
Comments are non-executable statements of python. It increases the readability and
understandability of code.
Types of comment:
i. Single line comment (#) – comments only single line.
e.g. a=7 # 7 is assigned to variable ‘a’
print(a) # displaying the value stored in ‘a’
39
Taking multiple inputs from user
40
Using split() method
Using List comprehension
split() method :
This function helps in getting multiple inputs from users. It breaks the given input by the specified
separator. If a separator is not provided then any white space is a separator. Generally, users use a
split() method to split a Python string but one can use it in taking multiple inputs.
input().split(separator, maxsplit)
List comprehension is an elegant way to define and create list in Python. We can create lists just like
mathematical statements in one line only. It is also used in getting multiple inputs from a user.
x, y, z = [int(x) for x in input("Enter three values: ").split()]
value(s) : Any value, and as many as you like. Will be converted to string before printed
sep=’separator’ : (Optional) Specify how to separate the objects, if there is more than
one.Default :’ ‘
end=’end’: (Optional) Specify what to print at the end.Default : ‘\n’
file : (Optional) An object with a write method. Default :sys.stdout
flush : (Optional) A Boolean, specifying if the output is flushed (True) or buffered (False).
Default: False
Debugging:-
Debugging is a process of locating and removing errors from program.
Errors in a program
An error or exception refers to an interruption in the execution of code due to which we cannot
attain the expected outcome to the end-users. These errors are classified on the basis of the event
when the program generate the error. The two types of errors are Compile Time Errors and
Runtime Errors and Logical errors
42
Runtime Errors
These errors occur during the run-time program execution after a successful compilation. Division
error is one of the most common errors (runtime). It occurs due to the division by zero. It is very
difficult for a compiler to find out a runtime error because it cannot point out the exact line at
which this particular error occurs.
Selection Statements
Decision making is valuable when something we want to do depends on some user input or some
other value that is not known when we write our program. This is quite often the case and Python,
along with all interesting programming languages, has the ability to compare values and then take
one action or another depending on that outcome.
Python have following types of selection statements
1. if statement
2. if else statement
3. Ladder if else statement (if-elif-else)
4. Nested if statement
if statements
This construct of python program consist of one if condition with one block of statements. When
condition becomes true then executes the block.
43
Syntax:
44
if ( condition):
Statement(s)
Example:
age=int(input(“Enter Age: “))
if ( age>=18):
print(“You are eligible for vote”)
if(age<0):
print(“You entered Negative Number”)
if - else statements
This construct of python program consist of one if condition with two blocks. When condition
becomes true then executes the block given below
Syntax:
if ( condition):
Statement(s)
else:
Statement(s)
Example
x = int(input("Please enter an integer: "))
y = int(input("Please enter another integer: "))
i f x > y:
print(x,"is greater than",y)
else:
print(y,"is greater than or equal to",x)
i = 20
if (i == 10):
45
print("i is 10")
elif (i == 15):
print("i is 15")
elif (i == 20):
print("i is 20")
else:
print("i is not present")
Nested-if
Nested if statements mean an if statement inside another if statement.
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
Example
The iteration (Looping) constructs mean to execute the block of statements again and again
depending upon the result of condition. This repetition of statements continues till condition meets
True result. As soon as condition meets false result, the iteration stops.
Python supports following types of iteration statements
1. while
2. for
Four Essential parts of Looping:
i. Initialization of control variable
ii. Condition testing with control variable
iii. Body of loop Construct
iv. Increment / decrement in control variable
46
for loop
For loops are useful when you need to do something for every element of a sequence
<statements before for loop>
for <variable> in <sequence>:
<body of for loop>
<statements after for loop>
Example
s = input("Please type some characters and press enter:")
for c in s:
print(c)
print("Done")
while Loop
Python's while statement is its most general iteration construct. In simple terms, it repeatedly
executes a block of indented statements, as long as a test at the top keeps evaluating to a true value.
When the test becomes false, control continues after all the statements in the while, and the body
never runs if the test is false to begin with.
while <test>: # loop test
<statements1> # loop body
else: # optional else
<statements2> # run if didn't exit loop with b
Example
count = 0
while (count < 9):
print ('The count is:', count )
count = count + 1
print ("Good bye!" )
Python supports to have an else statement associated with a loop statement. If the else statement is
used with a for loop, the else statement is executed when the loop has exhausted iterating the list. If
the else statement is used with a while loop, the else statement is executed when the condition
becomes false
Example:
count = 0
while count < 5:
print (count, " is less than 5" )
count = count + 1
else:
print( count, " is not less than 5”)
Single Statement Suites: If there is only one executable statement in while loop, then we can use this
47
format.
Example:
flag = 1
while (flag): print ('Given flag is really true!' )
print( "Good bye!" )
Jump Statements
Now that we‘ve seen a few Python loops in action, it‘s time to take a look at two simple statements that
have a purpose only when nested inside loops—the break and continue statements.
In Python:
pass
Does nothing at all: it‘s an empty statement placeholder
break
Jumps out of the closest enclosing loop (past the entire loop statement)
continue
Jumps to the top of the closest enclosing loop (to the loop‘s header line)
Example
range(5) => sequence of 0,1,2,3,4
range(2,5) => sequence of 2,3,4
range(1,10,2) => sequence of 1,3,5,7,9
range(5,0,-1) => sequence of 5,4,3,2,1
range(0,-5) => sequence of [ ] blank
list (default Step is +1)
range(0,-5,-1) => sequence of 0, -1, -2, -3, -4
range(-5,0,1) => sequence of -5, -4, -3, -2, -1
48
range(-5,1,1) => sequence of -5, -4, -3, -2, -1, 0
Advantages of Functions
● Reducing duplication of code
● Decomposing complex problems into simpler pieces
● Improving clarity of the code
● Reuse of code
● Information hiding
Python function types
There are three categories of functions:
● Built-in functions
49
● Function defined in modules
● User defined functions.
Built-in functions
The functions whose functionality is predefined in Python are referred to as built-in functions.
The python interpreter has several such functions that are always available for use.
E.g. len(), type(), int(), input()
Function defined in modules
These functions are pre-defined in particular modules and can only be used after the specific
module is imported.
E.g. All mathematical functions are defined in the module math.
User-defined functions
Python User Defined Functions allow users to write unique logic that the user defines. It is
the most important feature in Python that consists of custom-defined logics with a set of rules and
regulations that can be passed over the data frame and used for specific purposes.
Internally Python names the segment with top-level statements (no indentation) as
_main_ Python begins execution of a program from top-level statements.
Defining a Function
A function in Python is defined as given below:
def< function name >(parameters):
[“ ” ”<function’s docstring>” “ “]
<statements>
[<statements>
]
……………………..
50
● Keyword def that marks the start of the function header.
● A function name to uniquely identify the function. Function naming follows the same rules
of writing identifiers in Python.
● Parameters (arguments) through which we pass values to a function. They are optional.
● A colon (:) to mark the end of the function header.
● Optional documentation string (docstring) to describe what the function does.
● One or more valid python statements that make up the function body. Statements must
have the same indentation level (usually 4 spaces).
● An optional return statement to return a value from the function.
Function header:
The Header of a function specifies the name of the function and the name of each
of its parameters. It begins with the keyword def.
Parameters:
Whenever a function call statement is encountered, an execution frame for the function is
created and the control is transferred to it. The statements are then executed and if there is
return statement in the program, it will be executed and returns to the function call
statement block.
def message():
print('Hello I am learning how to create function in python.')
def
sum(a,b):
c=a+b
print('Sum of %d and %d is %d' %(a,b,c))
# main program
# calling the function
message() message()
# calling the function
sum() sum(10,20)
In the above program, two functions message() and sum() is declared. The message()
function does not accept any argument but displays a text on the screen whenever we call it. On the
other hand, the sum() function accept two arguments and display their sum on the screen. when the
main program calls the function message(), the program flow goes to the body of the function
message() and execute its codes. After that, it returns to the main program and then calls the second
function sum() by sending it two arguments (10,20), the program flow goes to the body of the
function sum(), and execute its code and again returns to the main program. At last, the main
programs end.
The function calling another function is called the caller and the functions being
called is the called function or callee.
53
Passing parameters:-
Python support three types of formal arguments/parameters:
1. Positional argument (required arguments):-
When the functions call statement must match the number and order of arguments as
define in the functions definition this is called the positional arguments.
Example:-
def check(a,b,c):
:
Then possible functions call for this can be:-
check(x,y,z)#3values(allvariables)passed
check(2,x,y)#3values(literal+variables)passed
check ( 2 , 3 , 4 ) # 3 values ( all literal ) passed.
Thus through such function calls-
• The argument must be provided for all parameters (required)
• The values of argument are matched with parameters, position(order)wise(positional)
2. Default arguments:-
A parameter having defined value in the function header is known as a default parameter.
Example:-
def interest(principal,time,rate=10):
si=interest(5400,2) #third argument missing
So the parameter principal get value 5400,time get 2 and since the third argument rate is missing, so
default value 0.10 is used for rate.
• Default argument are useful in situations where some parameters always have same
value.
Some advantages of the default parameters are listed below:-
54
• They can be used to add new parameters to the existing functions.
• They can be used to combine similar function in to one.
3. Keyword(or named)arguments:-
Keyword arguments are the named arguments with assigned values being passed in the
function call statement.
Example:-
def interest(prin,time,rate):
return prin * time * rate
print (interest ( prin = 2000 , time = 2 , rate 0.10 ))
print (interest ( time = 4 , prin = 2600 , rate = 0.09 ))
print(interest(time=2,rate=0.12,prin=2000))
All the above functions call are valid now, even if the order of arguments does not match.
4. Using multiple argument type together:-
Python allows you to combine multiple argument types in a function call.
Rules for combining all three types of arguments:-
And argument list must first contain positional(required) arguments followed by any
keyword argument.
• Keyword arguments should be taken from the required arguments preferably.
• You cannot specify a value for an argument more than once.
Example:-
def interest(prin,cc,time=2,rate=0.09):
return prin * time * rate
Types of user defined function
1. No Argument No return
2. With Argument No return
3. No Argument with return
4. With Argument with return
1. No Argument No return
def Add():
a= int (input(“Enter First Number”)) b=
int (input(“Enter Second Number”))
c=a+b
print (“The Sum of inputted Numbers is:”, c)
Add()
print(“ Executed”)
Remember: The variable in main program are differ from the variable in function definition i.e. a
and b should be x and y. In this scenario the variable passed (num1,num2)will be called argument,
and when it replace with the variable defined in the function will be called as parameter.
3. No Argument with return
def Add():
a=int (input(“Enter First Number”))
b= int (input(“Enter Second Number”))
c=a+b
return c
x= add()
print (“The Sum of inputted Numbers is:”, x)
Note: { As return does not show the result we have to store the returned value on another
variable x}
4. With Argument with return
def Add (a,b):
c=a+b return
c
a=int (input(“Enter First Number”))
b= int (input(“Enter Second Number”)) x=
add(a,b)
print (“The Sum of inputted Numbers is:”, x)
56
is called, the arguments are the data passed to the method’s parameters.
57
Function arguments : Arguments are used to pass information from the rest of the program to the
function. This information return a result. There is no limit to the number of arguments that can be
written. Depending on the type of function you’re performing, there might even be no argument.
Use commas to separate the arguments in a function. Take into account the number of
arguments you put in a function call. The number of arguments must be exactly the same as the
number of parameters.
In the example below, the variable name is the input parameter, where as the value, “Arnav”,
passed in the function call is the argument.
def welcome(name):
print("Hello! " + name + " Good Morning!!")
welcome("Arnav")
Output:
Hello! Arnav Good Morning!!
Returning a Function
If you wish to return some values from the function to the rest of the program, you can use
the return statement. As the name suggests, it returns a value without printing it. Executing this
statement will cause the Python function to end immediately and store the value being returned into
a variable.
Scope of variables
Scope means in which part(s) of the program, a particular piece of code or data is accessible
or known.
In python there are broadly 2 kinds of Scopes:
● Global Scope
● Local Scope
Global Scope:
● A name declared in top level segment(_main_) of a program is said to have global scope
and can be used in entire program.
● Variable defined outside of the all functions are global variables.
Local Scope :
● A name declared in a function body is said to have local scope i.e. it can be used only
within this function and the other block inside the function.
● The formal parameters are also having local scope.
When dealing with Python functions, you should also consider the scope of the variables.
The code in a function is in its own little world, separate from the rest of the program. Any variable
declared in the function is ignored by the rest of the function. This means that two variables with
the same name can exist, one inside the function and the other outside the function. However, this
is not a good practice. All variable names must be unique regardless of their scope.
58
Local variable: A variable that is defined within a function and can only be used within that
particular function. With respect to the local variable, the area in a function is called “local area”.
Global variable: A variable that is defined in the main part of the programming and, unlike local
variables, can be accessed via local and global areas.
Example:
Lifetime of Variables:
Lifetime is the time for which a variable lives in memory. For global variables the lifetime
is entire program run i.e. as long as program is executing. For local variable, lifetime is their
function’s run i.e. as long as function is executing.
59
Data files are files that store data pertaining to a specific application. The data files
can be stored in following ways:
● Text files: These files store information in the form of a stream of ASCII or UNICODE
characters. Each line is terminated by an EOL character. Python programs, contents written
in text editors are some of the example of text files.
● Binary files: These files store information in the form of a stream of bytes. No EOL
character is used and binary files hold information in the same format in which it is held in
the memory. The .exe files, mp3 file, image files, word documents are some of the examples
of binary files.We can’t read a binary file using a text editor.
Difference Between Text File And Binary File
Text Binary
File File
Stores information in ASCII characters. Stores information in the same format which
the information is held in memory.
Less prone to get corrupt as change reflects Can easily get corrupted, corrupt on even
as single
soon as made and can be undone. bit change.
Store only plain text in a file. Can store different types of data.
Widely used file format and can be opened in Developed for an application and can be
any text editor. opened in that only.
Slower than binary files. Binary files are faster and easier for a
program to read and write the text files.
Opened in any text editor. Mostly .txt and .rtf Can have any application defined extensions.
are used as extensions of text files.
60
Opening Files :
To perform file operation, it must be opened first then after reading, writing,editing
operation can be performed.To create any new file then too it must be opened. On opening
of any file, a file relevant structure is created in memory as well as memory space is
created to store contents. Once we are done working with the file, we should close the file.
Itisdoneusing open() function as per one of the following syntax:
<fileobjectname>=open(<filename>)
<fileobjectname>=open(<filename>,<mode>)
For example:
stu=open("students.txt")
The above statement open file"students.txt" in file mode as read mode(defaultmode) and attaches it
to file object namely stu.
Consider one more file open statement: - stu=open ("e:\\main\\
students.txt","w")
The above statement open file"students.txt"(storedinfoldere:\main)in write
mode(because of"w"givenasmode)and attaches it to file object namely stu.
• Please note that when you open a file in read mode,the given file must exist in folder,
otherwise Python will raise error.
File Object/File Handle:-A file object is a reference to a file on disk.It opens and makes it
available for a number of different tasks.
FileAccessModes:-
T Bina
Description
ex ry
t File
fil Mode
e
mode
‘r’ ‘rb’ Read-Default value. Opens a file for reading, error if the
file does not exist.
‘w’ ‘wb’ Write- Opens a file for writing, creates the file if it does
not exist
61
‘a’ ‘ab’ Append- Opens a file for appending, creates the file if it
does not exist
‘r+’ ‘rb+’ Read and Write- File must exist, otherwise error is raised.
62
‘w+’ ‘wb+’ Read and Write-File is created if does not exist.
A file-mode governs the type of operations(e.g.,read/write/append) possible in the opened file i.e., it
refers to how the file will be used once it's opened.
Closing Files :
One must always close a file when the file is no longer required for any more
operations.The file can be closed by using the close( ) function which can be used w ith the
file pointer as follows:
<file_handle>.close()
Working with Text Files:
1. Read the data from a file
2. Write the data to a file
3. Append the data to a file
Example-1:Programusingread()function: OUTPUT:
fin=open("D:\\pythonprograms\\Boo Python is interactive language. It is case
k.txt",'r') sensitive language.
It makes the difference between uppercase
63
str=fin.read( ) and
64
print(st lowercase letters. It is official language of
r) google.
fin.clos
e()
Example-2:Programusingread()function: OUTPUT:
fin=open("D:\\python programs\\
Python is
Book.txt",'r') str=fin.read(10)
print(str)
fin.close()
Example-3:usingreadline()function: OUTPUT:
Myfile
m Peter.
w are you?
65
f=open(r’MyFile.txt’,’r’)
data = f.read( )
66
print(da
ta)
f.close(
)
Example-2:Program using OUTPUT:
writelines()function: #It will append the content.
f=open(r’Myfile.txt’,’a’)
data=[‘I have a dog., ‘\nI love my cat.’]
f.writelines(da My name is Aarav.I have a
ta) f.close( ) dog. I love my cat.
f=open(r’Myfile.txt’,’r’)
data = f.read( )
print(da
ta)
f.close( )
flush( ) function:
● When we write any data to file, python hold everything in buffer (temporary
memory) and pushes it onto actual file later. If you want to force Python to write the
content of buffer onto storage, you can use flush() function.
● Python automatically flushes the files when closing them i.e. it will be implicitly
called by the close(), but if you want to flush before closing any file you can use flush()
seek( ) function:
The seek( ) function allows us to change the position of the file pointer in the
opened file as follows:
f.seek(offset,mode)
where
offset - is a number specifying number of bytes.
mode - specifies the reference point from where the offset will be calculated to
place the file pointer. The mode argument is optional and has three possible values namely
0, 1 and 2. The default value of mode is 0.
0 - beginning of file
1 - current position in file
2 - end of file
tell( ) function:
The tell() method returns the current position of the file pointer in the opened file. It is used as
follows:
f.tell()
67
Example-1: tell()function: OUTPUT:
Example: 14
fout=open("story.txt","w")
fout.write("Welcome Python")
print(fout.tell( ))
fout.close( )
CSV Files
The CSV (Comma Separated Values) is a special text file format in which rows of data are present
and the individual data elements are separated by commas. The CSV format is the most common
import and export format for spreadsheets and databases. The csv files have the extension .csv
Example for data contained in csv file
Raghu,23,100
Tisha,45,230
Yatin,67,90
68
Advantages of csv files:
● CSV is human readable and easy to edit manually.
● CSV is simple to implement and parse.
● CSV is processed by almost all existing applications.
● CSV is smaller in size
● CSV is considered to be standard format
● CSV is compact. For XML you start tag and end tag for each column in each row. In CSV
you write the column headers only once.
● CSV can handle large unstructured data generated by social media effectively
1. Each record is located on a separate line, delimited by a line break (CRLF). For example:
One,two,three CRLF four,five,six CRLF
2. The last record in the file may or may not have an ending line break. For example:
One,two,three CRLF four,five,six
3. There maybe an optional header line appearing as the first line of the file with the same
format as normal record lines. For example:
Name,Rollno,Marks CRLF Header line Raghu,1011,56 CRLF
Swara,1012,78 CRLF
4. Each field may or may not be enclosed in double quotes. If fields are not enclosed with
double quotes, then double quotes may not appear inside the fields. For example:
"one","two","three" CRLF Eight,nine,ten
[Note:
1. CR stands for the character 'Carriage Return' with Integer ASCII code - 13
and C++/Python notation \r or '\r'.
2. LF stands for the character 'Line Feed' with Integer ASCII code - 10 and
C++/Python notation \n or '\n'.
69
3. In Windows platform the Enter Key / End of Line(EOL) / newline character is
represented by the character combination CRLF i.e. '\r\n' in python.
4. In Unix/Linux platforms the Enter Key /End of Line (EOL) / newline character
is represented by the character LF only i.e. '\n' in python.
5. In Macintosh platforms the Enter Key / End of Line (EOL) / newline character
is represented by the character CR only i.e. '\r' in python.
6. When opening a file for reading CSV file add the parameter, newline='EOL_character' to
process the End of Line correctly.
While opening a CSV file for reading on Windows platform, add the parameter, newline='\r\n'
in the open() method to avoid adding an extra blank line while processing/displaying output on
the screen ]
In CSV files there can be delimiters other than comma(,)
Tab separated values
Raghu 23 100
Tisha 45 230
Yatin 67 90
import csv as c
or
import csv
READING FROM A CSV FILE-READER OBJECT
Reading from a csv file is done using a reader object. The CSV file is opened as a text
file with Python’s built-in open() function, which returns a file object. This creates a
special type of object to access the CSV file (reader object), using the reader()
70
function.
71
The reader object is an iterable that gives us access to each line of the CSV file as a
list of fields. You can also use next() directly on it to read the next line of the CSV file,
or you can treat it like a list in a for loop to read all the lines of the file (as lists of the
file’s fields).
Syntax:
csv.reader(fileobject,delimiter=“ “)-> it returns a reader object
import csv as c
with open(‘12ACS.csv’,"r") as mycsv:
csvreader=c.reader(mycsv,delimiter=",")
for row in csvreader:
print (row)
CREATING A CSV FILE THROUGH A PYTHON PROGRAM FOR WRITING DATA
To write to a CSV file in Python, we can use the csv.writer() function. The
csv.writer() function returns a writer object that converts the user's data into a
delimited string.
This string can later be used to write into CSV files using the writerow() function.
In order to write to a CSV file, we create a special type of object to write to the CSV
file "writer object", which is defined in the CSV module, and which we create using
the writer() function.
The writerow() method allows us to write a list of fields to the file. The fields
can be strings or numbers or both. Also, while using writerow(), you do not need to
add a new line character (or other EOL indicator) to indicate the end of the line,
writerow() does it for you as necessary.
writerow() Vs writerows()
writerow() is used to write a single row to a csv file.
72
writerows() is used to write multiple rows/lines to csv file
To demonstrate writerow() and writerows()
import csv
f=open("one.csv","w",newline='')
csvwriter=csv.writer(f,delimiter=',')
csvwriter.writerow(['one','two','three'])
l=[(23,45,67),(34,56,78),(45,67,78)]
csvwriter.writerows(l)
f.close()
OUTPUT:
one,two,three
23,45,67
34,56,78
45,67,78
❖ Push function
❖ Pop Function
❖ Display function
A data structure is a way of store, organize, or manage data in efficient and productive manner.
The python data structure stack is a linear data structure. It follows the principle of LIFO (Last In
First Out). The representation of data is something like this:
73
By observing the above image you can understand the following:
Push function
A function to push an element. To push the element append() method is used as well as the
position of the top should be changed. Observe the following code:
def push(stk,e):
stk.append(e)
Pop Function
The pop function requires validation to check whether the stack is underflow or not if it is not then
use the logic to delete the element from the top. Have a look at this code:
def pop_stack(stk):
if stk==[]:
return "UnderFlow"
else:
e = stk.pop()
return e
Display function
Write a function to check the element is inserted or not, observe this code:
def
display(stk):
if stk==[]:
print("Stack Underflow") 74
else:
for i in (stk[::-
1]): print(i)
Applications of the stack:
• Infix to Postfix /Prefix conversion
• Redo-undo features at many places like editors, photoshop.
• Forward and backward features in web browsers
• Used in many algorithms like Tower of Hanoi, tree traversals, stock span problems, and
histogram problems.
• String reversal is also another application of stack. Here one by one each character gets
inserted into the stack. So the first character of the string is on the bottom of the stack and
the last element of a string is on the top of the stack. After performing the pop operations
on the stack we get a string in reverse order.
75
76