The document provides an overview of functions, modules, and packages in Python, detailing how to define and call functions, manage arguments, and understand variable scope. It also covers the use of lambda functions, importing modules, and creating user-defined packages. Additionally, it mentions built-in modules and how to install external packages using pip.
The document provides an overview of functions, modules, and packages in Python, detailing how to define and call functions, manage arguments, and understand variable scope. It also covers the use of lambda functions, importing modules, and creating user-defined packages. Additionally, it mentions built-in modules and how to install external packages using pip.
Unt) II. - Functions, Modwes and Paciea
ihe 2 wie
In Python S . |
a Functions * Defining -Punctiong , Calling-function,
Sine nection uments g ment ,Scope of
Be Vato Lamb nection:
| 1 eee
pm Oefining functions: — =
. |AFaunction ta Python Is defined usiag tthe ‘def | Keyoood —
rfellowed: by the funcHton name and parentheses.
2:| you _can also specify parameters within «the porenihese
* Example 3—
def JreetCname) + ‘
oe pot CPU Hebe, es nS)
=
3,)-2. | Callin noton 3—
|. [7 cal] Function, Simply use it name —eliowed Ly
parentheses . a
2-| fF the—-function vequives aequments » you can pass
them inside the parentheses, i
» OXample red : a
| greet("'Mice'') tro/pt Hello» Alice a
81-3 chien uments $— E
41: |Fanction asquments iin python ave Input Values Hat
4 _|awe passed ~o a -funct(on'S parameters,
—__2:|furncHorn Can +one Various -types of arguments!
~___| 2 Position uments |
har
i ae
Positional eatin ook are. Pee and must be
Passed | io +the coder: Hey are oleclared.2 KeyOore argu mend S Sa a; Ee
ed inan
hese aarguments can be pa
2 cotrect
the numbes of axquments must 6 a
* Default arguments be SS
These Values gre provided hen & pease >
defined and become) optional when tHe Func
Is cated, 7 3 Re
2 Yoriable — length anquments :— ’ ot.
Using \#tasgs |-for non- keyoore GaqumentS and
Lae de Kuoarngs | -forw Keyword) anguments .
sPxamples —
dep add(a, b= 5)!
return a+b
prot Cadd(3)). stk ourpuh 1g
puiot CaddC3,2)) He output 5)
der Vatlable_avgs (#ranqs)!
return etim (args)
Hat CvaHable -a%gs (1,2) 3,4)).
2.
Por emery «— »
ro’ etakement }9 used -be el} g Funct!
and optionally Pass back a value. ‘
Return: statements Gn return data of any tye”
Including fntegers ) Floats strings | Jis+s | qictio-
wo
=ranies j aed even others -functHons.
he 4Ye = = Sg
: + Example s— i an
def square (x) ° ae
‘4 return x & a
esuHt = Square C4) SE resuttis [C.
3.1.5 SCope of Variables 2 —
1.[2n python | Variables ave the contalness -for storing
| dato values.
2.|Pytnon ig not!!! statically -+yped ’),
3. |A vaziable is oveated -the moment We -fivst assiqn
a value -to t+. :
4. | There ave +00 types of Vauables”
cal Matables—
Leca| Varlables ace +hose that ave tnitialixed elthio
afPuncHoo and are unique +e that funcHon, TE+ an-
-not be accessed outside of -+he:-funcHon.
« Cxample i=
ef FO): :
ak \peal VaHeable
Sea fame Git
pot CS) )
tt ofp) Lam Girl.
£0
—_| D Global Varrable s= 5 = 3
Global Yartables ave the ones that are define
declared outside any Function and-qre: Net agecified
~to_any -functoo. ria can be used et any pa
the program. éees ¢ Pxample io, |
PER 8c Qh lambda '
Lambda Functions :— ees
Laredo —funcHonsl aaelqhoagnisuehimations
Lao Tunctices ane ‘andnymous functions
“functions wlinout ainame ) defined using +
‘Yambda ! keyocd .
"Thea! cao) taney ene eae OF arguments:
Can only have one expression ,
ie
Hint Cadd (25a) aed a. ———[ + rample=
—— Tt my—medule -p
— Idef helloW:
on puotC''Hello From my medulet"')
TmpostHng a Module ,— a
j[You can Impost a module using the 'impoat ? a
=mert-
«Oxample:
impos my-module
my—module +helloC) =H Hello fom my module!
9.|Jou cag also Iinpet= Speclt ic fu cotionacomaclosses
uetag throm? atarement.
+ Pxample t _
from my. module jmpost hello
hello) tr cutpur + Helo from: my mode!
9.2.3 |Usin uilt-1a_medules -
1: | futon comes witha standasd \ibouny of bullt- io
Modules that you arn use wihout Needing oto insted]
anything.
2:| gome commonly used bullt-in modules inalude tmath!
Idatetime!, (08 ! and teys/, :
* Os —> Titeract withthe opereting System.
+ Sys —> System — specific eoameters anol-funct =.
One '
2 mach —> Nici tino ;
pletidine age soe and -fime operations: -
ert.ih module
|e vafng the mea
Lmpoah mats
[plot (math. 8
Lpulot Cmeath. pi)
tUsing the datetme mod
Hom datetime Impoot datetinze
now = datetime.nowl)
PHnt Crew) He output
na weat dateianal time
3.2.4]
me: ace § — ? ——_
[A Namespace |3 4 conbainenHrat holds 4 Set of
Jdentifiers Cnames) and thelr Conresponding object:
Pythen has Sever) namespaces 4 Including) _
* Buil+— in Nomespace:— contains bulH —io
=funcHons ond excepHens.
* Globa} Name spaces s— Contains names defined
at the +op level oF a module ow ScH!pti
» loca) Namespace $= Contalns ‘names defincol 3
Lolthin q-function. E.
~
i
« Enclosing !— Names inthe lace) acape of endlastng
—functtons.
—~ | * Global ‘— Names assigned at-he-top level of a
eS
Module.
*Bullt-{n $— Names pteassigned in the built = lo
Namespace .
example sa
=H Globe) Vad'able
L=lo
deF outer_-functioo C)' 4
te Enclosing Variable 4
Yy=20
def Innew-functionl)!
athlocal Voulable = ~
X= 30 4
pAorCi\annen function! "1 Y, 2) ]
Inner_-Function¢ ) i
paint Clouter-function | '! , X54) i
outer—fPuncH on ¢) s w
PHotC Globe) scope :", x) 4
on Packa 4 Create user defin Import
a usinI
——}——
sa
3.31 [Create Uses defined Package i— en
SREB Leics = or eee eae gerined package Jou Noes ty \
orga
[a 4 x
_| | A package I lea 4 “bay 2 a
lato a single < directors ee au code Jn q
| a. [paar Packege _aljou ou 6 Ss.
nd Ae),
2 manage 2 TeUge
jay “hak of ee
tfollo @ these Sep err = '
f oh
Ty Gabe @ Dlrectony -— Thiaieslll’ Dextre Pacrage
directory,
py) Flet= this File C90 be emp, |
orcen Comtale Inthalixat
Code -for-the package
a. Add an!_ init
3. Add Modules ¢—Geate Pythoo-filesCmodules) a
Inside the Package directooy
+ Example + — :
my package /
—— init__.py ald al
moduwiet py =
medulea. py
« Contents of 'modulel py! :
=tEmypackage module. py
deF greet(Cname) }
beturn fF" Hello) Iname % From MediteL |”-
am
>
* content of ‘module2 .py)!
Se Be muypackage /modtlea py
ST det FarewetCname’’
+ Example :
return f' Goodbye , Fname 4% from module 2)"
# Content of — nit— Py!
It my Package /_ init. p
Ht Thi's-file Can be empty oF con Include package =leve}
VaHables ov imports
B32 jing a Package
You can impost your user-defined package and ii+-s
modules in another Python Sorip+.
Create a File named ‘main.py '-to use the Imypackage!
He mal. py ae a
[ee TmpoH ng -Hhe entire Package
Import Mypacka ge .Module+
Import _mppackage «module 2. ‘ ,
ee mypackage .medule 2 \mpott favewel) ,
pHat mypackoge :modulet. greet ('' Mice")) ]
sthoutput Helle, Alice from modale +!
| print ( Mypackage «module 2 farrei 1 C'\Bob")) * |
aPoudput ; Goodbye , Bob From module 2!
from my package. Mmodwet. lerpoe greet ,
nt (greet ("chastie")) FE Hello, Chastie from modwet!, |
(Facey ('! Dlana W) 4 Goodbye | Diana from module 2!Usla on Puil+- in Packs es
| File and Dive: ° oo :
aii LS temprile ee J
2: | MathematHes anol Numbers ia o> YY
+ Limatanoes : —~
7 L9 emath J —_- . ~
I > Fandom —
L-4 dectmod : _|
L_»-fractions : i : 4
Ly StaHstes
3.|,08 $=
Used -for InteracHng With the Opematiog, =
such ag file and Airectory opewsctions:
_h.| ys 5— cw
Provides access a dem = specie Porameters
and funcHens |
& maths —
provides aro aed fa daha aad Ree acl -
“Stans[datetime + — ene —
[Uaed for Maniewating datesand times
Grenexates mand obo cumbers) Ree
Rejeon s=
an Used-for parsing aod cemeruitdéa J30n dato,
} : a
ACS
— =
a Provides suppert -fow requiay exprosstons,
Je. | collections + —
ae Peovides specializes! Container date types:
_ (ee setae pacha. for PPP .—
1 | We can insteul additonal packages by using the
thon pip tastall command.
2:|lets Suppose we vwoant -to {nstall the Numpy using
pee:
3-| We can do frusing the below command.
*Syntac t—
: pip fostall_oumpy
se f sia on Banke
1) rthar i's a 2
2) Sac =
[Define Moduledn = aed mperetng ‘4
| ereste el tree
scopim. : J
3
4
S)| Witte note oo Name aoe an
e
@
6) [create o user defined P2hOH aiid in oo
a nas bald io package: andl ball’ s
using eae
deserbe jostailing package