SlideShare a Scribd company logo
UNIT 3 OBJECTS ,
CLASSES & FILES
Python OOPs Concepts
Like other general-purpose programming languages, Python is
also an object-oriented language since its beginning. It allows us
to develop applications using an Object-Oriented approach.
In Python, we can easily create and use classes and objects.
An object-oriented paradigm is to design the program using
classes and objects. The object is related to real-word entities such
as book, house, pencil, etc. The oops concept focuses on writing
the reusable code. It is a widespread technique to solve the
problem by creating objects.
Major principles of object-oriented
programming system are given below.
1. Class
2. Object
3. Method
4. Inheritance
5. Polymorphism
6. Data Abstraction
7. Encapsulation
Class
The class can be defined as a collection of objects. It is a logical entity that has some
specific attributes and methods. For example: if you have an employee class, then it should
contain an attribute and method, i.e. an email id, name, age, salary, etc.
Syntax
class ClassName:
<statement-1>
.
.
<statement-N>
A class is a blueprint for the object
Example:
class car:
def __init__(self,modelname, year):
self.modelname = modelname
self.year = year
def display(self):
print(self.modelname,self.year)
Object
The object is an entity that has state and behavior. It may be any real-world object like the
mouse, keyboard, chair, table, pen, etc.
Everything in Python is an object, and almost everything has attributes and methods. All
functions have a built-in attribute __doc__, which returns the docstring defined in the
function source code.
When we define a class, it needs to create an object to allocate the memory.
Example:
Example:
class car:
def __init__(self,modelname, year):
self.modelname = modelname
self.year = year
def display(self):
print(self.modelname,self.year)
c1 = car("Toyota", 2016)
c1.display()
The __init__() Function
All classes have a function called __init__(), which is always
executed when the class is being initiated.
Use the __init__() function to assign values to object properties,
or other operations that are necessary to do when the object is
being created:
The first argument of every method is a reference to the current
instance of the class
By convention, we name this argument self
In __init__, self refers to the object currently being created; so,
in other class methods, it
refers to the instance whose method was called Similar to the
keyword this in Java or C++.
Example
Create a class named Person, use the __init__() function to
assign values for name and age:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
Object Methods
Example
Insert a function that prints a greeting, and execute it on the
p1 object:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
The self Parameter
The self parameter is a reference to the current instance of
the class, and is used to access variables that belongs to the
class.
It does not have to be named self , you can call it whatever
you like, but it has to be the first parameter of any function in
the class:
Example
Use the words mysillyobject and abc instead of self:
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc()
Inheritance
Inheritance is the most important aspect of object-oriented
programming, which simulates the real-world concept of
inheritance.
It specifies that the child object acquires all the properties and
behaviors of the parent object.
By using inheritance, we can create a class which uses all the
properties and behavior of another class.
The new class is known as a derived class or child class, and
the one whose properties are acquired is known as a base class
or parent class.
It provides the re-usability of the code.
# parent class
class Bird:
def __init__(self):
print("Bird is ready")
def whoisThis(self):
print("Bird")
def swim(self):
print("Swim faster")
# child class
class Penguin(Bird):
def __init__(self):
# call super() function
super().__init__()
print("Penguin is ready")
def whoisThis(self):
print("Penguin")
def run(self):
print("Run faster")
peggy = Penguin()
peggy.whoisThis()
peggy.swim()
peggy.run()
Encapsulation
Using OOP in Python, we can restrict access to methods and variables. This prevents data
from direct modification which is called encapsulation. In Python, we denote private attributes
using underscore as the prefix i.e single _ or double __.
class Computer:
def __init__(self):
self.__maxprice = 900
def sell(self):
print("Selling Price: {}".format(self.__maxprice))
def setMaxPrice(self, price):
self.__maxprice = price
c = Computer()
c.sell()
# change the price
c.__maxprice = 1000
c.sell()
# using setter function
c.setMaxPrice(1000)
c.sell()
Polymorphism
Polymorphism is an ability (in OOP) to use a common interface for multiple forms (data types).
Suppose, we need to color a shape, there are multiple shape options (rectangle, square, circle).
However we could use the same method to color any shape. This concept is called
Polymorphism.
class Parrot:
def fly(self):
print("Parrot can fly")
def swim(self): p
print("Parrot can't swim")
class Penguin:
def fly(self):
print("Penguin can't fly")
def swim(self):
print("Penguin can swim")
# common interface
def flying_test(bird):
bird.fly()
#instantiate objects
blu = Parrot()
peggy = Penguin()
# passing the object
flying_test(blu)
flying_test(peggy)
File Objects in Python
Files
Files are named locations on disk to store related information.
They are used to permanently store data in a non-volatile memory (e.g. hard
disk).
Since Random Access Memory (RAM) is volatile (which loses its data when the
computer is turned off), we use files for future use of the data by permanently
storing them.
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 the resources that are tied with the file are
freed.
Hence, in Python, a file operation takes place in the following order:
1. Open a file
2. Read or write (perform operation)
3. Close the file
1 . Python File Open -
The key function for working with files in Python is the open() function.
The open() function takes two parameters; filename, and mode.
There are four different methods (modes) for opening a file:
1. "r" - Read - Default value. Opens a file for reading, error if the file does
not exist
2. "a" - Append - Opens a file for appending, creates the file if it does not
exist
3. "w" - Write - Opens a file for writing, creates the file if it does not exist
4. "x" - Create - Creates the specified file, returns an error if the file exists
Syntax - f = open("demofile.txt")
f = open("demofile.txt", "rt")
Mode Description
r Opens a file for reading. (default)
w
Opens a file for writing. Creates a new file if it
does not exist or truncates the file if it exists.
x
Opens a file for exclusive creation. If the file
already exists, the operation fails.
a
Opens a file for appending at the end of the file
without truncating it. Creates a new file if it does
not exist.
t Opens in text mode. (default)
b Opens in binary mode.
+ Opens a file for updating (reading and writing)
2 . Python File Read -
1. The open() function returns a file object, which has
a read() method for reading the content of the file:
Example
f = open("demofile.txt", "r")
print(f.read())
2. If the file is located in a different location, you will have to
specify the file path, like this:
Example
f = open("D:myfileswelcome.txt", "r")
print(f.read())
3. By default the read() method returns the whole text, but
you can also specify how many characters you want to
return:
Example
f = open("demofile.txt", "r")
print(f.read(5))
3 . Python Write/Create File -
1. Write to an Existing File
To write to an existing file, you must add a parameter to
the open() function:
"a" - Append - will append to the end of the file
"w" - Write - will overwrite any existing content
2. Create a File
To create a new file in Python, use the open() method, with one of the
following parameters:
"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a file if the specified file does not exist
Method Description
close() Closes the file
detach() Returns the separated raw stream from the buffer
fileno() Returns a number that represents the stream, from the operating system's
perspective
flush() Flushes the internal buffer
isatty() Returns whether the file stream is interactive or not
read() Returns the file content
readable() Returns whether the file stream can be read or not
readline() Returns one line from the file
readlines() Returns a list of lines from the file
seek() Change the file position
seekable() Returns whether the file allows us to change the file position
tell() Returns the current file position
truncate() Resizes the file to a specified size
writable() Returns whether the file can be written to or not
write() Writes the specified string to the file
writelines() Writes a list of strings to the file
Built –in methods in python
Command Line Arguments in Python
The arguments that are given after the name of the program in the
command line shell of the operating system are known
as Command Line Arguments.
Python provides various ways of dealing with these types of
arguments.
The three most common are:
1. Using sys.argv
2. Using getopt module
3. Using argparse module
Using sys.argv
The sys module provides functions and variables used to
manipulate different parts of the Python runtime environment.
This module provides access to some variables used or maintained
by the interpreter and to functions that interact strongly with the
interpreter.
One such variable is sys.argv which is a simple list structure. It’s
main purpose are:
1. It is a list of command line arguments.
2. len(sys.argv) provides the number of command line arguments.
3. sys.argv[0] is the name of the current Python script.
# Python program to demonstrate
# command line arguments
import sys
# total arguments
n = len(sys.argv)
print("Total arguments passed:", n)
# Arguments passed
print("nName of Python script:", sys.argv[0])
print("nArguments passed:", end = " ")
for i in range(1, n):
print(sys.argv[i], end = " ")
# Addition of numbers
Sum = 0
# Using argparse module
for i in range(1, n):
Sum += int(sys.argv[i])
print("nnResult:", Sum)
Using getopt module
Python getopt module is similar to the getopt() function of C.
Unlike sys module getopt module extends the separation of the input string by parameter
validation.
It allows both short, and long options including a value assignment. However, this
module requires the use of the sys module to process input data properly.
To use getopt module, it is required to remove the first element from the list of
command-line arguments.
Syntax: getopt.getopt(args, options, [long_options])
Parameters:
args: List of arguments to be passed.
options: String of option letters that the script want to recognize. Options that
require an argument should be followed by a colon (:).
long_options: List of string with the name of long options. Options that
require arguments should be followed by an equal sign (=).
Return Type: Returns value consisting of two elements: the first is a list of
(option, value) pairs. The second is the list of program arguments left after
the option list was stripped.
Using argparse module
Using argparse module is a better option than the
above two options as it provides a lot of options
such as positional arguments, default value for
arguments, help message, specifying data type of
argument etc.
Note: As a default optional argument, it includes
-h, along with its long version –help.

