UNI T- 3
StringSlicing
String slicingin Python is a way to get specific parts of a string by
using start, end, and step values. I t’s especially useful for text
manipulation and
data parsing. St ring slicing is a way of creat ing a sub- st ring from a given st
ring. I n
t his process, we ext ract a port ion or piece of a st ring. Usually, we use t he
slice operat or " [ : ] " to perf orm slicing on a Pyt hon St ring.
St ri ng I ndexi ng
Pyt hon allows you to access any individual charact er from t he st ring by its
index. Example:
var = " HELLO PYTHON"
print ( var[ 0] )
print ( var[ 7]
) print
( var[ 11] )
print
( var[ 12] )
Pyt hon St ri ng Negat i ve & Posi t i ve I ndexi ng
One of t he unique f eat ures of Pyt hon sequence types ( and t heref ore a st ring obj
ect ) is t hat it has a negat ive indexing scheme also. I n t he example above, a posit
ive indexing scheme is used where t he index increment s from lef t to right . I n case
of negat ive
indexing, t he charact er at t he end has - 1 index and t he index decrement s from
right to lef t , as a result t he first charact er H has - 12 index.
2.
St ri ngSli ci ng
Pyt hon def ines " :" as st ring slicing operat or. I t ret urns a subst ring from t he
original st ring. I ts general usage is as f ollows −
subst r=var[ x:y]
The " :" operat or needs t wo int eger operands ( bot h of which may be omit t ed,
The first operand x is t he index of t he first charact er of t he desired slice. The
second operand y is t he index of t he charact er next to t he last in t he desired st
ring. So
var( x:y] separat es charact ers from xth posit ion to ( y- 1) th posit ion from t he
original st ring.
var=" HELLO PYTHON" print ( " var:" , var) print ( " var[ 3:8] :" , var[ 3:8] )
Functions
Functionsis a block of statements that return the specific task. The idea
is to put some commonly or repeatedly done tasks together and make a
function so that instead of writing the same code again and again for
different inputs,
we can do the function calls to reuse code contained in it over and over
again.
Funct i on Declarat i on
def f unct ion_ name( paramet er: dat a_ type) - > ret urn_
type: " " " Docst ring" " "
# body of t he f unct ion
3.
Creat i nga Funct i on
Function in Python are created using the def keyword
def f unct ion1( ) :
print ( " Hello! Welcome to Pyt
hon." ) # Calling t he f unct ion
f unct ion1( )
Calli ng a Functi on
After creating a function we can call it by using the name of the
functions Python followed by parenthesis containing parameters of that
particular
function.
Example:
def f unct ion1( ) :
print ( " Hello! Welcome to Pyt
hon." ) # Calling t he f unct ion
f unct ion1( )
ADVANTAGES OF FUNCTI ON
Advantages of Functions in
Python
1.Code Reusabilit y
2. Easier Debugging & Maint
enance
3. Flexibilit y wit h Paramet ers
4.
These functions acceptparameters ( arguments) to process and return
results dynamically. Parameters allow for flexibility, enabling the
function to handle different inputs each time it is called.
Example:
# functi on defi ni ti
on def functi
on1( name) :
pri nt( " Hello," ,
name)
# functi on call
functi on1( " RI YA" )
2. Functi ons
wi th def ault
arguments
A function can have default values assigned to its parameters. I f no
argument is provided when calling the function, it takes the default value.
Example:
# functi on defi ni ti
on: def functi on1( x,
y=50) : pri nt( " x:" ,
x)
pri nt( " y:" , y)
# functi on call
5.
Functi on1( 10)
3.Keyword argument f uncti ons
Function arguments can be passed using keywords to improve code
readability. This ensures the correct mapping of values to parameters,
regardless of their order.
Example:
# functi on defi ni ti
on def fun( name,
age) :
pri nt( name, " i
s" , age, " years
old." )
# functi on call
fun( age=21, name="
shakshi " )
4. Vari able length argument f uncti ons
When the number of arguments is unknown, a function can accept
multiple arguments using*args( for non- keyword arguments) or
**kwargs( for keyword arguments) .
Example:
# functi on defi nati
on def fun( *args) :
for arg in args:
pri nt( arg)
# functi on calli ng
fun( " Python" , "
Java" , " C++" )
6.
5. Functi onswi th Return value
A function can return a value using the return statement. This allows
the function to send back a result for further computation.
6. Lambda f uncti ons
Alambda function is an anonymous ( nameless) function that is defined
in a single line using the lambda keyword. I t is used for short, simple
operations where defining a full function is unnecessary.
Example:
res = lambda x: x * x
print( res( 4) )
7.
Com
mand Li neArgument s
Pyt hon Command line argument s are input paramet ers passed to t he script when
execut ing t hem.
Almost all programming language provide support f or command line argument s. Then we
also have command line opt ions to set some specif ic opt ions f or t he program.
Pyt hon Command Line Arguments
There are many opt ions to read pyt hon command line argument s. The t hree most
common ones are:
1. Pyt hon sys.argv
Pyt hon get opt
module
2.
3. Pyt hon argparse
module
Python sys module
Pyt hon sys module st ores t he command line argument s int o a list , we can
access it using sys.argv. This is very usef ul and simple way to read command line
argument s as St ring.
import sys
print ( type( sys.argv) )
print ( ' The command line argument s
are:' ) f or i in sys.argv:
print ( i)
Python getopt module
Pyt hon get opt module is very similar in working as t he C getopt( ) f unct ion f or
parsing command- line paramet ers. Pyt hon get opt module is usef ul in parsing
command line argument s where we want user to ent er some opt ions t oo.
8.
Python argparse module
Python argparse module is t he pref erred way to parse command line argument s. I t
provides a lot of opt ion such as posit ional argument s, def ault value f or argument s,
help message, specif ying dat a type of argument
EXAMPLE :
CREATE A FUNCTI ON TO ADD TO
NO:
def add_ numbers( num1, num2) :
ret urn num1 + num2
result = add_ numbers( 5,
7) print ( " Sum:" , result )
Python Packages
A package is a cont ainer t hat cont ains various f unct ions to perf orm specif ic t
asks. For
9.
example, t hemat h package includes t he sqrt ( ) f unct ion to perf orm t he square
root of a number.
A package in Pyt hon is a way of st ruct uring relat ed modules t oget her. I t
allows f or bet t er code organizat ion, reusabilit y, and maint ainabilit y. A package
is essent ially a
direct ory t hat cont ains a special file called _ _ init_ _ .py, which makes Pyt hon t
reat t he direct ory as a package.
Creating a Python Package
To creat e a Pyt hon package, f ollow t hese st eps:
St ep 1: Creat e a Package Direct ory
Creat e a direct ory f or your package, e.g.,
mypackage/. St ep 2: Add an _ _ init_ _ .py File
I nside mypackage/, creat e an empt y file named _ _ init_ _ .py. This file can be empt
y or cont ain init ializat ion code.
St ep 3: Creat e Modules I nside t he Package
Add Pyt hon files ( modules) inside t he package. For example:
mypackage/
_ _ init _ _ .py
mat h_ operat
ions.py st ring_
operat ions.py
st ep 4: Writ e Funct ions I nside
Modules Example: math_ operations.py
def add( a, b) :
return a + b
def subtract( a, b)
:
return a
– b
Example:
string_
operations.py
def t o_ uppercase( t
ext ) : ret urn t
ext .upper( ) def t o_
lowercase( t ext ) :
ret urn t ext .lower( )
10.
St ep 5:Use t he Package in Your
Script
from mypackage.math_ operations import add, subtract
from mypackage.string_ operations import to_
uppercase print( add( 5, 3) )
print( to_ uppercase( " hello" ))
STANDARD PACKAGES
Pyt hon’ s built - in math module provides f unct ions f or mat hemat ical
operat ions. Example: Using math f or calculations
1.
i mport math
pri nt( math.sqrt( 25) )
# Square root 5.0
pri nt( math.factori al( 5)
) # Factori al
120
pri nt( math.pi )# Value of Pi
3.141592653589793
pri nt( math.si n( math.radi
ans( 30) ) ) 30 degrees
0.5
# Si ne
of
2.
numpy Module ( Numerical
Computations)
NumPy is used f or working wit h arrays, mat rices, and numerical operat
ions.
import numpy as np
arr = np.array( [ 1, 2, 3, 4, 5] )
print( arr * 2) # Multiply each element by 2 [ 2 4 6 8 10]
matrix = np.array( [ [ 1, 2] , [ 3, 4] ] )
print( np.linalg.inv( matrix) ) # I nverse of a matrix
3. scipy Module ( Scient ific Comput at
ions)
11.
SciPy builds onNumPy and provides scient ific comput at ion f unct ions
like int egrat ion, int erpolat ion, and opt imizat ion.
Finding Fact orial and I nt egrat ion
from scipy.special import
factorial from scipy.integrate
import quad
# Factorial of a number
print( factorial( 5) ) #
Output: 120
# I ntegration of f unction f( x) = x^2 from 0 to
2 def f( x):
return x**2
result, _ = quad( f , 0, 2)
print( " I ntegral result:" , result) # Output:
2.6666...
4.
matplotlib Module ( Data Visualization)
Matplotlib is used f or plot t ing graphs and visualizing
dat a.
Plot t ing a Graph
import mat plot lib.pyplot as
plt import numpy as np
x = np.linspace( 0, 10, 100) # 100 point s from 0 to
10 y = np.sin( x) # Sine f unct ion
plt .plot ( x, y, label=" Sine
Wave" ) plt .xlabel( " X- axis" )
plt .ylabel( " Y
- axis" )