Nothing Special   »   [go: up one dir, main page]

Jcs2201-Python Programming Unit-I Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 42

JCS2201 PYTHON PROGRAMMING

UNIT I INTRODUCTION TO PYTHON PROGRAMMING

Introduction to Python

 A Python program is read by a parser. Python was designed to be a highly readable


language.

 The syntax of the Python programming language is the set of rules which defines how a
Python program will be written.

What is python?

⮚ Python is a general purpose, interpreted, open source, object-oriented, high-level powerful


programming language.
⮚ Developed by Guido van Rossum in Netherland at early 1990s. Named after Monty Python
⮚ It is widely used in industry due to simple, coincise, and large library 7 easy syntax.
⮚ Python runs on many Unix variants, on the Mac, and on Windows 2000 and later.

History
⮚ The name Python was selected from "Monty Python’s Flying Circus" which was a British
sketch comedy series created by the comedy group Monty Python and broadcast by the BBC
from 1969 to 1974.
⮚ Python was created in the early 1990s by Guido van Rossum at the National Research
Institute for Mathematics and Computer Science in Netherlands.
⮚ Python was created as a successor of a language called ABC (All Basic Code) and released
publicly in1991. Guido remains Python’s principal author, although it includes many
contributions from active user community.
⮚ Between 1991 and 2001 there are several versions released, current stable release is 3.2.
In 2001 the Python Software Foundation (PSF) was formed, a non-profit organization
created specifically to own Python-related Intellectual Property. Zope Corporation is a
sponsoring member of the PSF.
Features of Python

1. General purpose language:

⮚ It means that you can use python to write code for any program task.
⮚ Nowadays, python is used in google, NASA, New York stock exchange.
2. Interpreted :
⮚ Python programs are interpreted, takes source code as input, by the interpreter (to
portable byte-code) one statement at a time and executes it immediately.
⮚ No need to compiling or linking.
3. Object-Oriented :
⮚ Data in python are object created from class. A class is essentially a type or category
that define objects of same kind with properties and methods for manipulating objects.
⮚ Python is a full-featured object-oriented programming language, with features such as
classes, inheritance, objects, and overloading.

4. Open source:
⮚ Python is publicly available open source software, anyone can use source code that
doesn’t cost anything.

5. Easy-to-learn :

⮚ Popular (scripting/extension) language, clear and easy syntax, no type declarations.


⮚ Automatic memory management, high-level data types and operations, design to read
(more English like syntax) and write (shorter code compared to C, C++, and Java) fast.

6. Portable :
⮚ High level languages are portable, which means they are able to run across all major
hardware and software platforms with few or no change in source code. ⮚ Python is
portable and can be used on Linux, Windows, Macintosh, Solaris, FreeBSD, OS/2,
Amiga, AROS, AS/400 and many more.
7. High-level Language :

⮚ High-level language (closer to human) refers to the higher level of concept from
machine language (for example assembly languages).
⮚ Python is an example of a high-level language like C, C++, Perl, and Java with low
level optimization.

8. Python is Interactive :

⮚ Python has an interactive console where you get a Python prompt (command line) and
interact with the interpreter directly to write and test your programs.
⮚ This is useful for mathematical programming.

9. Extendable :

⮚ Python is often referred to as a “glue” language, meaning that it is capable to work in


mixed-language environment.
⮚ The Python interpreter is easily extended and can add a new built-in function or
modules written in C/C++/Java code.
10 .Libraries :

⮚ Databases, web services, networking, numerical packages, graphical user interfaces, 3D


graphics, others.

11. Supports: Support from online Python community.

INSTALLATION OF PYTHON

 Python is a widely used high-level programming language. To write and execute code
in python, we first need to install Python on our system.

 Installing Python on Windows takes a series of few easy steps.

Step 1 − Select Version of Python to Install

Python has various versions available with differences between the syntax and working of
different versions of the language. We need to choose the version which we want to use or
need. There are different versions of Python 2 and Python 3 available.
Step 2 − Download Python Executable Installer

On the web browser, in the official site of python (www.python.org), move to the Download
for Windows section.

All the available versions of Python will be listed. Select the version required by you and click
on Download. Let suppose, we chose the Python 3.9.1 version.

On clicking download, various available executable installers shall be visible with different
operating system specifications. Choose the installer which suits your system operating system
and download the installer. Let suppose, we select the Windows installer(64 bits).

The download size is less than 30MB.