More Related Content

Similar to Master of computer application python programming unit 3.pdf (20)

PPTX
5-filehandling-2004054567151830 (1).pptx
lionsconvent1234
 
PDF
Python file handling
Prof. Dr. K. Adisesha
 
PPTX
File handling in Python
Megha V
 
PDF
Python Files I_O17.pdf
RashmiAngane1
 
PPT
File Handling as 08032021 (1).ppt
Raja Ram Dutta
 
PPTX
pspp-rsk.pptx
ARYAN552812
 
PPTX
Python programming
saroja20
 
PPTX
File Handling in Python -binary files.pptx
deepa63690
 
PPTX
FILE INPUT OUTPUT.pptx
ssuserd0df33
 
PDF
File handling with python class 12th .pdf
lionsconvent1234
 
PPTX
files.pptx
KeerthanaM738437
 
PDF
file handling.pdf
RonitVaskar2
 
PPTX
File Operations in python Read ,Write,binary file etc.
deepalishinkar1
 
PPTX
Data File Handling in Python Programming
gurjeetjuneja
 
PPTX
Understanding Python
Kaleem Ullah Mangrio
 
PPTX
Python IO
RTS Tech
 
PPTX
software construction and development week 3 Python lists, tuples, dictionari...
MuhammadBilalAjmal2
 
