Professional Documents
Culture Documents
Python Scripting1 1627728722468
Python Scripting1 1627728722468
Unit -1
Why Python?
• wide range of libraries for open source data
analysis tools, web frameworks, testing, and so
on
• can be used on different platforms (Windows,
Mac, Linux, and embedded Linux H/W platforms,
such as Raspberry Pi).
• Developers canwrite programs with fewer lines
• Prototyping is very quick, as Python runs on an
interpreter system
Why Python?
• can be treated in an object-oriented, a
procedural, or a functional way.
• great feature: indentation.
• Using indentations, we can define the scope
for decision-making statements, loops such as
for and while loops, functions, and classes.
Python installation
• Installation on the Linux platform
– To install python3 on Debian-based Linux
• sudo apt install python3
– To install python3 on centos
• sudo yum install python3
– https://www.python.org/downloads/
Installation on the Windows
platform
• download the executable from python.org and
install it.
• Download python.exe from
• https://www.python.org/downloads/
Output:
The sum is 1
The sum is 3
The sum is 6
The sum is 10
The sum is 15
The sum is 21
The sum is 28
The sum is 36
The sum is 45
The sum is 55
Dictionaries
• A dictionary is a data type in Python, which
consists of key value pairs and is enclosed in
curly braces {}.
• Dictionaries are unordered and indexed by
keys, where each key must be unique.
• These keys must be immutable type.
• Tuples can be used as keys if they contain only
strings, numbers, or tuples.
Dictionaries
>>> student = {'Name':'John', 'Age':25}
>>> student['Address'] = 'Mumbai'
>>> student
student = {'Name':'John', 'Age':25, 'Address':'Mumbai'}
>>> student['Age']
25
>>> del student['Address']
>>> student
student = {'Name':'John', 'Age':25}
>>> list(student.keys())
['Name', 'Age']
>>> sorted(student.keys())
['Age', 'Name']
>>> 'Name' in student
True
>>> 'Age' not in student
False
Dictionaries
• Arbitrary key and value expressions along with
dictionary comprehensions are used to create
dictionaries:
• >>> {x: x**2 for x in (4, 6, 8)}
• {4: 16, 6: 36, 8: 64}
• When the keys are simple strings, it is sometimes
easier to specify pairs using keyword arguments:
• >>> dict(John=25, Nick=27, Jack=28)
• {'Nick': 27, 'John': 25, 'Jack': 28}
Parsing command-line arguments
• $ python program_name.py img.jpg
• Here, program_name.py and img.jpg are
arguments.
Module Use Python version
optparse Deprecated < 2.7
sys All arguments in All
sys.argv (basic)
argparse Building a command- >= 2.3
line interface
fire Automatically All
generating
Command-Line
Interfaces (CLIs)
docopt Creating CLIs >= 2.5
interfaces
Sys.argv
• The sys module is used to access command-line
parameters.
• The len(sys.argv) function contains the number of
arguments.
• To print all of the arguments, simply execute str(sys.argv).
• example: 01.py
import sys
print('Number of arguments:', len(sys.argv))
print('Argument list:', str(sys.argv))
Output:
Python3 01.py img
Number of arguments 2
Arguments list: ['01.py', 'img']
The range() function
• range() function will generate a sequence of
numbers.
• For example, range(10) will generate numbers
from 0 to 9 (10 numbers).
• We can also define the start, stop, and step
size as parameters and range() will be as
follows:
• range(start, stop, step size).
• Step size defaults to 1 if not provided.
• For loop example using range() function:
• for i in range(5):
• print("The number is", i)
Output:
• The number is 0
• The number is 1
• The number is 2
• The number is 3
• The number is 4
Iterators
• Iterator is an object that can be iterated upon.
• It is an object that will return data, one
element at a time.
• Python's iterator object implements two
methods, __iter__() and __next__().
• Mostly, iterators are implemented within
loops, generators, and comprehensions.
using the next() function
numbers = [10, 20, 30, 40]
numbers_iter = iter(numbers)
print(next(numbers_iter))
print(next(numbers_iter))
print(numbers_iter.__next__())
print(numbers_iter.__next__())
next(numbers_iter)
Output:
10
20
30
40
Traceback (most recent call last):
File "sample.py", line 10, in <module>
next(numbers_iter)
StopIteration
• After reaching the end and there is no more data to be returned, it will raise
StopIteration
Generators
• A generator is a function that returns an
object that we can iterate over.
• We can create a generator just by defining a
function with a yield statement instead of a
return statement.
• If a function contains at least one yield
statement, it becomes a generator function.
• yield and return statements will return some
value from a function.
• Here is an example:
Generators
def my_gen():
n=1
print('This is printed first')
yield n
n += 1
print('This is printed second')
yield n
n += 1
print('This is printed at last')
yield n
for item in my_gen():
print(item)
Output:
This is printed first
1
This is printed second
2
This is printed at last
3
Functions
• A function is a set of statements that perform a
specific task.
• Usingfunctions helps in breaking our program
into smaller parts.
• Programs will be more organized if we use
functions as it avoids repetition and makes code
reusable.
syntax:
def function_name(parameters):
statement(s)
Functions - Example
def welcome(name):
print("Hello " + name + ", Welcome to Python
Programming !")
welcome("John")
Output:
Hello John, Welcome to Python Programming !
return statement
• The return statement is used to exit a function. Refer to the following
syntax:
return [expression_list]
• This statement may contain an expression where a value has to be
returned.
• If there is no expression, then the function will return a None object
• Example:
def return_value(a):
if a >= 0:
return a
else:
return -a
print(return_value(2))
print(return_value(-4))
Output:
24
Lambda functions
• In Python, an anonymous function is a
function that is defined without a name and is
called a lambda function, as it is defined using
a keyword lambda.
• We use these functions whenever we require
a function for a short period of time.
• Lambda functions are used along with built-in
functions, such as filter(), and map().
• The filter() function returns a list of elements and
has only one iterable as input.
• The following shows an example using filter():
• numbers = [10, 25, 54, 86, 89, 11, 33, 22]
• new_numbers = list(filter(lambda x: (x%2 == 0) ,
numbers))
• print(new_numbers)
Output:
[10, 54, 86, 22]
• The map() function returns a list of results
after applying the specified function.
• Example using map():
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(map(lambda x: x * 2 , my_list))
print(new_list)
Output:
[2, 10, 8, 12, 16, 22, 6, 24]
Modules
• Modules are just files that contain Python statements
and definitions.
• A file that contains Python code (for example,
sample.py) is called a module and its module name
would be sample.
• Using modules, we can break larger programs into
small and organized ones.
• An important feature of a module is re-usability.
• Instead of copying the definitions of the most used
functions in different programs, you can define them in
the module and just import them whenever needed.
create a module and import it
• create two scripts: sample.py and add.py.
• We will import a sample module in our
add.py.
• Now, save the following code as sample.py.
• sample.py
def addition(num1, num2):
result = num1 + num2
return result
Importing modules
• Now we will import the sample module in add.py
script:
• add.py
import sample
sum = sample.addition(10, 20)
print(sum)
Output:
30