Step 3 − Run Executable Installer


 We downloaded the Python 3.9.1 Windows 64 bit installer.

 Run the installer. Make sure to select both the checkboxes at the bottom and then click Install
New.
On clicking the Install Now, The installation process starts.

The installation process will take few minutes to complete and once the installation is
successful, the following screen is displayed.
Step 4 − Verify Python is installed on Windows
To ensure if Python is succesfully installed on your system. Follow
the given steps − ∙ Open the command prompt.
∙ Type ‘python’ and press enter.
∙ The version of the python which you have installed will be displayed if the python is
successfully installed on your windows.

Step 5 − Verify Pip was installed


 Pip is a powerful package management system for Python software packages. Thus, make sure
that you have it installed.

 To verify if pip was installed, follow the given steps −

∙ Open the command prompt.

∙ Enter pip –V to check if pip was installed.

∙ The following output appears if pip is installed successfully.


We have successfully installed python and pip on our Windows system.

RUNNING PYTHON PROGRAM

Python programmers must know every possible way to run the Python scripts or code. This is
the only way to verify whether code is working as we want. Python Interpreter is responsible for
executing the Python scripts. Python interpreter is a piece of software which works between the
Python program and computer hardware

Here we are describing the series of ways to run Python scripts.


 The operating system command-line or terminal.
 The Python interactive mode.
 The IDE or Text editor
 The file manager of system.
 The operating system command-line or Terminal

We can run the Python code using a command line because in Python shell once we close the
session, we will lose the complete code that we have written. So it is good to write a Python
code using the plain text files. The text file must save as .py extension.

Using the Python command line


 Open the command line to run a Python script. We need to type the python, followed by the file
name to execute the file. Now, hit the enter key, and if there is no the error in file.
 The Python interactive mode.
 To run the Python code, we can use the Python interactive session. We need to start Python interactive session,
just open a command-line or terminal in start menu, then type in python, and press enter key.
 It allows us to check every piece of code, and this facility makes it an awesome development tool. But
once we close the session it will lose all code that we have written.
Python Line Structure
 A Python program is divided into a number of logical lines and every logical line is terminated by the
token NEWLINE. A logical line is created from one or more physical lines. A line contains only spaces,
tabs, form feeds possibly a comment, is known as a blank line, and Python interpreter ignores it.

 A physical line is a sequence of characters terminated by an end-of-line sequence (in windows it is


called CR LF or return followed by a linefeed and in Unix, it is called LF or linefeed). See the following
example.