PDF
Python introduction 2
Ahmad Hussein
 
PPTX
Functions in python
Santosh Verma
 
5-filehandling-2004054567151830 (1).pptx
lionsconvent1234
 
Python file handling
Prof. Dr. K. Adisesha
 
File handling in Python
Megha V
 
Python Files I_O17.pdf
RashmiAngane1
 
File Handling as 08032021 (1).ppt
Raja Ram Dutta
 
pspp-rsk.pptx
ARYAN552812
 
Python programming
saroja20
 
File Handling in Python -binary files.pptx
deepa63690
 
FILE INPUT OUTPUT.pptx
ssuserd0df33
 
File handling with python class 12th .pdf
lionsconvent1234
 
files.pptx
KeerthanaM738437
 
file handling.pdf
RonitVaskar2
 
File Operations in python Read ,Write,binary file etc.
deepalishinkar1
 
Data File Handling in Python Programming
gurjeetjuneja
 
Understanding Python
Kaleem Ullah Mangrio
 
Python IO
RTS Tech
 
software construction and development week 3 Python lists, tuples, dictionari...
MuhammadBilalAjmal2
 
Python introduction 2
Ahmad Hussein
 
Functions in python
Santosh Verma
 

Recently uploaded (20)

PPTX
Aerobic and Anaerobic respiration and CPR.pptx
Olivier Rochester
 
PPTX
How to Add a Custom Button in Odoo 18 POS Screen
Celine George
 
PPT
Indian Contract Act 1872, Business Law #MBA #BBA #BCOM
priyasinghy107
 
PDF
TLE 8 QUARTER 1 MODULE WEEK 1 MATATAG CURRICULUM
denniseraya1997
 
DOCX
Lesson 1 - Nature and Inquiry of Research
marvinnbustamante1
 
PDF
Vani - The Voice of Excellence - Jul 2025 issue
Savipriya Raghavendra
 
PPTX
PLANNING FOR EMERGENCY AND DISASTER MANAGEMENT ppt.pptx
PRADEEP ABOTHU
 
PDF
DIGESTION OF CARBOHYDRATES ,PROTEINS AND LIPIDS
raviralanaresh2
 
PDF
Lesson 1 - Nature of Inquiry and Research.pdf
marvinnbustamante1
 
PPTX
How to Manage Expiry Date in Odoo 18 Inventory
Celine George
 
