Unit Iv
Unit Iv
Unit Iv
UNIT-IV
FUNCTIONS
If the problem is simple, the steps involved are less, the number of lines code written are few for
solving problem and is very easy to understand and also to identify mistakes, if any, in them.
On the other hand, if the problem is complex, the steps involved are huge and have thousands of
lines of code and become difficult to understand. Sometimes we need to write a particular block
of code that needs to be executed more than once in our program to specify one or more actions
to be performed for the large program. An error in one such block may introduce many errors in
the program. If a group of statements/block of code is repeatedly required then it is not
recommended to write these statements every time separately. We have to define these
statements as a single unit and we can call that unit any number of times based on our
requirement without rewriting. This unit is nothing but function.
TYPES OF FUNCTIONS:
1. Built-in functions
Built- in functions are pre- defined functions which comes along with python software
automatically.
Eg: id(), type(), print(), input(), eval() etc.
2. User defined functions
The functions which are developed by programmer explicitly according to business requirements,
are called user defined functions.
def function_name(parameters):
"""doc string"""
----
-----
return value
Ex:
def wish():
print('Hello Good Morning')
wish()
wish()
wish()
output:
Hello Good Morning
Hello Good Morning
Hello Good Morning
Parameters are inputs to the function. If a function contains parameters, then at the time of calling,
compulsory we should provide values otherwise, we will get error.
Ex: Write a function to take name of the student as input and print wish message b name.
def wish(name):
print('Hello Good Morning', name)
wish('sai')
wish('ravi')
wish('giri')
Output:
Hello Good Morning sai
Hello Good Morning ravi
Hello Good Morning giri
Return statement
The return statement is used if you want to return some values from a function.
Return statement is used to quit the function it is executing and to pass the control back to the
statement from where it was called.
• The return statement can have an expression which gets evaluated and the value is returned or a
value directly can be returned.
• If there is no expression in the statement then the function will return None.
• If the function does not have a return statement, then the function will return None.
output:
sum: 6
Ex2:
def add(a,b):
c = a + b
return
print('sum: ', add(2,4))
output:
sum: None
Ex3:
def add(a,b):
c = a + b
print('sum: ', add(2,4))
output:
sum: None
Q. Write a function to check whether the given number is even or odd?
(Given in R20 24th Feb 2022)
def even_odd(num):
if num%2==0:
print(num,"is Even Number")
else:
print(num,"is Odd Number")
even_odd(10)
even_odd(15)
Output
10 is Even Number
15 is Odd Number
Q. Write a function to find factorial of given number. (Given in R19, 10th August 2021)
def fact(num):
result = 1
while num >= 1:
Output:
The factorial of 1 is: 1
The factorial of 2 is: 2
The factorial of 3 is: 6
The factorial of 4 is: 24
Ex:
Python Program to Find HCF or GCD
# Python program to find H.C.F of two numbers
# define a function
def compute_hcf(x, y):
num1 = 54
num2 = 24
return x * y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
while True:
# take input from the user
choice = input("Enter choice(1/2/3/4): ")
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
Output:
The results are:
30
10
200
2.0
Parameters are used to give inputs to a function. They are specified with a pair of parentheses in
the function’s definition.
When a programmer calls a function, the values are also passed to the function.
Example:
def sum(a,b):
print(a+b)
sum(1,2) # Here the values 1,2 are arguments
In a function, there are two types of arguments, namely formal arguments and actual arguments.
For example:
In the above example, a and b behave as formal arguments whereas 1 and 2 behave as actual
arguments.
There are different types of arguments in Python.
1. Positional arguments:
Positional arguments are passed to the function at a proper positional order. The position and the
number of the arguments should be compared. By changing the order, the result may change
whereas by changing the number of arguments, an error message will be displayed.
Ex 1:
Output:
4
Ex 2:
Output:
2
Ex 3:
Output:
Keyword arguments (or named arguments) are values that, when passed into a function, are
identifiable by specific parameter names. i.e. If the programmer knows the parameter name
used within the function then the parameter name can explicitly be used while calling the
function.
A keyword argument is preceded by a parameter and the assignment operator, =.
Here, the order of arguments is not mandatory, but the number of arguments should match.
Ex 1:
Output:
12
Note: The keyword and the positional arguments can be used together, but the order should be
positional and then keyword argument.
Ex 2:
def add(x, y, z): # formal parameters
s = x + y + z
return s
Output:
File "<python-input-12-5a481a665e75>", line 1
add(2, z=5, 10) # is not possible
^
SyntaxError: positional argument follows keyword argument
Ex 3:
def add(x, y, z): # formal parameters
s = x + y + z
return s
add(2, 5, y=10) # Is this valid?
Output:
-----------------------------------------------------------------
----------
TypeError Traceback (most recent
call last)
<ipython-input-13-3aafe06a3aa0> in <module>
----> 1 add(2, 5, y=10)
3. Default arguments:
Default arguments, are keyword arguments whose values are assigned at the time of function
definition/declaration.
Thus, at the time of calling the function, if the programmer doesn’t provide a value for the
parameter for which we specified the default argument, the function simply assumes the default
value as the argument in that case. Thus, calling the function will not result in any error even if
we don’t provide any value as an argument for the parameter with a default argument.
Ex1:
output:
12
17
Ex 2:
Output:
4
9
9
Ex 3:
\*** non-default arguments must not follow default arguments
def add(x=0, y, z=0):
r = x + y + z
return r
print(add(4, 5))
File "<ipython-input-16-66d675e7f8c4>", line 1
def add(x=0, y, z=0):
^
A variable length argument is an argument that can accept variable number of values.
You may need to process a function for more arguments than you specified while defining the
function i.e, where the exact number of arguments are not known in the beginning. These
arguments are called variable-length arguments.
Using variable length argument, you can pass zero or more arguments to a function.
Values pass to *args are stored in a tuple.
Before variable args you can have a formal argument but not after a variable args. After
variable argument you can have keyword arguments.
Ex1:
def add(*args):
print(type(args))
s = 0
for x in args:
s = s + x
return s
res = add(2, 3, 4.0, 5, 6, 7.5, 8, 9)
print(res)
Ex2:
def add(*args):
print(type(args))
s = 0
for x in args:
s = s + x
return s
add()
output:
<class 'tuple'>
Python keyword variable length argument is an argument that accept variable number of
keyword arguments (arguments in the form of key, value pair). To indicate that the function
can take keyword variable length argument you write an argument using double asterisk ‘**’,
for example **kwargs.
Values passed as keyword variable length argument are stored in a dictionary that is
referenced by the keyword arg name.
Ex:
def add(**kwargs):
print (type(kwargs))
print (kwargs)
for var, val in kwargs.items():
print (var,'->', val)
add(a=20, b=30, c=40)
output:
<class 'dict'>
{'a': 20, 'b': 30, 'c': 40}
a -> 20
b -> 30
c -> 40
Parameter unpacking:
Ex1:
Ex2:
t = 2, 3, 4
def fun(x, y, z):
print(x + y + z)
fun(t[0], t[1], t[2]) # Passing parameters by unpacking them
fun(*t) # passing all parameters at once
output:
9
9
1. Global Variables
The variables which are declared outside of function are called global variables.
These variables can be accessed in all functions of that module.
Ex:
x=15 # global variable
def f1():
print(x)
def f2():
print(x)
f1()
f2()
output:
15
15
2. Local Variables:
The variables which are declared inside a function are called local variables.
Local variables are available only for the function in which we declared it.i.e from outside of
function we cannot access.
Ex:
def f1():
x=15 # local variable
print(x)
def f2():
print(x) # can't access x
f1()
f2()
output:
15
NameError: name 'x' is not defined
Global keyword:
The global keyword is used:
Ex1:
Output:
15
20
Ex2:
def f1():
global x
x=15
print(x)
def f2():
print(x)
f1()
f2()
output
15
15
Note: If global variable and local variable having the same name then we can access
Output:
15
20
Recursive Function
Python also supports the recursive feature, which means that a function is repeatedly calling itself.
Thus, a function is said to be recursive if the statement declared in the body of the function calls itself,
like calculating the factorial is an example of recursive function.
Ex:
factorial(3)=3*factorial(2)
=3*2*factorial(1)
=3*2*1*factorial(0)
=3*2*1*1
=6
fac(n) = n* fac(n- 1)
Program: Write a program using recursion that calculates the factorial of a number
def factorial(n):
if n==0:
result=1
else:
result=n*factorial(n-1)
return result
print("Factorial of 4 is :",factorial(4))
print("Factorial of 5 is :",factorial(5))
Output:
Factorial of 4 is : 24
Factorial of 5 is : 120
Sometimes we can declare a function without any name, such type of nameless functions
are called anonymous functions or lambda functions.
The main purpose of anonymous function is just for instant use (i.e for one-time usage)
Normal Function:
We can define by using def keyword.
def squareIt(n):
return n*n
lambda Function:
We can define by using lambda keyword
lambda n:n*n
Syntax of lambda Function:
lambda argument_list : expression
Note: By using Lambda Functions we can write very concise code so that readability of
the program will be improved.
Output
The Square of 4 is : 16
The Square of 5 is : 25
s=lambda a, b : a + b
print("The Sum of 10,20 is:",s(10,20))
print("The Sum of 100,200 is:",s(100,200))
Output
The Sum of 10,20 is: 30
The Sum of 100,200 is: 300
Q. Lambda Function to find biggest of given values.
Output:
The Biggest of 10,20 is: 20
The Biggest of 100,200 is: 200
Note:
Lambda Function internally returns expression value and we are not required to write return
statement explicitly.
Sometimes we can pass function as an argument to another function. In such cases lambda
functions are best choice.
We can use lambda functions very commonly with filter (), map () and reduce () functions, b'z
these functions expect function as an argument.
filter () function:
We can use filter () function to filter values from the given sequence based on some
condition.
filter (function, sequence)
Where function argument is responsible to perform conditional check
Sequence can be list or tuple or string.
Q. Program to filter only even numbers from the list by using filter () function?
def isEven(x):
if x % 2==0:
return True
else:
return False
l=[0,5,10,15,20,25,30]
l1=list(filter(isEven,l))
print(l1)
Output:
[0,10,20,30]
l = [0,5,10,15,20,25,30]
l1 = list(filter(lambda x:x%2==0,l))
print(l1)
l2 = list(filter(lambda x:x%2!=0,l))
print(l2)
Output:
[0,10,20,30]
[5,15,25]
map () function:
For every element present in the given sequence, apply some functionality and generate
new element with the required modification. For this requirement we should go for map () function.
Eg: For every element present in the list perform double and generate new list of doubles.
Syntax:
map (function, sequence)
The function can be applied on each element of sequence and generates new sequence.
Eg: Without lambda
l=[1,2,3,4,5]
def doubleIt(x):
return 2*x
l1=list(map(doubleIt,l))
print(l1)
Output:
[2, 4, 6, 8, 10]
with lambda
l=[1,2,3,4,5]
l1=list(map(lambda x:2*x,l))
print(l1)
output:
[2, 4, 6, 8, 10]
l=[1,2,3,4,5]
l1=list(map(lambda x:x*x,l))
print(l1)
Output:
[1, 4, 9, 16, 25]
We can apply map() function on multiple lists also. But make sure all list should have same
length.
Eg3:
l1=[1,2,3,4]
l2=[2,3,4,5]
l3=list(map(lambda x,y:x*y,l1,l2))
print(l3)
Output:
[2, 6, 12, 20]
reduce () function:
reduce () function reduces sequence of elements into a single element by applying the
specified function.
reduce(function,sequence)
reduce() function present in functools module and hence we should write import statement.
(Given in R19 28th august 2021)
Eg1:
output:
150
Eg2:
l=[10,20,30,40,50]
result=reduce(lambda x,y:x*y,l)
print(result)
output:
12000000
Eg3:
Eg:
def f1():
print("Hello")
print(f1)
print(id(f1))
Output
<function f1 at 0x000002AE9F90A290>
2949024621200
Fruitful Functions
These are the functions that return a value after their completion. A fruitful function must always
return a value to where it is called from. A fruitful function can return any type of value may it be
string, integer, boolean, etc. It is not necessary for a fruitful function to return the value of one
variable, the value to be returned can be an array or a vector. A fruitful function can also return
multiple values.
Ex1: Ex2:
Output
GOOD MORNING
good morning
Modules
A module in python is a set of re-usable classes, functions, and variables. If we need those classes,
functions or variables in our project, we just import them.
Modules can be either:
Built in modules
Built-in modules come with default Python installation. Some commonly used Python built-in
modules are datetime, os, math, sys, random, etc.
User-defined modules
The modules which the user defines or create are called a user-defined module. We can create our
own module, which contains classes, functions, variables, etc., as per our requirements.
Create a Module
To create a module, create a Python file with a .py extension.
Ex:
x = 10
y = 20
def add(a,b):
print('The Sum : ',a+b)
def product(a,b):
print('The product :', a*b)
CALL A MODULE
If we want to use members of module in our program then we should import that module.
Syntax of importing a module
import modulename
modulename.variable
modulename.function()
Ex:
import example
print(example.x)
example.add(10,20)
example.product(10,20)
Output:
10
The Sum : 30
The product : 200
Note: Whenever we are using a module in our program, for that module compiled file will be
generated and stored in the hard disk permanently. This is available at __pycache__ file, which is
available at current working directory.
Advantages of Modules
The main purpose of creating modules is to make Python code reusable.
Code Re-usability has the following benefits:
Module aliasing (Renaming a module at the time of import) [R19, 28th August2021]
We can create alias name for a module. This can be done as follows:
import example as ex
Here, example is original module name and ex is alias name. We can access members by using alias
name ex.
Ex:
import example as ex
print(ex.x)
ex.add(10,20)
ex.product(10,20)
Output:
10
The Sum : 30
The product : 200
Ex:
import example as ex
print(example.x)
example.add(10,20)
example.product(10,20)
output:
Output:
Traceback (most recent call last):
NameError: name 'product' is not defined
We can import all members of a module as follows
Eg
Output:
10
The Sum : 30
The product : 200
member aliasing
Similar to module aliasing, member aliasing also possible in python. This can be done as follows:
from example import x as y,add as sum
print(y)
sum(10,20)
Note: Once we defined as alias name, we should use alias name only and we should not use original
name.
x=10
y=20
def f1():
print("Hello")
print(dir())
Output:
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__',
'__loader__', '__name__', '__package__', '__spec__', 'add', 'ex',
'example', 'f1', 'product', 'sum', 'x', 'x1', 'y']
Eg2: To display members of particular module
Consider example.py module,
import example module in another module, called as run.py,
import example
print(dir(example))
the above two lines of code will be saved as run.py and run we will get
output:
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__',
'__name__', '__package__', '__spec__', 'add', 'product', 'x', 'y']
Note:
For every module at the time of execution Python interpreter will add some special properties
automatically for internal use.
Eg: '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__',
'__spec__'
For every Python program , a special variable _ name_ will be added internally. This variable stores
information regarding whether the program is executed as an individual program or as a module.
If the program executed as an individual program then the value of this variable is _ main_.
If the program executed as a module from some other program then the value of this variable is the
name of module where it is defined.
Hence by using this _ name_ variable we can identify whether the program executed directly or as a
module.
Random Module
The random module is used to generate various random numbers. It comprises several functions that
are defined below:
1. random() Function: It produces any float value in the range 0 to 1, without inclusive 0 and 1.
2. randint() Function: It produces any random integer between specified numbers, with including
them.
Example:
3. uniform() Function: It produces any random float values between specified numbers, without
including them.
Example:
4. randrange ([begin], end, [step]): It produces a random number from the defined range. Here, the
begin argument is optional and if not defined, then the by- default value is 0. The step argument is
also optional and if not defined then, the by- default value is 1.
Ex:
Ex:
Ex:
5. choice() Function: It gives a random object from the specified list or the tuple.
Example:
Q 1. Write a Python program to generate a six digit random number as One Time Password
(OTP).
for i in range(10):
for x in range(6):
print(randint(0,9),end='') # Correct version
print()
for i in range(6):
File I/O
File is a collection of data stored externally on an external media (not in RAM, RAM is a volatile
memory). i.e. on permanent storage devices (eg. Hard disk, is a non-volatile memory) with a
name.
Content of file can be simple text, binary data (image, audio, video) etc...
Why files?
Till now, we were taking the input from the console and writing it back to the console to interact
with the user.
Sometimes, it is not enough to only display the data on the console. The data to be displayed may
be very large, and only a limited amount of data can be displayed on the console since the
memory is volatile, it is impossible to recover the programmatically generated data again and
again.
File handling plays an important role when the data needs to be stored permanently in the file.
Types of Files
Opening a File:
Before performing any operation (like read or write) on the file, first we have to create a file
object that is associated with a physical file is called opening a file. To open that file we should
use Python's inbuilt function open ( ).
But at the time of open, we have to specify mode, which represents the purpose of opening file.
fileVariable = open(filename, mode)
The open function returns a file object for filename. The mode parameter is a string that specifies
how the file will be used (for reading or writing), as shown below.
The allowed modes in Python are
It is the default mode. The file gets opened for reading purpose only and the cursor
r points at the starting of the file.
If the specified file does not exist then we will get FileNotFoundError
The file gets opened for writing. If the file exists of the mentioned name, it gets
w
overwritten else another file will be created.
The existing file is opened for the appending purpose. If the file exists, the pointer
a points at the end of file as the file is in the append mode otherwise, a new file will be
created for the writing purpose.
The file gets open for reading and writing as well. The existing data is the file doesn’t
r+
gets deleted. The cursor is kept at the starting of file.
File gets open for both reading and writing as well. It will overwrite the file if the file
w+
exists. Otherwise, another file will be deployed.
The file gets open for append and read purpose. If the file exists, the pointer is at the
a+ end of file. The file opens in append mode whereas if the file doesn’t exist, a new file
will be created for read and write purpose.
The file gets open for exclusive creation for writing the data. The operation fails if
x
the file already exists.
Note: All the above modes are applicable for text files. If the above modes suffixed with 'b' then
these represent binary files.
Eg: rb,wb,ab,r+b,w+b,a+b,xb
For example, the following statement opens a file named Scores.txt in the current directory for
reading:
input = open("Scores.txt", "r")
You can also use the absolute filename to open the file in Windows, as follows:
input = open(r"c:\pybook\Scores.txt", "r")
The statement opens the file Scores.txt that is in the c:\pybook directory for reading. The r prefix
before the absolute filename specifies that the string is a raw string, which causes the Python
interpreter to treat backslash characters as literal backslashes. Without the r prefix, you would
have to write the statement using an escape sequence as:
input = open("c:\\pybook\\Scores.txt", "r")
illustrate opening files with a neat diagram. (given in R19 10th august 2021)
Closing a File:
Opening files consume system resources, and, depending on the file mode, other programs may
not be able to access them. It is important to close the file once the processing is completed. After
the file handler object is closed, you cannot further read or write from the file. Any attempt to use
the file handler object after being closed will result in an error.
The syntax for close() function is,
file_handler.close()
Attributes/properties of a file object:
Attribute Information Obtained
Mode The access mode with which the file has opened will be returned.
Closed If the file is closed, it will return True. Else False will be returned.
readable() It will return the Boolean value mentioning whether the file is readable or not.
writable() It will return the Boolean value mentioning whether the file is writable or not
For writing to a file, we first need to open it in write or append mode. If we open an existing file
in write mode, the previous data will be erased, and the file object will be positioned at the
beginning of the file. On the other hand, in append mode, new data will be added at the end of the
previous data as the file object is at the end of the file.
After opening the file, we can use the following methods to write data (character data) in the file.
write() - for writing a single string
writelines() - for writing a sequence of strings/list of lines
write():
write() method takes a string as an argument and writes it to the text file. It returns the number of
characters being written on single execution of the write() method.
Also, we need to add a newline character (\n) at the end of every sentence to mark the end of line.
Ex:
def main():
outfile = open("Presidents.txt", "w")# Open file for output
outfile.write("George Bush\n")
outfile.write("Barack Obama\n")
outfile.write("Bill Clinton\n")
outfile.close() # Close the output file
main() # Call the main function
The program opens a file named Presidents.txt using the w mode for writing data.
If the file does not exist, the open function creates a new file. If the file already exists, the contents
of the file will be overwritten with new data. You can now write data to the file.
When a file is opened for writing or reading, a special marker called a file pointer is positioned
internally in the file. A read or write operation takes place at the pointer’s location.
When a file is opened, the file pointer is set at the beginning of the file. When you read or write
data to the file, the file pointer moves forward.
The program invokes the write method on the file object to write three strings.
The program closes the file to ensure that data is written to the file. After this program is
executed, three names are written to the file. You can view the file in a text editor, as shown in
Figure.
Instead of overriding if we want append operation then we should open the file as follows.
def main():
outfile = open("Presidents.txt", "a")# Open file for output
outfile.write("George Bush\n")
outfile.write("Barack Obama\n")
outfile.write("Bill Clinton\n")
outfile.close() # Close the output file
main() # Call the main function
Writelines() method:
This method is used to write multiple strings to a file. We need to pass an iterable object like lists,
tuple, etc. containing strings to the writelines() method. Unlike write(), the writelines() method
does not return the number of characters written in the file. The following code explains the use of
writelines().
Code:
f=open("abcd.txt",'w')
list=["sunny\n","bunny\n","vinny\n","chinny"]
f.writelines(list)
print("List of lines written to the file successfully")
f.close()
chinny
Eg 4: To read all lines into list:
f=open("abc.txt",'r')
lines=f.readlines()
for line in lines:
print(line,end='')
f.close()
Output
sunny
bunny
chinny
vinny
Eg 5:
f=open("abc.txt","r")
print(f.read(3))
print(f.readline())
print(f.read(4))
print("Remaining data")
print(f.read())
Output
sun
ny
bunn
Remaining data
y
chinny
vinny
Ex:
myobject=open("myfile.txt", 'w')
list = ['Hello everyone\n', 'Writing multiline strings\n', 'This is the third line']
myobject.writelines(list)
myobject.close()
In case we want to display each word of a line separately as an element of a list, then we can use
split() function. The following code demonstrates the use of split() function.
myobject=open("myfile.txt",'r')
d=myobject.readlines()
for line in d:
words=line.split()
print(words)
output:
['Hello', 'everyone']
['Writing', 'multiline', 'strings']
['This', 'is', 'the', 'third', 'line']
In the output, each string is returned as elements of a list. However, if splitlines() is used instead
of split(), then each line is returned as element of a list, as shown in the output below
myobject=open("myfile.txt",'r')
d=myobject.readlines()
for line in d:
words=line.splitlines()
print(words)
Output:
['Hello everyone']
['Writing multiline strings']
['This is the third line']
Let us now write a program that accepts a string from the user and writes it to a text file.
Thereafter, the same program reads the text file and displays it on the screen.
Program: Writing and reading to a text file
fobject=open("testfile.txt","w") # creating a data file
sentence=input("Enter the contents to be written in the file: ")
fobject.write(sentence) # Writing data to the file
fobject.close() # Closing a file
print("Now reading the contents of the file: ")
fobject=open("testfile.txt","r")
#looping over the file object to read the file
for str in fobject:
print(str)
fobject.close()
In Program, the file named testfile.txt is opened in write mode and the file handle named fobject is
returned. The string is accepted from the user and written in the file using write(). Then the file is
closed and again opened in read mode. Data is read from the file and displayed till the end of file
is reached.
Output
The functions that we have learnt till now are used to access the data sequentially from a file. But
if we want to access data in a random fashion, then Python gives us seek() and tell() functions to
do so.
The tell() method
==>We can use tell() method to return current position of the cursor(file pointer) from beginning
of the file. [ can you plese telll current cursor position]
The position(index) of first character in files is zero just like string index.
Syntax: file_object.tell()
abc.txt file contains
department
mechanical
engineering
f=open("abc.txt","r")
print(f.tell())
print(f.read(2))
print(f.tell())
print(f.read(3))
print(f.tell())
Output:
0
de
2
par
5
seek():
We can use seek() method to move cursor(file pointer) to specified location.
[Can you please seek the cursor to a particular location]
f.seek(offset, fromwhere)
offset represents the number of positions
The allowed values for second attribute(from where) are
0---->From beginning of file(default value)
1---->From current position
2--->From end of the file
Note: Python 2 supports all 3 values but Python 3 supports only zero.
Ex:
data="All Students are VERY GOOD"
f=open("file.txt","w")
f.write(data)
with open("file.txt","r+") as f:
text=f.read()
print(text)
Note:
sys.exit(0) ===>To exit system without executing rest of the program.
argument represents status code . 0 means normal termination and it is the default value.
Q. Program to print the number of lines,words and characters present in the given file?
File contains the following:
department
mechanical
engineering
import os,sys
fname=input("Enter File Name: ")
if os.path.isfile(fname):
print("File exists:",fname)
f=open(fname,"r")
else:
print("File does not exist:",fname)
sys.exit(0)
lcount=wcount=ccount=0
for line in f:
lcount=lcount+1
ccount=ccount+len(line)
words=line.split()
wcount=wcount+len(words)
print("The number of Lines:",lcount)
print("The number of Words:",wcount)
print("The number of Characters:",ccount)
Output:
Enter File Name: abc.txt
File exists: abc.txt
The number of Lines: 3
The number of Words: 3
The number of Characters: 34
fileobject=open("report.txt", "w+")
print ("WRITING DATA IN THE FILE")
print() # to display a blank line
while True:
line= input("Enter a sentence ")
fileobject.write(line)
fileobject.write('\n')
choice=input("Do you wish to enter more data? (y/n): ")
if choice in ('n','N'): break
print("The byte position of file object is ",fileobject.tell())
fileobject.seek(0) #places file object at beginning of file
print()
print("READING DATA FROM THE FILE")
str=fileobject.read()
print(str)
fileobject.close()