Python Unit 1 To 5
Python Unit 1 To 5
III Functions: Function Definition – Function Call – Variable Scope and its
Lifetime-Return Statement. Function Arguments: Required Arguments,
Keyword Arguments, Default Arguments and Variable Length Arguments-
15
Recursion. Python Strings: String operations- Immutable Strings - Built-in
String Methods and Functions - String Comparison.
Modules: import statement- The Python module – dir() function – Modules and
Namespace – Defining our own modules.
IV Lists: Creating a list -Access values in List-Updating values in Lists- Nested lists
-Basic list operations-List Methods. Tuples: Creating, Accessing, Updating and
Deleting Elements in a tuple – Nested tuples– Difference between lists and 15
tuples. Dictionaries: Creating, Accessing,
Updating and Deleting Elements in a Dictionary – Dictionary Functions
and Methods - Difference between Lists and Dictionaries.
V Python File Handling: Types of files in Python - Opening and Closing files-
Reading and Writing files: write() and writelines() methods- append() method –
read() and readlines() methods – with keyword – Splitting words 15
– File methods - File Positions- Renaming and deleting files.
TOTAL HOURS 75
Develop program using selection statement, Work with Looping PO1, PO2, PO3,
CO2
and jump statements, Do programs on Loops and jump statements. PO4, PO5, PO6
Textbooks
1 Reema Thareja, “Python Programming using problem solving approach”, First Edition,
2017, Oxford University Press.
2 Dr. R. Nageswara Rao, “Core Python Programming”, First Edition, 2017, Dream tech
Publishers.
Reference Books
1. VamsiKurama, “Python Programming: A Modern Approach”, Pearson Education.
2. Mark Lutz, ”Learning Python”, Orielly.
3. Adam Stewarts, “Python Programming”, Online.
4. Fabio Nelli, “Python Data Analytics”, APress.
5. Kenneth A. Lambert, “Fundamentals of Python – First Programs”, CENGAGE
Publication.
Web Resources
1. https://www.programiz.com/python-programming
Python programming
Unit - I
Python
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics developed by
Guido van Rossum. It was originally released in 1991.
Python is used for server-side web development, software development, mathematics, and system scripting, and is
popular for Rapid Application Development and as a scripting or glue language to tie existing components because
of its high-level, built-in data structures, dynamic typing, and dynamic binding. Program maintenance costs are
reduced with Python due to the easily learned syntax and emphasis on readability. Additionally, Python's support of
modules and packages facilitates modular programs and reuse of code. Python is an open source community
language, so numerous independent programmers are continually building libraries and functionality for it.
Dynamic and strongly typed language: Python is strongly typed as the interpreter keeps
track of all variables types. It's also very dynamic as it rarely uses what it knows to limit variable usage.
Embeddable: Programmers can embed Python within their C, C++, COM, ActiveX, CORBA and Java
Programs to give „scripting „capability for users.
Extensive Libraries: Python has huge set of libraries that is easily portable across different platforms with
different operating systems.
Easy maintenance: Code Written in Python is easy to maintain.
Secure: This Programming language is secure for tampering. Modules can be distributed to prevent altering of
source code. Additionally, Security checks can be easily added to implement additional security features.
History of Python.
Python was first developed by Guido van Rossum in the late 80‟s and early 90‟s at the National Research
Institute for Mathematics and Computer Science in the Netherlands.
It has been derived from many languages such as ABC, Modula-3, C, C++, Algol-68, SmallTalk, UNIX shell
and other scripting languages.
Since early 90‟s Python has been improved tremendously. Its version 1.0 was released in 1991, which
introduced several new functional programming tools.
While version 2.0included list comprehension was released in 2000 by the Be Open Python Labs team.
Python 2.7 which is still used today will be supported till 2020.
Currently Python 3.6.4 is already available. The newer versions have better features like flexible string
representation e.t.c,
Although Python is copyrighted, its source code is available under GNU General Public License (GPL) like
that Perl.
Python is currently maintained by a core development team at the institute which is directed by Guido Van
Rossum.
These days, from data to web development, Python has emerged as very powerful and popular language. It
would be surprising to know that python is actually older than Java, R and JavaScript.
Applications of Python:
Embedded scripting language: Python is used as an embedded scripting language for various testing/ building/
deployment/ monitoring frameworks, scientific apps, and quick scripts.
3D Software: 3D software like Maya uses Python for automating small user tasks, or for doing more complex
integration such as talking to databases and asset management systems.
Web development: Python is an easily extensible language that provides good integration with database and other
web standards.
GUI-based desktop applications: Simple syntax, modular architecture, rich text processing tools and the ability to
work on multiple operating systems makes Python a preferred choice for developing desktop-based applications.
Image processing and graphic design applications: Python is used to make 2D imaging software such as
Inkscape, GIMP, Paint Shop Pro and Scribus. It is also used to make 3D animation packages, like Blender, 3ds
Max, Cinema 4D, Houdini, Light wave and Maya.
Scientific and Computational applications: Features like high speed, productivity and availability of tools, such
as Scientific Python and Numeric Python, have made Python a preferred language to perform computation and
processing of scientific data. 3D modeling software, such as FreeCAD, and finite element method software, like
Abaqus, are coded in Python.
Games: Python has various modules, libraries, and platforms that support development of games. Games like
Civilization-IV, Disney's Toontown Online, Vega Strike, etc. are coded using Python.
Enterprise and Business applications: Simple and reliable syntax, modules and libraries, extensibility, scalability
together make Python a suitable coding language for customizing larger applications. For example, Reddit which
was originally written in Common Lips, was rewritten in Python in 2005. A large part of Youtube code is also
written in Python.
Operating Systems: Python forms an integral part of Linux distributions.
Keyword in Python:
Keywords are the reserved words in Python. We cannot use a keyword as variable name, function name or any
other identifier.
Here's a list of all keywords in Python Programming.
There are 33 keywords in Python 3.3. This number can vary slightly in course of time.
All the keywords except True, False and None are in lowercase and they must be written as it is. The list of all the
keywords are given below.
as elif if or yield
assert else import pass
break except in raise
Literal Constants
Numeric Literals
Boolean Literals
String Literals
Literal Constants
In programming constants are referred to variables that cannot be changed.
Generally Literal constants are classified in to three types.
Numeric Literals
The value of a literal constant can be used directly in programs. For example, 7, 3.9, 'A', and "Hello" are literal
constants.
Numbers refers to a numeric value. You can use four types of numbers in Python program- integers, long integers,
floating point and complex numbers.
Numbers like 5 or other whole numbers are referred to as integers. Bigger whole numbers are called long integers.
For example, 535633629843L is a long integer.
Numbers like are 3.23 and 91.5E-2 are termed as floating point numbers.
Numbers of a + bj form (like -3 + 7j) are complex numbers.
Boolean Literals
A Literals Boolean type can have one of the two values- True or False.
String Literals
A string is a group of characters.
Using Single Quotes ('): For example, a string can be written as 'HELLO'.
Using Double Quotes ("): Strings in double quotes are exactly same as those in single quotes. Therefore, 'HELLO'
is same as "HELLO".
Using Triple Quotes (''' '''): You can specify multi-line strings using triple quotes. You can use as many single
quotes and double quotes as you want in a string within triple quotes.
Escape Sequences
Some characters (like ", \) cannot be directly included in a string. Such characters must be escaped by placing a
backslash before them.
Raw Strings
If you want to specify a string that should not handle any escape sequences and want to display exactly as specified
then you need to specify that string as a raw string. A raw string is specified by prefixing r or R to the string.
Example:
Data types
The variables can hold values of different type called Data Type.
Data type is a set of values and the allowable operations on those values.
Python has a great set of useful data types. Python's data types are built in the core of the language. They are easy to
use and straightforward.
Example a person age is stored in a number ,his name is made only with characters, and his address is made with
mixture of numbers and characters.
Python ha various standard data types to define the operations possible on them and storage method for each of
them.
Python supports the following five standard data types
1.Numbers
2.Strings
3.Lists
4.Tuple
5.Dictionary
6. Sets
Example: Program to display data of different types using variables and literal constants.
In Python , you can reassign variables as many times as you want to change the value stored in them. You may even
store value of one data type in a statement and other data type in subsequent statement. This is possible because
Python variables do not have specific types, i.e., we can assign integer to the variable, later we assign string to the
same variable.
Example:Program to reassign value to a variable
val = „Hello‟
print(val)
val = 100
print(val)
val=10.32
print(val)
Output
Hello
100
10.32
Multiple Assignments
Python allows programmers to assign single value to more than one variable simultaneously.
For example
>>>sum = flag = a = b = 0
In the above statement, all four integer variables are assigned a value 0.You can also assign different values to
multiple variables simultaneously as shown below
For example
Boolean Type
A variable of Boolean type can have one of the two values- True or False.
Similar to other variables, the Boolean variables are also created while we assign a value to them or when we use a
relational operator on them.
TUPLE
A tuple is similar to the list as it also consists of a number of values separated by commas and enclosed within
parentheses.
The main difference between lists and tuples is that you can change the values in a list but not in a tuple. This
means that while tuple is a read only data type, the list is not.
Lists
Lists are the most versatile data type of Python language.
A list consist of items separated by commas and enclosed within square brackets The values stored in a list are
accessed using indexes.
The index of the first element being 0 and n-1 as that of the last element, where n is the total number of elements in
the list. Like strings, you can also use the slice, concatenation and repetition operations on lists.
Example program to demonstrate operations on lists
print(list[1:3])
print(list[2:])
print(list * 2)
print(list + list1)
Output:
['a', 'bc', 78, 1.23]
a
['bc', 78]
[78, 1.23]
['a', 'bc', 78, 1.23, 'a', 'bc', 78, 1.23]
['a', 'bc', 78, 1.23, 'd', 78]
Dictionary
Python‟s dictionaries stores data in key-value pairs.
The key values are usually strings and value can be of any data type. The key value pairs are enclosed with curly
braces ({ }).
Each key value pair separated from the other using a colon (:). To access any value in the dictionary, you just need
to specify its key in square braces ([]).Basically dictionaries are used for fast retrieval of data.
SET
Set is an unordered collection of unique items.set is defined by values seperated by commas inside braces{ }.
For example
Sid={11,12,13,16}
Print(sid)
Identifiers
Identifiers are names given to identify something. This something can be a variable, function, class, module or
other object. For naming any identifier, there are some basic rules like:
The first character of an identifier must be an underscore ('_') or a letter (upper or lowercase).
The rest of the identifier name can be underscores ('_'), letters (upper or lowercase), or digits (0-9).
Identifier names are case-sensitive. For example, myvar and myVar are not the same.
Punctuation characters such as @, $, and % are not allowed within identifiers.
Examples of valid identifier names are sum, __my_var, num1, r, var_20, First, etc.
Examples of invalid identifier names are 1num, my-var, %check, Basic Sal, H#R&A, etc.,
5. Operators
Operators are special symbols in Python that carry out arithmetic or logical computation. The value that the
operator operates on is called the operand.
For example:
>>> 2+3
5
Here, + is the operator that performs addition. 2 and 3 are the operands and 5 is the output of the operation.
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication etc.
This operator will work on two operands.
Example: If a=100 and b=200 then look at the table below, to see the result of arithmetic operations.
Comparision (Relational) Operators
A Relational or Comparison operator checks the relationship between two operands. If the relation is true, it
returns 1; if the relation is false, it returns value 0
For Example assuming a=100 and b=2000,we can use the comparison operators on them as specified in the
following table.
Unary Operator
Unary operators act on single operands. Python supports unary minus operator.
Unary minus operator is strikingly different from the arithmetic operator that operates on two operands and
subtracts the second operand from the first operand.
When an operand is preceded by a minus sign, the unary operator negates its value.
For example, if a number is positive, it becomes negative when preceded with a unary minus operator. Similarly, if
the number is negative, it becomes positive after applying the unary minus operator. Consider the given example.
b = 10 a = -(b)
The result of this expression, is a = -10, because variable b has a positive value. After applying unary minus
operator (-) on the operand b, the value becomes -10, which indicates it as a negative value.
Bitwise Operators
As the name suggests, bitwise operators perform operations at the bit level.
These operators include bitwise AND, bitwise OR, bitwise XOR, and shift operators.
Bitwise operators expect their operands to be of integers and treat them as a sequence of bits.
The truth tables of these bitwise operators are given below.
Example: If a=60 and b=13 then look at the table below, to see the result of Bitwise operations.
Logical Operators
Logical operators are used to simultaneously evaluate two conditions or expressions with relational operators.
Logical AND (and) If expressions on both the sides (left and right side) of the logical operator are true, then the
whole expression is true.
For example, If we have an expression (a>b) and (b>c), then the whole expression is true only if both expressions
are true. That is, if b is greater than a and c.
Logical OR (or) operator is used to simultaneously evaluate two conditions or expressions with relational operators.
If one or both the expressions of the logical operator is true, then the whole expression is true.
For example, If we have an expression (a>b) or (b>c), then the whole expression is true if either b is greater than a
or b is greater than c.
Logical NOT (not) operator takes a single expression and negates the value of the expression. Logical NOT
produces a zero if the expression evaluates to a non-zero value and produces a 1 if the expression produces a zero.
In other words, it just reverses the value of the expression.
Identity Operators
is Operator: Returns true if operands or values on both sides of the operator point to the same object and false
otherwise.
Print(a is b)
Output
True
if a is b returns 1, if id(a) is same as id(b).
is not Operator: Returns true if operands or values on both sides of the operator does not point to the same object
and false otherwise.
For example,
A=10
B=20
Print(a is not b)
Output
true
if a is not b returns 1, if id(a) is not same as id(b).
5.8 Assignment Operators
Assignment operators are used in Python to assign values to variables.
a = 5 is a simple assignment operator that assigns the value 5 on the right to the variable a on the left.
There are various compound operators in Python like a += 5 that adds to the variable and later assigns the same. It
is equivalent to a = a + 5.
Assignment operators in Python
Operator Example Equivatent
to
= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
&= x &= 5 x=x&5
|= x |= 5 x=x|5
^= x ^= 5 x=x^5
>>= x >>= 5 x = x >> 5
Input Operation
To take input from the users, Python makes use of the input( ) function. The input( ) function prompts the user to
provide some information on which the program can work and give the result.
However, we must always remember that the input function takes user‟s input as a string.
Comments
Comments are the non-executable statements in a program. They are just added to describe the statements in the
program code.
Comments make the program easily readable and understandable by the programmer as well as other users who are
seeing the code. The interpreter simply ignores the comments.
In Python, a hash sign (#) that is not inside a string literal begins a comment. All characters following the # and up
to the end of the line are part of the comment
Indentation
Whitespace at the beginning of the line is called indentation. These whitespaces or the indentation are very
important in Python.
Where as indentation in code is only for readability in other programming languages.it is critical in python employs
indentation to denote a block of code.
Rules
Python default indentation spaces are four spaces
Indentation is not permitted on the first line of python code.
Python requires indentation to define statement blocks.
A block of code must have a consistent number of spaces.
To indent in Python, whitespaces are preferred over tabs. Also, use either whitespace or tabs to indent; mixing
tabs and whitespaces in indentation can result in incorrect indentation errors.
Example
j=1
while(j<= 5):
print(j)
j=j+1
Expressions
An expression is any combination of symbols (like variables, constants and operators) that represents a value.
In Python, an expression must have at least one operand (variable or constant) and can have one or more operators.
On evaluating an expression, we get a value. Operand is the value on which operator is applied.
Generally Expressions are divided into the following types
1. Constant Expressions: One that involves only constants.
Example: 8 + 9 – 2
2. Integral Expressions: One that produces an integer result after evaluating the expression.
Example:a = 10
3. Floating Point Expressions: One that produces floating point results.
Example: a * b / 2.0
4. Relational Expressions: One that returns either true or false value.
Example: c = a>b
5. Logical Expressions: One that combines two or more relational expressions and returns a value as True or False.
Example: x = y&z
7. Assignment Expressions: One that assigns a value to a variable.
Example: c = a + b or c = 10
Example Program:
Give the output for the following statements)
a = 20
b = 10
c = 15
d=5
print ("a:%d b:%d c:%d d:%d" % (a,b,c,d ))
e = (a + b) * c / d
d) is ", e)
e = a + (b * c) / d
print ("Value of a + (b * c) / d is ", e)
Output:
a:20 b:10 c:15 d:5
Value of (a + b) * c / d is 90.0
Value of ((a + b) * c) / d is 90.0
Value of (a + b) * (c / d) is 90.0
Value of a + (b * c) / d is 50.0
Operator Precedence
The operator precedence in Python are listed in the following table.
It is in descending order, upper group has higher precedence than the lower ones.
Operator precedence rule in Python
Operators Meaning
() Parentheses
** Exponent
+x, -x, ~x Unary plus, Unary minus, Bitwise NOT
*, /, //, % Multiplication, Division, Floor division,
Modulus
+, - Addition, Subtraction
<<, >> Bitwise shift operators
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
==, !=, >, >=, <, <=, is, is not, in, not in Comparison, Identity, Membership
operators
Typecodes are alphabetic representations that are used to define the type of value the array is going to store. Some
common typecodes are:
Typecode value
To access an array elemt, you need to specify the index number. Indexing starts at index 0
Hence, the index number is always one less than the length of the array.
Example
Array methods
Insert()
insert()function is used to insert an element to the array at a specific index or position.
It will take pos, and value as its parameters
where pos variables tell the position and value is the value need to insert into array.
Syntax
Arrayname.insert(index,value)
Example
a = array('i',[1,2,3,4])
a. insert(2,9)
print("Array after inserting 9 is", a)
append(value)
append() function is used to add value or append a value to the existing array in the end. It will take the value
which we want to add as an argument.
Syntax
Arrayname.append(value)
Ex
a. append(6)
print(a)
remove(value)
remove() function is used to remove the given element from the array. It will take value to remove as an argument
and removes the element from the array and it won’t display the element.
Syntax
Remove(value)
example
remove(9)
print(a)
extend(arr)
extend() function is used to add an array of values at the end of the existing array created. It will take an array of
values or an array as its input argument.
Syntax
Arrayname.extend([array values])
a. extend([7,5,8])
print(a)
pop()
The above function, pop() is used to remove an element from the array. It can take the argument as a position of the
element we want to remove or by default it removes the element at the last index.
Ex:
a.pop()
a.pop(4)
It removes the element at 4th index position in the array and displays element
reverse()
To Reverses the order of an array list
Ex:
a.reverse()
count(value)
The above function, count() will tell the total number of occurrences of the given value in the array. It will take a
value as an argument to it to know the total number of occurrences.
a. extend([2,1,3,2,1])
a.count(2)
Type conversion
Python defines type conversion functions to directly convert one data type to another
There are two types of Type Conversion in Python:
1. Implicit Type Conversion
2. Explicit Type Conversion
In Implicit type conversion of data types in Python, the Python interpreter automatically converts one data type to
another .this is known as type coercion.
For example
Converting int to float
Python promotes the conversion of the lower data type(int) to the higher data type(float) to avoid data loss.
a=123
b=45.6
c=a+b
print(“value=”,c)
output
168.6
This type of conversion is also called typecasting because the user casts(changes) the datatype of the objects.
There is a risk of data loss since we are forcing an expression to be changed in some specific data loss
Example
S=’12’
a=23
S=int(s)
C=s+a
Print(“sum=”,c)
Function Description
Conditional statement
A program’s control flow is the order in which the program’s code executes.
The control flow of a Python program is regulated by conditional statements, loops, and function calls.
Sequential
Selection
Repetition
Sequential
Sequential statements are a set of statements whose execution process happens in a sequence. The problem
with sequential statements is that if the logic has broken in any one of the lines, then the complete source
code execution will break.
Example
a=10
b=20
c=a-b
Print(c)
The selection statement allows a program to test several conditions and execute instructions based on which
condition is true.Some decision control statements are:
if
if-else
nested if
if-elif-else
if Statement:
An if statement is a selection control statement which is based on the valueof a given Boolean Expression.
Syntax:
if test_expression:
statement 1
.....
statement n
statement x
Flowchart:
Example
X=10
If(x>0):
x=x+1
Print(x)
if-else –
The if-else statement evaluates the condition and will execute the statement block1 if if the test condition
is True, but if the condition is False, then the statement block2 of else block is executed.
Syntax:
if (test expression):
statement_block 1
else:
statement_block 2
statement x
Flowchart:
Example
n=5
If(n%2==0):
Print(“Even number”)
else:
Print(“Odd number”)
In the following code example, the else body will execute as 5 modulo 2 is not equal to 0.
Nested if Statements :
To perform more complex checks, if statements can be nested, that is, canbe placed one inside the other.
In such a case, the inner if statement is the statement part of the outer one.
Nested if statements are used to check if more than one conditions aresatisfied.
Syntax
If(test expression1):
Statement
Statement
if-elif-else Statement :
The if-elif-else construct works in the same way as a usual if-else statement.
A series of if and elif statements have a final else block, which is executed if none of the if or elif
expressions is True.
Syntax:
statement block1
statement block2
. . . . . . . . . . . . . . ..
statement block N
else:
statement block X
Flowchart:
Example
a=10
b=15
c=20
Else
Iterative statements are decision control statements that are used to repeat the execution of a list of statements.
while loop
for loop.
while Loop :
The While loop provides a mechanism to repeat one or more statements while a particular condition is TRUE.
Statement block
Statement y
In while loop, the condition is tested before any of the statements in the statement block is executed.
If the condition is TRUE, only then the statements will be executed otherwise if the condition is False, the
control will jump to statement y, that is the immediate statement outside the while loop block.
Flowchart:
Example
S=0
While(n>0):
r=n%10
s=s*10+r
n=n//10
for Loop:
For loop provides a mechanism to repeat a task until a particular condition is True. It is usually known as a
determinate or definite loop because the programmer knows exactly how many times the loop will repeat.
The for...in statement is a looping statement used in Python to iterate over a sequence of objects.
Syntax
Syntax:
statement block
FLOWCHART
o The range( ) function is a built-in function in Python that is used to iterate over a sequence of numbers.
Syntax
range(beg,end,[step])
The range( ) produces a sequence of numbers starting with beg (inclusive) and ending with one less than the
number end.
The step argument is option (that is why it is placed in brackets). By default, every number in the range is
incremented by 1 but we can specify a different increment using step. It can be both negative and positive, but
not zero.
EXAMPLE
for i in range(1,5):
Print(i,end= “ “)
Output
1 2 3 4
Example
for I in range(1,10,2)
Print(I,end=” “)
Output
1 3 5 7 9
If range( ) function is given a single argument, it produces an object with values from 0 to argument-1. For
example: range(10) is equal to writing range(0, 10).
If range( ) is called with two arguments, it produces values from the first to the second. For example, range(0,
10) gives 0-9.
If range( ) has three arguments then the third argument specifies the interval of the sequence produced. In this
case, the third argument must be an integer.
Nested Loops :
Python allows its users to have nested loops, that is, loops that can be placed inside other loops.
Although this feature will work with any loop like while loop as well as for loop.
A for loop can be used to control the number of times a particular set of statements will be executed.
Another outer loop could be used to control the number of times that a whole loop is repeated.
Loops should be properly indented to identify which statements are contained within each for statement.
Example:
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Print( )
For j in range(1,i+1)
Print(j,end=” “)
TheBreak Statement:
The break statement is used to terminate a loop and skip the next code
after the loop
When compiler encounter a break statement, the control passes to the statement that
follows the loop in which the break statement appears.
syntax
Break
Example:Programtodemonstratethebreakstatement
When i is equal to 5 the break statement terminates the loop.
It is used to skip the current iteration of the loop and the control flow of the
program goes to the next iteration.
Syntax
Continue
Example
For I in range(1,10) :
If(I==5):
Continue
Print(I)
Print(“done”)
Output
12346789
Done
In Python you can have the else statement associated with a loop
statements.
If the else statement isused with a for loop,the else statement is executed when the
loop has completed iterating.
UNIT- III
FUNCTIONS:
Understanding, coding and testing multiple separate functions are far easier than doing the same for one huge
function.
When a big program is broken into comparatively smaller functions, then different programmers working on that
project can divide the workload by writing different functions.
All the libraries in Python contain pre-defined and pre-tested functions which the programmers are free to use
directly in their programs, without worrying about their code details.
Like Python libraries, programmers can also make their own functions and use them from different points in the
main program or any other program that needs its functionalities.
TYPES OF FUNCTIONS
FUNCTION DEFINITION
Function header
Function body
syntax
Def function_name(variable1,variable2,….) :
Documentation string
Function body
Return[ expression]
. Parameters or arguments that the function accept are placed within parentheses.
. A function may have a return[expression] statement. That is, the return statement is optional. You can assign the
function name to a variable.
Example
For i in range(4):
Print(“hello world”)
func()
Function Call
Defining a function means specifying its name, parameters that are expected, and the set of instructions. The
function call statement invokes the function.
When a function is invoked the program control jumps to the called function to execute the statements that are a
part of that function. Once the called function is executed, the program control passes back to the calling function.
When a function is called,the interpreter checks that the number and type of arguments are used in the function call
Function Parameters
A function can take parameters which are nothing but some values that are passed to it so that the function can
manipulate them to produce the desired result.
Function name and the number and type of arguments in the function call must be same as that given in the function
definition.
If the data type of the argument passed does not matches with that expected in function then an error is generated.
Example
Def total(a,b) :
Result=a+b
Print(“sum= “,result)
total(a,b)
The scope of variable is a region of the program where a variable is visible or accessible. Lifetime of a variable is
the duration for which a variable exists in the memory. The existence and accessibility depend on the declaration of
a variable in the program.
For example, the lifetime of a variable declared inside a function is as long as the function is alive. When the
execution of function body is finished, then the variable defined inside a function will destroy.
The location where we can find a variable and also access it if required is called the scope of a variable.
There are three basic types of scope of variables in Python. They are:
Global scope
Local scope
Nonlocal Keyword
Local variables are those that are initialized within a function and are unique to that function. It cannot be
accessed outside of the function. Let’s look at how to make a local variable.
def f():
# local variable
s = "I love Geeksforgeeks"
print(s)
# Driver code
f()
Global variables are the ones that are defined and declared outside any function and are not specified to any
function. They can be used by any part of the program.
Example:
def f():
print(s)
# Global scope
s = "I love Geeksforgeeks"
f()
In Python, the nonlocal keyword is used in the case of nested functions. This keyword works similarly to the
global, but rather than global, this keyword declares a variable to point to the variable of an outside enclosing
function, in case of nested functions.
print("Value of a using nonlocal is : ", end="")
def outer():
a=5
def inner():
nonlocal a
a = 10
inner()
print(a)
outer()
RETURN STATEMENT
A return statement is used to end the execution of the function call and “returns” the result to the caller.
SYNTAX
Return [Expression ]
Example
Def cube(x):
Return(x*x*x)
Num=10
Print(“cube of”, Num, “=”,result)
Moreondefiningfunctions:
Inthissectionwewilldiscusssomemorewaysofdefiningafunction.
1. Requiredarguments
2. Keywordarguments
3. Defaultarguments
4. Variable-lengtharguments
RequiredArguments
Example:
KeywordArguments
When we call a function with some values,the values are assigned to the arguments
based on their position. Python also allow functions to be called using keyword
arguments in which the order(orposition) of the argument can be changed.The values are
not assigned to arguments according to their position but based on their
name(orkeyword).
Keywordargumentsarebeneficialintwocases.
• First,ifyouskiparguments.
• Second,ifinthefunctioncallyouchangetheorderofparameters.Example:
DefaultArguments
Python allow users to specify function arguments that can have default values.This means that
a function can be called with fewer arguments than it is defined to have.
That is,if the function accepts three parameters,but function call provide only two
arguments, then the third parameter will be assigned the default (already specified)value.
The default value to an argument is provided by using the assignment
operator(=).Userscanspecifyadefaultvalueforoneormorearguments.
Example:
Variable-lengthArguments
In some situations,it is not known in advance how many arguments will be passed to a
function.In such cases,Python allows programmers to make function calls with arbitrary(orany)
number of arguments.
When we use arbitrary arguments or variable length arguments, then the function
definition use an asterisk(*) before the parameter name.The syntax for a function using
variable arguments can be given as,
RecursiveFunctions
A recursive function is defined as a function that calls smaller version of its task until a
final call is made which does not require a call
toitself.Everyrecursivesolutionhastwomajorcases,whichareasfollows:
• basecase,in which the problem is simple enough to be solved directly with out
making any further calls to the same function.
• recursivecase,in which first the problemat hand is divided into simpler sub
parts.Recursion utilized divide and conquer technique of problem solving.
Example
DocumentationStrings
.
Modules
A module may containd definition for many variable sand functions.When you import a
module,you can use any variable or function defined in that module. But if you want to
use only selected variable sor functions,then you can use the from...import
statement.Forexample, in the aforementioned program you are using only the path variable in
the sysmodule,so you could have better written from sysimportpath.
A module may contain definition for many variable sand functions.When you import a module,you can
use any variable or function defined in that module. But if you want to use only selected variables
or functions, then you can use the from...import statement.Forexample,in the a for mentioned program
you are using only the path variable in the sysmodule,so you could have better written from
sysimportpath.
Example:
Every Python program is a module,that is,every file that you save as.py extension is a
module.
Modules should be placed in the same directory as that of the program in which it is
Thedir()function
dir() is a built-in function that list the identifiers defined in a module. These identifiers may
include functions, classes and variables.If no name is specified,thedir() will return the list of
names defined in the current module.
ThePythonModule:
We have seen that a Pythonmodule is a file that contain ssome definitions and
statements.When a Python file is executed directly,it is considered the main
module of a program.
Main modules are given the special name main and provide the basis for
acomplete Pythonprogram.
The main module may import any number of other modules which may in turn
import other modules.But the main moduleof a Python program cannot be
imported into other modules.
ModulesandNamespaces
A namespace is a container that provide sanamed context for identifiers. However,in some
situations we need to have same name identifiers.Tocaterto such situations, namespaces is
the keyword. Namespaces enable programs to avoid potential name clashes by associating
each identifier with the namespace from which it originates.
Example:
Local,Global,andBuilt-inNamespaces
During a program‟s execution, there are three main namespaces that are referenced -
thebuilt-innamespace,theglobalnamespace,andthelocalnamespace.Thebuilt -
innamespace,asthenamesuggestscontainsnamesofallthebuilt-
infunctions,constants,etcthatarealreadydefinedinPython.Theglobalnamespacecontainsident
ifiers of the currently executing module and the local namespace has
identifiersdefinedinthecurrentlyexecutingfunction(ifany).
WhenthePythoninterpreterseesanidentifier,itfirstsearchesthelocalnamespace,thentheglobal
namespace, and finallythebuilt-innamespace. Therefore,
iftwoidentifierswithsamenamearedefinedinmorethanoneofthesenamespaces,itbecomesmasked
.
ModulePrivateVariables
In Python, all identifiers defined in a module are public by default.This meanst all
identifiers are accessible by any other module that imports it.But,ifyou want some
variables or functions in a module to be privately used within the module,but not
to be accessed from outside it,thenyou need to declare those identifiers as private.
In Python identifiers whose name starts with two under scores()are known as private
identifiers.Theseidentifierscanbeusedonlywithinthemodule.Innoway,theycanbeaccess
edfromoutsidethemodule.
Therefore,whenthemoduleisimportedusingtheimport*formmodulename,alltheidentifie
rsofamodule‟snamespaceisimportedexcepttheprivateones(onesbeginningwithdoub leun
derscores).Thus,privateidentifiersbecomeinaccessiblefromwithintheimportingmodule.
AdvantagesofModules:
Strings
Concatenating,AppendingandMultiplyingStrings
Example:Programtoconcatenatetwostringsusing+operator
StringsareImmutable
Python strings are immutable which means that once created they cannot be
changed. Whenever you try to modify an existing string variable, a new string is
created.
Example:
StringFormattingOperator
LISTS
The most basic data structure in Python is the sequence. Each element of a sequence is assigned a number - its
position or index. The first index is zero, the second index is one, and so forth.
There are certain things you can do with all sequence types. These operations include indexing, slicing, adding,
multiplying, and checking for membership.
Creating a List:
Creating a list is as simple as putting different comma-separated values between square brackets. Similar to string
indices, list indices start at 0, and lists can be sliced, concatenated and so on.
Syntax:
List_variable = [val1,val2,…]
Example:
1)list_A =[1,2,3,4]
print(list_A)
Output [1,2,3,4]
2)list_C=[„Good”,”Going”]
print(list_C)
Output [‘Good’,’Going’]
Accessing values in lists:
Similar to strings, lists can be sliced and concatenated
To access values in lists, square brackets are used to slice along with index or indices to get value stored at that
index.
Syntax
s=list[start:stop:step]
For Example:
Example 1
num_list=[1,2,3,4,5,6,7,8,9,10]
print(“num_list is:”,num_list)
print(“first elemnent in the list is”,num_list[0])
print(“num_list[2:5]=”,num_list[2:5])
print(“num_list[::2]=”,num_list[::2])
print(“num_list[1::3]=”,num_list[1::3])
Output:
num_list is: [1,2,3,4,5,6,7,8,9,10]
first elemnent in the list is 1
num_list[2:5]= [3,4,5]
num_list[::2]= [1,3,5,7,9]
num_list[1::3]= [2,5,8]
Append()
The append() method adds elements at the end of the list. This method can only add a single element at a time. You
can use the append() method inside a loop to add multiple elements.
example
extend()
The extend() method adds more than one element at the end of the list. Although it can add more than one element,
unlike append(), it adds them at the end of the list like append().
Code:
insert()
The insert() method can add an element at a given position in the list. Thus, unlike append(), it can add elements at
any position, but like append(), it can add only one element at a time. This method takes two arguments. The first
argument specifies the position, and the second argument specifies the element to be inserted.
Code:
remove()
The remove() method removes an element from the list. Only the first occurrence of the same element is removed
in the case of multiple occurrences.
Code:
pop()
The method pop() can remove an element from any position in the list. The parameter supplied to this method is the
element index to be removed.
Code:
Code:
Code:
Code:
Code:
myList =[1,2,3,4,5,6,7]
print(min(myList))
print(max(myList))
count()
The function count() returns the number of occurrences of a given element in the list.
Code:
myList =[1,2,3,4,3,7,3,8,3]
print(myList.count(3))
concatenate
The concatenate operation merges two lists and returns a single list. The concatenation is performed using the +
sign. It’s important to note that the individual lists are not modified, and a new combined list is returned.
Code:
Code:
Tuple Definition:
1.A tuple is a sequence of immutable objects. That is, you can change the value of one or more items in a list;
you cannot change the values in a tuple.
2. Tuples use parenthesis to define its elements. Whereas lists use square brackets.
Creating a Tuple:
Creating a tuple is as simple as putting different comma-separated values. Optionally you can put these comma-
separated values between parentheses.
Syntax:
Tup1=(val1,val2,….)
Where val (or values) can be an integer, a floating number, a character, or a string.
Examples:
print(Tup1)
output: note: no ouput will be displayed.
print(Tup1)
Output: 5
print (Tup1)
print(Tup2)
print(Tup3)
print(Tup4)
print(Tup5)
Output:
1,2,3,4,5,
a‟,‟b‟,‟c‟,‟d‟ „abc‟,‟def‟,‟ghi‟
1.2,2.3,3.4,4.5,5.6 1,
‟abc‟,2.3,‟d‟
print(„a‟,”bcd”,2,4.6)
a,b=10,20
print(a,b)
Output: 10 20
Example :
1) Tup1=(1,2,3,4,5,6,7,8,9,10)
print(“Tup[3:6]=”,Tup1[3:6])
print(“Tup[:8]=”,Tup1[:4])
print(“Tup[4:]=”,Tup1[4:])
print(“Tup[:]=”,Tup1[:])
Output:
Tup[3:6]=(4,5,6)
Tup[:8]=(1,2,3,4)
Tup[4:]=5,6,7,8,9,10)
Tup[:]=(1,2,3,4,5,6,7,8,9,10)
The tuple values can be accessed using square brackets:
2) Tuple =(1,2,3,4,5.5,‟str‟)
Input:
1.print tuple
2.print tuple[5]
3.print tuple[1:5]
Output:
1. 1,2,3,4,5.5,‟str‟
2. ‟str‟
3. 2,3,4,5.5
Updating tuples:
As we all know tuples are immutable objects so we cannot update the values but we can just extract the
values from a tuple to form another tuple.
Example:
1. Tup1=(1,2,3,4,5)
Tup2=(6,7,8,9,10)
Tup3=Tup1+Tup2
print(Tup3)
Output: (1,2,3,4,5,6,7,8,9,10) 2)
2.Tup1=(1,2,3,4,5)
Tup2=(„sree‟,‟vidya‟,‟ram‟)
Tup3=Tup1+Tup2
print Tup3
Output: (1,2,3,4,5,‟sree‟,‟vidya‟,‟ram‟
Deleting a single element in a tuple is not possible as we know tuple is a immutable object. Hence there
is another option to delete a single element of a tuple i.e..,you can create a new tuple that has all elements in
your tuple except the ones you don‟t want.
Example:
Tup1=(1,2,3,4,5)
del Tup1[3]
print Tup1
Output: Traceback (most recent call last): File "test.py", line 9, in del Tup1[3] Type error: „tuple‟
object doesn‟t support item deletion
however, you can always delete the entire tuple by using del statement.
Tup1=(1,2,3,4,5)
del Tup1
print Tup1
Output: Traceback (most recent call last): File "test.py", line 9, in print Tup1; NameError: name
'Tup1' is not define
Nested Tuples
A nested tuple is a Python tuple that has been placed inside of another tuple.
Using the + operator and "," during initialization
The list is better for performing operations, such as A Tuple data type is appropriate for accessing
3
insertion and deletion. the elements
5 Lists have several built-in methods Tuple does not have many built-in methods.
6 Unexpected changes and errors are more likely to occur In a tuple, it is hard to take place.
Dictionary:
It is a data structure in which we store values as a pair of key and value.
Each key is separated from its value by a colon (:), and consecutive items are separated by commas.
The entire items in a dictionary are enclosed in curly brackets ({}).
Syntax:
dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3}
If there are many keys and values in dictionaries, then we can also write just one key-value pair on a line to
make the code easier to read and understand. This is shown below.
dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3 , ….}
Keys in the dictionary must be unique and be of any immutable data type (like Strings, numbers, or tuples), there is
no strict requirement for uniqueness and type of values.
Values of a key can be of any type.
Dictionaries are not Sequences, rather they are mappings.
Mappings are collections of objects that are store objects by key instead of by relative position.
Creating a Dictionary:
o Note that one key value pair is separated from the other using a comma.
Example:
d= {'roll_no':'18/001','Name:':'Arav','Course':'B.tech'}
print(d)
Accessing Values:
Example:
print('d[Name]:',d['Name'])
print('d[course]:',d['Course'])
print('d[roll_no]:',d['roll_no'])
output:
To add a new entry or a key-value pair in a dictionary, just specify the keyvalue pair as you had done for the
existing pairs.
Syntax:
Example:
Modifying an Entry:
To modify an entry, just overwrite the existing value as shown in the following example: 1. program
to modify an item in the dictionary
d={'Name': 'Arav', 'Course': 'B.tech', 'roll_no': '18/001'} d['marks']=99 #new entry
print('d[Name]:',d['Name'])
print('d[course]:',d['Course'])
print('d[roll_no]:',d['roll_no'])
print('d[marks]:',d['marks'])
d[‘Course’]=’BCA’ #Updated entry
print('d[course]:',d['Course'])
Output:
d[Name]: Arav
d[course]: B.tech
d[roll_no]: 18/001
d[marks]: 99
d[course]: BCA
Deleting Items :
You can delete one or more items using the del keyword.
To delete or remove all the items in just one statement, use the clear () function.
Finally, to remove an entire dictionary from the memory, we can gain use the del statement as del
Dict_name.
The syntax to use the del statement can be given as,
del dictionary_variable[key]
Example:
1.Program to demonstrate the use of del statement and clear() function
Keys must have unique values.
Not even a single key can be duplicated in a dictionary. If you try to add a duplicate key, then the last assignment
is retained.
In a dictionary, keys should be strictly of a type that is immutable. This means that a key can be of strings,
numbers, or tuple type but it cannot be a list which is mutable.
In case you try to make your key of mutable type, then a Type error will be granted.
Tuples can be used as keys only if they contain immutable objects like strings, numbers, or other tuples.
If a tuple used as key contains any mutable object either directly or indirectly, then an error is generated.
The in keyword can be used to check whether a single key is present in the dictionary
The keys() method of dictionary returns a list of all the keys used in the dictionary in a arbitrary order. The sorted()
function is used to sort the keys as shown below:
d={'roll_no':653,'name':'python','course':'b.tech'}
print(sorted(d.keys()))
output:
1.Program to access
d={'roll_no':653,'name':'python','course':'b.tech'}
print("KEYS:",end=' ')
for key in d: print(key,end=' ')
print("\n VALUES:",end=' ')
for val in d.values():
print(val,end=' ')
print("\n Dictionary:",end=' ')
for key,val in d.items():
print(key,val,end=';')
output:
KEYS: course name roll_no
VALUES: b.tech python 653
Dictionary: course b.tech;name python;roll_no 653;
Dictionary Functions
len(dict): Returns the length (i.e., the number of key-value pairs) of the dictionary.
dict[key]: Returns the value associated with the specified key. If the key is not found, a KeyError is raised.
dict.get(key, default=None): Returns the value associated with the specified key, or the default value if the
key is not found. If the default parameter is not specified, it defaults to None.
dict.items(): Returns a list of all the key-value pairs in the dictionary, as tuples.
dict.pop(key, default=None): Removes the key-value pair with the specified key from the dictionary and
returns the value. If the key is not found and the default is not specified, a KeyError is raised.
dict.popitem(): Removes and returns an arbitrary key-value pair from the dictionary. If the dictionary is
empty, a KeyError is raised.
dict.update(other_dict): Updates the dictionary with key-value pairs from another dictionary. If a key
exists in both dictionaries, the value in the other dictionary overwrites the value in the original dictionary.
dict.fromkeys(seq, value=None): Creates a new dictionary with keys from the specified sequence (e.g., a
list, tuple, or set) and values set to the specified value. If the value parameter is not specified, it defaults to None.
Difference between a List and a Dictionary
The following table shows some differences between a list and a dictionary in Python:
List Dictionary
The list is a collection of index value The dictionary is a hashed structure of the key and value
pairs like that of the array in C++. pairs.
The list is created by placing elements in [ The dictionary is created by placing elements in { } as
] separated by commas “,” “key”:”value”, each key-value pair is separated by commas “, “
The elements are accessed via indices. The elements are accessed via key-value pairs.
Introduction to Files:
When a program is being executed, its data is stored in RAM. Though RAM can be accessed faster by the
CPU,it is also volatile, which means when the program ends, or the computer shuts down, all the data is lost.
If you want to use the data in future,then you need to store this data on a permanent or nonvolatile storage
media such as hard disk, USB drive and DVD e.t.c.,
A file is a collection of data stored on a secondary storage device like hard disk.
A file is basically used because real-life applications involve large amounts of data and in such situations
the console oriented I/O operations pose two major problems:
First, it becomes cumbersome and time consuming to handle huge amount of data through terminals.
Second, when doing I/O using terminal, the entire data is lost when either the program is terminated or
computer is turned off. Therefore, it becomes necessary to store data on a permanent storage (the disks) and
read whenever necessary, without destroying the data.
Binary Files
A binary file is a file which may contain any type of data, encoded in binary form for computer
storage and processing purposes. It includes files such as word processing documents, PDFs,
images, spreadsheets, videos, zip files and other executable programs.
Like a text file, a binary file is a collection of bytes. A binary file is also referred to as a character
stream with following two essential differences.
A binary file does not require any special processing of the data and each byte of data is
transferred to or from the disk unprocessed.
Python places no constructs on the file, and it may be read from, or written to,in any manner the
programmer wants. While text files can be processed sequentially, binary files, on the other
hand, can be either processed sequentially or randomly depending on the needs of the
application.
File Operations
When we want to read from or write to a file we need to open it first. When we are done, it needs to be closed, so
that resources that are tied with the file are freed.
1. Open a file
Opening A File
Before reading from or writing to a file, you must first open it using Python‟s built-in open() function.
This function creates a file object, which will be used to invoke methods associated with it.
Where file_name is a string value that specifies name of the file that you want to access.
access_mode indicates the mode in which the file has to be opened, i.e., read, write, append, etc.
File=open(“file1.txt”,”rb”)
Print(file)
Access modes
Python supports the following access modes for opening a file those are
1. Read Only (‘r’) : Open text file for reading. The handle is positioned at the beginning of the file. If the
file does not exists, raises the I/O error. This is also the default mode in which a file is opened.
2. Read and Write (‘r+’): Open the file for reading and writing. The handle is positioned at the beginning
of the file. Raises I/O error if the file does not exist.
3. Write Only (‘w’) : Open the file for writing. For the existing files, the data is truncated and over -written.
The handle is positioned at the beginning of the file. Creates the file if the file does not exist.
4. Write and Read (‘w+’) : Open the file for reading and writing. For an existing file, data is truncated and
over-written. The handle is positioned at the beginning of the file.
5. Append Only (‘a’): Open the file for writing. The file is created if it does not exist. The handle is
positioned at the end of the file. The data being written will be inserted at the end, after the existing data.
6. Append and Read (‘a+’) : Open the file for reading and writing. The file is created if it does not exist.
The handle is positioned at the end of the file. The data being written will be inserted at the end, after the
existing data.
7. Read only(rb) : this mode opens only for binary file. This file pointer only is placed at the beginning of
the file.
name: Return the name of the file. It is a read-only attribute and may not be present on all file-like objects.
If the file object was created using the open() function, the file’s name is returned. Otherwise, some string
indicates the source of the file object is returned.
encoding: It returns the encoding this file uses, such as UTF-8. This attribute is read-only. When Unicode
strings are written to a file, they will be converted to byte strings using this encoding. It may also be None. In
that case, the file uses the system default encoding for converting Unicode strings.
mode: Returns the file access mode used while opening a file.
closed: Returns True if a file is closed. It is a boolean value indicating the current state of the file object.
newline: Files opened in universal newline read mode keep track of the newlines encountered while reading
the file. The values are ‘\r’, ‘\n’, ‘\r\n’, None (no newlines read yet), or a tuple containing all the newline
Closing A File
The close() method is used to close the file object. Once a file object is closed, you cannot further read from or
write into the file associated with the file object.
While closing the file object the close() flushes any unwritten information.
Although, Python automatically closes a file when the reference object of a file is reassigned to another file, but as
a good programming habit you should always explicitly use the close() method to close a file.
fileObj.close()
The close() method frees up any system resources such as file descriptors, file locks, etc. that are associated with
the file.
Once the file is closed using the close() method, any attempt to use the file object will result in an error. Example2:
file = open('File1.txt','wb')
print('File is closed:',file.closed)
file.close()
print('File is closed',file.closed
print(file.read())
Output:
in print(file.read())
io.UnsupportedOperation: rea
Writing A File
Of course this string may include numbers, special characters or other symbols.
While writing data to a file, you must remember that the write() method does not add a newline character ('\n') to
the end of the string.
fileObj.write(string)
Example:
file=open('data.txt','w')
file.close()
Output:
writeline() method:
file=open('data.txt','w')
file.writelines(lines)
file.close( )
Output:
append() method:
Once you have stored some data in a file,you can always open that file again to write more data or append data
to it
To append a file, you must open it using „a‟ or „ab‟ mode depending on whether it is text file or binary file.
Note that if you open a file with „w‟ or „wb‟ mode and then start writing data into it, then the existing
contents would be overwritten.
Example:
file=open('data.txt','a')
file.close()
Reading A File
The read() method is used to read a string from an already opened file.
As said before, the string can include, alphabets, numbers, characters or other symbols.
fileObj.read([count])
count is an optional parameter which if passed to the read() method specifies the number of bytes to be read
from the opened file.
The read() method starts reading from the beginning of the file and if count is missing or has a negative
value then, it reads the entire contents of the file (i.e., till the end of file)
Example1:
file=open('data.txt','r')
print(file.read(8))
file.close()
Output: hellocse
Example2:
file=open('data.txt','r')
file.close()
readline() Method
This method returns an empty string when end of the file has been reached.
Example
file=open('data.txt','r')
print('firtsline:',file.readline())
print('second line:',file.readline())
print('third line:',file.readline())
file.close()
third line
readlines() Method
Example:Programtodemonstratereadlines()function
file=open('data.txt','r')prin
data.txt
t(file.readlines())file.clos
e() hellocsehope to enjoylearningpython
['hellocsehopetoenjoylearningpythonprogramming\n','Haveaniceday']
4.4.1 ist()Method
list() method is also used to display entire contents of the file.you need to
passthefileobjectasanargumenttothelist()method.
Example:Program todisplaythecontentsofthefiledata.txtusingthelist()
methodfile=open('data.tx
t','r')print(list(file))file.cl data.txt
ose()
hellocsehope to enjoylearningpython
Output:
programmingHaveanice day
['hellocsehopetoenjoylearningpythonprogramming\n','Haveaniceday']
4.4.2 Openingafileusingwithkeyword:
It is good programming habit to use the with keyword when working with file
objects.
Thishastheadvantagethatthefileisproperlyclosedafteritisusedevenifanerroroccursduringr
eadorwriteoperationorevenwhenyouforgettoexplicitlyclosethefile.
4.4.3 SplittingWords:
Python allows you to read line(s) from a file and splits the line (treated as
astring)basedonacharacter.Bydefault,thischaracterisspacebutyoucanevenspecify
anyothercharactertosplitwordsinthestring.
Example:
Program to split the line into series of words and use space to perform the split operation
withopen('data.txt','r')asfile:line=file.readline()words=line.split()print(words)
open('data.txt','r')asfile:line=file.readline()words=line.split()print(words)
Output:
['hellocsehope','to','enjoylearningpython','programming']
FileMethods:
4.1 FilePositions:
With every file, the file management system associates a pointer often
knownasfilepointerthatfacilitatesthemovementacrossthefileforreadingand/orwriting
data.
The filepointer specifiesa locationfromwherethecurrent read
orwriteoperationisinitiated.Oncetheread/writeoperationiscompleted,thepointerisau
tomaticallyupdated.
Pythonhasvariousmethodsthattellsorsetsthepositionofthefilepointer.
Forexample,thetell()methodtellsthecurrentpositionwithinthefileatwhichthenextreadorwr
iteoperationwilloccur.Itisspecifiedasnumberofbytesfromthebeginningofthefile.
When you just open a file for reading, the file pointer is positioned at
location0,whichisthebeginningofthefile.
Thesyntaxforseek() functionis
seek(offset[,from])
The offset argument indicates the number of bytes to be moved and the from
argument specifies the reference position from where the bytes are to be moved.
File1.txt
HelloAll,
Hopeyouareenjoyinglearningpython
Example:Programtorenamefile‘File1.txt’to‘student.txt’
Example:Programtodeleteafilename