Comments in Python
A comment begins with a hash character (#) which is not a part of the string literal and ends at
the end of the physical line. All characters after the # character up to the end of the line are part
of the comment and the Python interpreter ignores them. See the following example. It should
be noted that Python has no multi-lines or block comments facility.
Joining two lines
When you want to write a long code in a single line you can break the logical line in two or
more physical lines using backslash character (\). Therefore, when a physical line ends with
a backslash characters(\) and not a part of a string literal or comment then it can join
another physical line. See the following example.

Multiple Statements on a Single Line

You can write two separate statements into a single line using a semicolon (;) character between
two line.
Indentation
Python uses whitespace (spaces and tabs) to define program blocks whereas other languages
like C, C++ use braces ({}) to indicate blocks of codes for class, functions or flow control. The
number of whitespaces (spaces and tabs) in the indentation is not fixed, but all statements
within the block must be the indented same amount. In the following program, the block
statements have no indentation.

This is a program with single space indentation.

This is a program with single tab indentation.


Here is an another program with an indentation of a single space + a single tab.

Python Coding Style

 Use 4 spaces per indentation and no tabs.


 Do not mix tabs and spaces. Tabs create confusion and it is recommended to use only
spaces.
 Maximum line length : 79 characters which help users with a small display.
 Use blank lines to separate top-level function and class definitions and single blank line to
separate methods definitions inside a class and larger blocks of code inside functions.
 When possible, put inline comments (should be complete sentences).
 Use spaces around expressions and statements.

PYTHON INTERPRETER AND INTERACTIVE MODE:


Assume that you have installed python on your computer. You can start the python shell by start
typing IDLE (Integrated Development Environment) in search option.
 Once you clicked IDLE option a new window will open as seen below with sign (>>>)
 This >>> symbol is called python statement prompt.
⮚ In the interactive mode you can able to type program and execute but cannot able to save
the program for future use.
⮚ If you want to save your program, then you have to use the interpreter in script mode by
creating a new file from file option in the python shell.
⮚ A new text editor will open like notepad then you can type your program and save the file
with extension filename.py
⮚ If you want to run the program, then press F5 or click select run module under Run menu.

TOKENS

Def: The smallest individual unit element in the program is known as token or lexical unit.

⮚ Python has following tokens:


1. Keywords

2. Identifiers

3. Literals

4. Operators

5. Punctuators

6. Special characters
1. Keywords:
⮚ Keyword is also reserved words that have particular meaning and usage in the language.
⮚ User cannot edit the meaning or usage of the keywords he can only able to use them.
⮚ Keywords cannot be used as a identifier or variable name.
⮚ Following table contains the keywords of the python.

False class finally is return

None continue for lambda try

True def from nonlocal while

And del global not with

As elif if or yield

Assert else import pass return

Break except in raise

2. Identifiers & variables:

Identifiers:
⮚ It is the fundamental building blocks of program and are used as general terminology for
names given to different parts of the program viz, variables, objects, classes, function, list,
dictionaries, etc

Variables

⮚ A variable is a memory location where a programmer can store a value.


⮚ Example: roll_no, amount, name etc.
⮚ Value is either string, numeric etc. Example : "Sara", 120, 25.36
⮚ Variables are created when first assigned.
⮚ Variables must be assigned before being referenced.
⮚ The value stored in a variable can be accessed or updated later.
⮚ No prior declaration required.
⮚ The type (string, int, float etc.) of the variable is determined by Python.
⮚ The interpreter allocates memory on the basis of the data type of a variable.

Rules for declaring python variable names & identifiers:

⮚ Must begin with a letter (a - z, A - B) or underscore (_)


⮚ Other characters can be letters, numbers or _
⮚ Not a Case Sensitive
⮚ Can be any (reasonable) length
⮚ There are some reserved words which you cannot use as a variable name because Python
uses them for other things.

Good Variable Name


⮚ Choose meaningful name instead of short name. roll_no is better than rn.
⮚ Maintain the length of a variable name. Roll_no_of_a-student is too long?
⮚ Be consistent; roll_no or or RollNo
⮚ Begin a variable name with an underscore(_) character for a special case.

3. Literals:

⮚ Literals are data items that have fixed value. Python allows several kinds of literals:
1. String literals
2. Numeric literals
3. Boolean literals
4. Special None

Please refer above topic 2.2 Values & types for example and notes.

4. Punctuators:

⮚ Punctuators are the symbols used in programming language to organize sentence structure,
and indicate the rhythm and emphasis of expressions, statements, and program structure.

⮚ Examples: “‘#\()[]{},:.`=;
5. Special characters in strings

The backslash (\) character is used to introduce a special character. See the following table.

Escape Meaning
sequence

\n Newline

\t Horizontal Tab

\\ Backslash

\' Single Quote

\" Double Quote

Python Interpreter

 In interactive mode, type Python programs and the interpreter displays the
result: ∙ Type python into your terminal's command line.
 After a short message, the >>> symbol will appear.
 The above symbol signals the start of a Python interpreter's command
line. ∙ Python interpreter evaluates inputs.
(For example >>> 4*(6-2) return 16)

How stable is Python?


⮚ Very stable. New, stable releases have been coming out roughly every 6 to 18 months since
1991, and this seems likely to continue.
⮚ Currently there are usually around 18 months between major releases.
⮚ The latest stable releases can always be found on the Python download page. There is two
recommended production-ready versions at this point in time, because at the moment there are
two branches of stable releases: 2.x and 3.x.
⮚ Python 3.x may be less useful than 2.x, since currently there is more third party software
available for Python 2 than for Python 3. Python 2 code will generally not run unchanged in
Python 3.
INDENTATION

Python uses whitespace (spaces and tabs) to define program blocks whereas other languages
like C, C++ use braces ({}) to indicate blocks of codes for class, functions or flow control.

The number of whitespaces (spaces and tabs) in the indentation is not fixed, but all statements
within the block must be the indented same amount. In the following program, the block
statements have no indentation.

This is a program with single space indentation.


This is a program with single tab indentation.

Here is another program with an indentation of a single space + a single tab.


Python Coding Style
 Use 4 spaces per indentation and no tabs.
 Do not mix tabs and spaces. Tabs create confusion and it is recommended to use only spaces.
 Maximum line length : 79 characters which help users with a small display.
 Use blank lines to separate top-level function and class definitions and single blank line to separate
methods definitions inside a class and larger blocks of code inside functions.
 When possible, put inline comments (should be complete sentences).
 Use spaces around expressions and statements.

COMMENTS

 As programs get bigger and more complicated, they get more difficult to read. Formal languages are dense,
and it is often difficult to look at a piece of code and figure out what it is doing, or why.
 For this reason, it is a good idea to add notes to your programs to explain in natural language what the
program is doing. These notes are called comments, and they start with the # symbol
#This is a comment
#print out Hello
print('Hello')
⮚Everything from the # to the end of the line is ignored—it has no effect on the execution of
the program.
⮚Comments are most useful when they document non-obvious features of the code. It is
reasonable to assume that the reader can figure out what the code does; it is more useful to
explain why.
⮚Another way of doing this is to use triple quotes, either ''' or """.
⮚These triple quotes are generally used for multi-line strings. But they can be used
as multi-line comment as well. Unless they are not docstrings, they do not
generate any extra code.
⮚"""This is also a
⮚perfect example of
⮚multi-line comments"""
⮚Good variable names can reduce the need for comments, but long names can make
complex expressions hard to read, so there is a tradeoff.

Variables

⮚A variable is a memory location where a programmer can store a value.


⮚Example: roll_no, amount, name etc.
⮚Value is either string, numeric etc. Example : "Sara", 120, 25.36
⮚Variables are created when first assigned.
⮚Variables must be assigned before being referenced.
⮚The value stored in a variable can be accessed or updated later.
⮚No prior declaration required.
⮚The type (string, int, float etc.) of the variable is determined by Python.
⮚The interpreter allocates memory on the basis of the data type of a variable.

Rules for declaring python variable names & identifiers:

⮚Must begin with a letter (a - z, A - B) or underscore (_)


⮚Other characters can be letters, numbers or _
⮚Not a Case Sensitive
⮚Can be any (reasonable) length
Good Variable Name
⮚Choose meaningful name instead of short name. roll_no is better than rn.
⮚Maintain the length of a variable name. Roll_no_of_a-student is too long? ⮚
Be consistent; roll_no or or RollNo
⮚Begin a variable name with an underscore(_) character for a special case.

DATATYPES AND ITS CONVERSION

Datatypes are means to identify the type of data and associated operations of handling it.Python
offers following built in core data types:
1. Numbers ( Int, float, complex numbers)
2. Bool or Boolean
3. String
4. List
5. Tuples
6. Dictionary
7. None
Definition of value:
⮚A value is one of the basic things a program works with, like a letter or a number. Some
values we have seen so far are 2, 42.0, and 'Hello, World!'.

Definition of types:
⮚Type represents the kind of value and determines how the value can be used. All data values
in Python are encapsulated in relevant object classes.
⮚Everything in Python is an object and every object has an identity, a type, and a value.
⮚Like another object-oriented language such as Java or C++, there are several data types
which are built into Python.
⮚Extension modules which are written in C, Java, or other languages can define additional
types.
⮚To determine a variable's type in Python you can use the type() function. The value of
some objects can be changed. Objects whose value can be changed are called mutable
and objects whose value is unchangeable (once they are created) are called immutable.
Here are the details of Python data types.

⮚These values belong to different types: 2 is an integer, 42.0 is a floating-point number,


and 'Hello, World!' is a string, so-called because the letters it contains are strung together.

Python defines type conversion functions to directly convert one data type to another which is
useful in day-to-day and competitive programming. This article is aimed at providing information
about certain conversion functions.

There are two types of Type Conversion in Python:

1. Python Implicit Type Conversion


2. Python Explicit Type Conversion

Implicit Type Conversion in Python


In Implicit type conversion of data types in Python, the Python interpreter automatically converts one
data type to another without any user involvement.

x = 10
print("x is of type:",type(x))
y = 10.6
print("y is of type:",type(y))
z=x+y
print(z)
print("z is of type:",type(z))

Output
x is of type: <class 'int'>
y is of type: <class 'float'>
20.6
z is of type: <class 'float'>
Explicit Type Conversion in Python
In Explicit Type Conversion in Python, the data type is manually changed by the user as per
their requirement. With explicit type conversion, there is a risk of data loss since we are forcing an
expression to be changed in some specific data type.

Converting integer to float


int(a, base): This function converts any data type to an integer. ‘Base’ specifies the base in which
the string is if the data type is a string.
float(): This function is used to convert any data type to a floating-point number.

Example:

# initializing string

s = "10010"

# printing string converting to int base 2

c = int(s,2)

print ("After converting to integer base 2 : ", end="")

print (c)

# printing string converting to float

e = float(s)

print ("After converting to float: ", end="")

print (e)

Output:
After converting to integer base 2 : 18
After converting to float : 10010.0
Python Type conversion using tuple(), set(), list()

tuple(): This function is used to convert to a tuple.


set(): This function returns the type after converting to set.
list(): This function is used to convert any data type to a list type.

# initializing string

s = 'Study'

# printing string converting to tuple

c = tuple(s)

print ("After converting string to tuple : ",end="")

print (c)

# printing string converting to set

c = set(s)

print ("After converting string to set : ",end="")

print (c)

# printing string converting to list

c = list(s)

print ("After converting string to list : ",end="")

print (c)

Output:
After converting string to tuple : ('s', 't', 'u', 'd', 'y')
After converting string to set : {'d', 'u', 'y', 's'}
After converting string to list : ['s', 't', 'u', 'd', 'y']
Python code to demonstrate Type conversion using dict(), complex(), str()
dict(): This function is used to convert a tuple of order (key, value) into a dictionary.
str(): Used to convert an integer into a string.
complex(real,imag) : This function converts real numbers to complex(real, imag) number.

# initializing integers

a=1

b=2

# initializing tuple

tup = (('a', 1) ,('f', 2), ('g', 3))

# printing integer converting to complex number

c = complex(1,2)

print ("After converting integer to complex number : ",end="")

print (c)

# printing integer converting to string

c = str(a)

print ("After converting integer to string : ",end="")

print (c)

# printing tuple converting to expression dictionary

c = dict(tup)

print ("After converting tuple to dictionary : ",end="")

print (c)

Output:
After converting integer to complex number : (1+2j)
After converting integer to string : 1
After converting tuple to dictionary : {'a': 1, 'f': 2, 'g': 3}
OPERATORS AND ITS PRECEDENCE

Python Operators

Operators are used to perform operations on variables and values.

Python divides the operators in the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Identity operators
 Membership operators
 Bitwise operators

Python Arithmetic Operators


Python Assignment Operators

Assignment operators are used to assign values to variables.


Python Identity Operators

Identity operators are used to compare the objects, not if they are equal, but if they are actually the same

object, with the same memory location.

Python Membership Operators

Membership operators are used to test if a sequence is presented in an object:


Operator Precedence

Operator precedence describes the order in which operations are performed.

Example

Parentheses has the highest precedence, meaning that expressions inside parentheses must be evaluated first:

print((6 + 3) - (6 + 3))

Example

Multiplication * has higher precedence than addition +, and therefor multiplications are evaluated

before additions:

print(100 + 5 * 3)
EXPRESSIONS IN PYTHON

An expression is a combination of operators and operands that is interpreted to produce some other
value. In any programming language, an expression is evaluated as per the precedence of its operators. So
that if there is more than one operator in an expression, their precedence decides which operation will be
performed first. We have many different types of expressions in Python. Let’s discuss all types along with
some exemplar codes:

1. Constant Expressions: These are the expressions that have constant values only.
# Constant Expressions
x = 15 + 1.3
print(x)
2. Arithmetic Expressions: An arithmetic expression is a combination of numeric values, operators, and
sometimes parenthesis. The result of this type of expression is also a numeric value. The operators used in
these expressions are arithmetic operators like addition, subtraction, etc. Here are some arithmetic operators
in Python:

Example:
# Arithmetic Expressions
x = 40
y = 12

add = x + y
sub = x - y
pro = x * y
div = x / y

print(add)
print(sub)
print(pro)
print(div)
Output
52

28

480

3.3333333333333335

3. Integral Expressions: These are the kind of expressions that produce only integer results after
all computations and type conversions.

Example:
# Integral Expressions
a = 13
b = 12.0
c = a + int(b)
print(c)

Output
25

4. Floating Expressions: These are the kind of expressions which produce floating point numbers as
result after all computations and type conversions.

Example:

# Floating Expressions
a = 13
b=5
c=a/b
print(c)

Output
2.6
5. Relational Expressions: In these types of expressions, arithmetic expressions are written on both sides
of relational operator (>, < , >= , <=). Those arithmetic expressions are evaluated first, and then
compared as per relational operator and produce a boolean output in the end. These expressions are also
called Boolean expressions.
Example:
# Relational Expressions
a = 21
b = 13
c = 40
d = 37
p = (a + b) >= (c - d)
print(p)

Output
True

6. Logical Expressions: These are kinds of expressions that result in either True or False. It basically
specifies one or more conditions. For example, (10 == 9) is a condition if 10 is equal to 9. As we know it
is not correct, so it will return False. Studying logical expressions, we also come across some logical
operators which can be seen in logical expressions most often. Here are some logical operators in Python:

Example:

P = (10 == 9)
Q = (7 > 5)
# Logical Expressions
R = P and Q
S = P or Q
T = not P
print(R)
print(S)
print(T)

Output
False

True

True

7. Bitwise Expressions: These are the kind of expressions in which computations are performed at bit level.

Example:

# Bitwise Expressions
a = 12
x = a >> 2
y = a << 1
print(x, y)

Output
3 24

8. Combinational Expressions: We can also use different types of expressions in a single expression, and that
will be termed as combinational expressions.

Example:
# Combinational Expressions
a = 16
b = 12
c = a + (b >> 1)
print(c)

Output
22
Multiple operators in expression (Operator Precedence)

Operator Precedence simply defines the priority of operators that which operator is to be executed
first. Here we see the operator precedence in Python, where the operator higher in the list has more
precedence or priority:

Precedence Name Operator

1 Parenthesis ()[]{}

2 Exponentiation **

3 Unary plus or minus, complement -a , +a , ~a

4 Multiply, Divide, Modulo / * // %

5 Addition & Subtraction + –

6 Shift Operators >> <<

7 Bitwise AND &

8 Bitwise XOR ^

9 Bitwise OR |

10 Comparison Operators >= <= > <

11 Equality Operators == !=

12 Assignment Operators = += -= /= *=

13 Identity and membership operators is, is not, in, not in

14 Logical Operators and, or, not


So, if we have more than one operator in an expression, it is evaluated as per operator precedence.
For example, if we have the expression “10 + 3 * 4”. Going without precedence it could have given two
different outputs 22 or 52. But now looking at operator precedence, it must yield 22.

# Multi-operator expression
a = 10 + 3 * 4
print(a)
b = (10 + 3) * 4
print(b)
c = 10 + (3 * 4)
print(c)

Output
22

52

22

INPUT AND PRINT FUNCTIONS

Input() Function

We can use the input() function to take input from the user.
# take user input
name = input()
print(name)

Printing Message Before Input

We can also print a message inside the input() function to let users know what they need to enter.
# displaying prompt message before taking input
name = input("Enter name: ")
print(name)

Output:
Enter name: computer
computer
Numeric Input

In Python, the input() function always takes input as a string. We can check this by using the type() function.

# print the type of input.

number = input("Enter a number: ")

print(type(number))

Output
<class 'str'>

Python print()

The print() function prints specified values and variables to the screen.

# print a string

print('Harry Potter')

# print a number

print(50)

number = 400

# print a variable

print(number)

goals = '100'

# strings and variables in the same line

print('Ronaldo has reached ', goals, ' goals')

Output:
Harry Potter
50
400
Ronaldo has reached 100 goals
Here,

 The first print statement prints a string, the second prints an integer, and the third one prints a variable.

 The final print statement takes a string variable and prints it along with the rest of the string in the statement.

COMMAND-LINE ARGUMENTS:

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:
 Using sys.argv
 Using getopt module
 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:

 It is a list of command line arguments.


 len(sys.argv) provides the number of command line arguments.
 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("\n\nResult:", Sum)

Output:

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 inpu t 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.

Example:

# Python program to demonstrate

# command line arguments

import getopt, sys

# Remove 1st argument from the

# list of command line arguments

argumentList = sys.argv[1:]

# Options

options = "hmo:"

# Long options

long_options = ["Help", "My_file", "Output="]

try:

# Parsing argument

arguments, values = getopt.getopt(argumentList, options, long_options)

# checking each argument

for currentArgument, currentValue in arguments:

if currentArgument in ("-h", "--Help"):

print ("Displaying Help")


elif currentArgument in ("-m", "--My_file"):

print ("Displaying file_name:", sys.argv[0])

elif currentArgument in ("-o", "--Output"):

print (("Enabling special output mode (% s)") % (currentValue))

except getopt.error as err:

# output error, and return with an error code

print (str(err))

Output:

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.
Example 1: Basic use of argparse module.

# Python program to demonstrate


# command line arguments
import argparse
# Initialize parser
parser = argparse.ArgumentParser()
parser.parse_args()
Output:

------------------------------------------------------------

You might also like