PDF
WATERSHED MANAGEMENT CASE STUDIES - ULUGURU MOUNTAINS AND ARVARI RIVERpdf
Ar.Asna
 
PPTX
Introduction to Indian Writing in English
Trushali Dodiya
 
PDF
Indian National movement PPT by Simanchala Sarab, Covering The INC(Formation,...
Simanchala Sarab, BABed(ITEP Secondary stage) in History student at GNDU Amritsar
 
PPTX
ENGlish 8 lesson presentation PowerPoint.pptx
marawehsvinetshe
 
PPTX
Ward Management: Patient Care, Personnel, Equipment, and Environment.pptx
PRADEEP ABOTHU
 
PPTX
Marketing Management PPT Unit 1 and Unit 2.pptx
Sri Ramakrishna College of Arts and science
 
PPTX
How to Create & Manage Stages in Odoo 18 Helpdesk
Celine George
 
PDF
Android Programming - Basics of Mobile App, App tools and Android Basics
Kavitha P.V
 
PDF
CAD25 Gbadago and Fafa Presentation Revised-Aston Business School, UK.pdf
Kweku Zurek
 
PPTX
Life and Career Skills Lesson 2.pptxProtective and Risk Factors of Late Adole...
ryangabrielcatalon40
 
Aerobic and Anaerobic respiration and CPR.pptx
Olivier Rochester
 
How to Add a Custom Button in Odoo 18 POS Screen
Celine George
 
Indian Contract Act 1872, Business Law #MBA #BBA #BCOM
priyasinghy107
 
TLE 8 QUARTER 1 MODULE WEEK 1 MATATAG CURRICULUM
denniseraya1997
 
Lesson 1 - Nature and Inquiry of Research
marvinnbustamante1
 
Vani - The Voice of Excellence - Jul 2025 issue
Savipriya Raghavendra
 
PLANNING FOR EMERGENCY AND DISASTER MANAGEMENT ppt.pptx
PRADEEP ABOTHU
 
DIGESTION OF CARBOHYDRATES ,PROTEINS AND LIPIDS
raviralanaresh2
 
Lesson 1 - Nature of Inquiry and Research.pdf
marvinnbustamante1
 
How to Manage Expiry Date in Odoo 18 Inventory
Celine George
 
WATERSHED MANAGEMENT CASE STUDIES - ULUGURU MOUNTAINS AND ARVARI RIVERpdf
Ar.Asna
 
Introduction to Indian Writing in English
Trushali Dodiya
 
Indian National movement PPT by Simanchala Sarab, Covering The INC(Formation,...
Simanchala Sarab, BABed(ITEP Secondary stage) in History student at GNDU Amritsar
 
ENGlish 8 lesson presentation PowerPoint.pptx
marawehsvinetshe
 
Ward Management: Patient Care, Personnel, Equipment, and Environment.pptx
PRADEEP ABOTHU
 
Marketing Management PPT Unit 1 and Unit 2.pptx
Sri Ramakrishna College of Arts and science
 
How to Create & Manage Stages in Odoo 18 Helpdesk
Celine George
 
Android Programming - Basics of Mobile App, App tools and Android Basics
Kavitha P.V
 
CAD25 Gbadago and Fafa Presentation Revised-Aston Business School, UK.pdf
Kweku Zurek
 
Life and Career Skills Lesson 2.pptxProtective and Risk Factors of Late Adole...
ryangabrielcatalon40
 
Ad

Master of computer application python programming unit 3.pdf

  • 1. UNIT 3 OBJECTS , CLASSES & FILES
  • 2. Python OOPs Concepts Like other general-purpose programming languages, Python is also an object-oriented language since its beginning. It allows us to develop applications using an Object-Oriented approach. In Python, we can easily create and use classes and objects. An object-oriented paradigm is to design the program using classes and objects. The object is related to real-word entities such as book, house, pencil, etc. The oops concept focuses on writing the reusable code. It is a widespread technique to solve the problem by creating objects.
  • 3. Major principles of object-oriented programming system are given below. 1. Class 2. Object 3. Method 4. Inheritance 5. Polymorphism 6. Data Abstraction 7. Encapsulation
  • 4. Class The class can be defined as a collection of objects. It is a logical entity that has some specific attributes and methods. For example: if you have an employee class, then it should contain an attribute and method, i.e. an email id, name, age, salary, etc. Syntax class ClassName: <statement-1> . . <statement-N> A class is a blueprint for the object Example: class car: def __init__(self,modelname, year): self.modelname = modelname self.year = year def display(self): print(self.modelname,self.year)
  • 5. Object The object is an entity that has state and behavior. It may be any real-world object like the mouse, keyboard, chair, table, pen, etc. Everything in Python is an object, and almost everything has attributes and methods. All functions have a built-in attribute __doc__, which returns the docstring defined in the function source code. When we define a class, it needs to create an object to allocate the memory. Example: Example: class car: def __init__(self,modelname, year): self.modelname = modelname self.year = year def display(self): print(self.modelname,self.year) c1 = car("Toyota", 2016) c1.display()
  • 6. The __init__() Function All classes have a function called __init__(), which is always executed when the class is being initiated. Use the __init__() function to assign values to object properties, or other operations that are necessary to do when the object is being created: The first argument of every method is a reference to the current instance of the class By convention, we name this argument self In __init__, self refers to the object currently being created; so, in other class methods, it refers to the instance whose method was called Similar to the keyword this in Java or C++.
  • 7. Example Create a class named Person, use the __init__() function to assign values for name and age: class Person: def __init__(self, name, age): self.name = name self.age = age p1 = Person("John", 36) print(p1.name) print(p1.age)
  • 8. Object Methods Example Insert a function that prints a greeting, and execute it on the p1 object: class Person: def __init__(self, name, age): self.name = name self.age = age def myfunc(self): print("Hello my name is " + self.name) p1 = Person("John", 36) p1.myfunc()
  • 9. The self Parameter The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class. It does not have to be named self , you can call it whatever you like, but it has to be the first parameter of any function in the class: Example Use the words mysillyobject and abc instead of self: class Person: def __init__(mysillyobject, name, age): mysillyobject.name = name mysillyobject.age = age def myfunc(abc): print("Hello my name is " + abc.name) p1 = Person("John", 36) p1.myfunc()
  • 10. Inheritance Inheritance is the most important aspect of object-oriented programming, which simulates the real-world concept of inheritance. It specifies that the child object acquires all the properties and behaviors of the parent object. By using inheritance, we can create a class which uses all the properties and behavior of another class. The new class is known as a derived class or child class, and the one whose properties are acquired is known as a base class or parent class. It provides the re-usability of the code.
  • 11. # parent class class Bird: def __init__(self): print("Bird is ready") def whoisThis(self): print("Bird") def swim(self): print("Swim faster") # child class class Penguin(Bird): def __init__(self): # call super() function super().__init__() print("Penguin is ready") def whoisThis(self): print("Penguin") def run(self): print("Run faster") peggy = Penguin() peggy.whoisThis() peggy.swim() peggy.run()
  • 12. Encapsulation Using OOP in Python, we can restrict access to methods and variables. This prevents data from direct modification which is called encapsulation. In Python, we denote private attributes using underscore as the prefix i.e single _ or double __. class Computer: def __init__(self): self.__maxprice = 900 def sell(self): print("Selling Price: {}".format(self.__maxprice)) def setMaxPrice(self, price): self.__maxprice = price c = Computer() c.sell() # change the price c.__maxprice = 1000 c.sell() # using setter function c.setMaxPrice(1000) c.sell()
  • 13. Polymorphism Polymorphism is an ability (in OOP) to use a common interface for multiple forms (data types). Suppose, we need to color a shape, there are multiple shape options (rectangle, square, circle). However we could use the same method to color any shape. This concept is called Polymorphism. class Parrot: def fly(self): print("Parrot can fly") def swim(self): p print("Parrot can't swim") class Penguin: def fly(self): print("Penguin can't fly") def swim(self): print("Penguin can swim") # common interface def flying_test(bird): bird.fly() #instantiate objects blu = Parrot() peggy = Penguin() # passing the object flying_test(blu) flying_test(peggy)
  • 14. File Objects in Python
  • 15. Files Files are named locations on disk to store related information. They are used to permanently store data in a non-volatile memory (e.g. hard disk). Since Random Access Memory (RAM) is volatile (which loses its data when the computer is turned off), we use files for future use of the data by permanently storing them. 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 the resources that are tied with the file are freed. Hence, in Python, a file operation takes place in the following order: 1. Open a file 2. Read or write (perform operation) 3. Close the file
  • 16. 1 . Python File Open - The key function for working with files in Python is the open() function. The open() function takes two parameters; filename, and mode. There are four different methods (modes) for opening a file: 1. "r" - Read - Default value. Opens a file for reading, error if the file does not exist 2. "a" - Append - Opens a file for appending, creates the file if it does not exist 3. "w" - Write - Opens a file for writing, creates the file if it does not exist 4. "x" - Create - Creates the specified file, returns an error if the file exists Syntax - f = open("demofile.txt") f = open("demofile.txt", "rt")
  • 17. Mode Description r Opens a file for reading. (default) w Opens a file for writing. Creates a new file if it does not exist or truncates the file if it exists. x Opens a file for exclusive creation. If the file already exists, the operation fails. a Opens a file for appending at the end of the file without truncating it. Creates a new file if it does not exist. t Opens in text mode. (default) b Opens in binary mode. + Opens a file for updating (reading and writing)
  • 18. 2 . Python File Read - 1. The open() function returns a file object, which has a read() method for reading the content of the file: Example f = open("demofile.txt", "r") print(f.read()) 2. If the file is located in a different location, you will have to specify the file path, like this: Example f = open("D:myfileswelcome.txt", "r") print(f.read()) 3. By default the read() method returns the whole text, but you can also specify how many characters you want to return: Example f = open("demofile.txt", "r") print(f.read(5))
  • 19. 3 . Python Write/Create File - 1. Write to an Existing File To write to an existing file, you must add a parameter to the open() function: "a" - Append - will append to the end of the file "w" - Write - will overwrite any existing content 2. Create a File To create a new file in Python, use the open() method, with one of the following parameters: "x" - Create - will create a file, returns an error if the file exist "a" - Append - will create a file if the specified file does not exist "w" - Write - will create a file if the specified file does not exist
  • 20. Method Description close() Closes the file detach() Returns the separated raw stream from the buffer fileno() Returns a number that represents the stream, from the operating system's perspective flush() Flushes the internal buffer isatty() Returns whether the file stream is interactive or not read() Returns the file content readable() Returns whether the file stream can be read or not readline() Returns one line from the file readlines() Returns a list of lines from the file seek() Change the file position seekable() Returns whether the file allows us to change the file position tell() Returns the current file position truncate() Resizes the file to a specified size writable() Returns whether the file can be written to or not write() Writes the specified string to the file writelines() Writes a list of strings to the file Built –in methods in python
  • 21. Command Line Arguments in Python The arguments that are given after the name of the program in the command line shell of the operating system are known as Command Line Arguments. Python provides various ways of dealing with these types of arguments. The three most common are: 1. Using sys.argv 2. Using getopt module 3. Using argparse module
  • 22. Using sys.argv The sys module provides functions and variables used to manipulate different parts of the Python runtime environment. This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter. One such variable is sys.argv which is a simple list structure. It’s main purpose are: 1. It is a list of command line arguments. 2. len(sys.argv) provides the number of command line arguments. 3. sys.argv[0] is the name of the current Python script.
  • 23. # Python program to demonstrate # command line arguments import sys # total arguments n = len(sys.argv) print("Total arguments passed:", n) # Arguments passed print("nName of Python script:", sys.argv[0]) print("nArguments passed:", end = " ") for i in range(1, n): print(sys.argv[i], end = " ") # Addition of numbers Sum = 0 # Using argparse module for i in range(1, n): Sum += int(sys.argv[i]) print("nnResult:", Sum)
  • 24. Using getopt module Python getopt module is similar to the getopt() function of C. Unlike sys module getopt module extends the separation of the input string by parameter validation. It allows both short, and long options including a value assignment. However, this module requires the use of the sys module to process input data properly. To use getopt module, it is required to remove the first element from the list of command-line arguments. Syntax: getopt.getopt(args, options, [long_options]) Parameters: args: List of arguments to be passed. options: String of option letters that the script want to recognize. Options that require an argument should be followed by a colon (:). long_options: List of string with the name of long options. Options that require arguments should be followed by an equal sign (=). Return Type: Returns value consisting of two elements: the first is a list of (option, value) pairs. The second is the list of program arguments left after the option list was stripped.
  • 25. Using argparse module Using argparse module is a better option than the above two options as it provides a lot of options such as positional arguments, default value for arguments, help message, specifying data type of argument etc. Note: As a default optional argument, it includes -h, along with its long version –help.