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

PAGENo.

thon lutoyia DATE

* Pthon
ihoo 1s a qeneral-
tAnfta purpOseioterpreted;interattive-
Obiect: ortented _bigh: level
Language t Laas _cLea ted by pr0gramming-
Aurinq 85-1990ike Guido Vdn Rossum
also avallable per python sotice
Under the GNU Geneya code s
(GPL) Thls tutorlat give genexaLPublic
Public \ceose
ltceose
s enougn unde
Pribon pidqramminq langua.ge- xtandng D-
l hy to learn python
ython PHbon is desiqned to be hiqbly readable
R uses_enqlish
ketpta.ords reqentty u0here as Other
Languages use punctuation it bas keeoer
Syntatcad con.stuctions han Otber tqnquagce

pytbooIs musi or Students ooYkinq projeasiondls


o become a Qieat Solttoae êqieer especially
Ohenthe p are toQrein q to uneb developmen
clomaln'I
1Lollltist do can Some otbe
the kep
key
advantaqes [earninqpython:

thon is interpreheclpython is processed aiontime


bythe nterpreter Yao_do not need to compile yaur
pLoQra lseore erecuting it this s Similay to Perl
n dpHp

Python is ioteratHve ou Can CLctuclly sit at a Python.


rompt 2 iteractLaith the inteapeter direcHy to
LOife uoy pr0qrami
DATE

Python Is obiectOrieotecd python suppovts abie s


oien ted style techniqwe progiamminq that
encapsulates code withinobsdcts.

python ls a beqiantrs lanquaqe-Pyth0n Is agrett


tnquaqe oy the beoloney erel p10q1ammers &
Supporf the deretopment d olde fange
applicationsrom simple tX pioesio td w
baotoseK o omes

characteristics Python
ol are imp: dhar. oPyhon progoJ
I spp orfstanctionat k Structued Pioqa mminq_
N,
methads as oetl as o0P

Tcanbe used ala SctipioGanquaq4 orcan be -


Compile d to byte-codde or boildioq arqe
applica do
Taxq
It piavicles very plgh level dynamlc data types.
SopOrts dynamic type Checkido:

TfsuppOYts automatic qarbage ollectton.

It can be easily iateqkated with ctt,com


Activeys VTAVA
PAGE No.
DATE

than isnteratre-
yotta-Aduallycit ata
etlo LOOle usin pyBbon
JuM to qive yoo little excitement
aboUt_pyth0
Tm 4oinq o qive y0v a small con ve
tletto Lorld paraqramyod an try ntieno pytho0
hok it _Uslnq dlemg

Priot hettoOPythorn")

pplications Pyihao PuCPython Features)


AS mentaded beknre Python is one
the most
LAldely Dsed lanquageover the web. Tm
qoing to-
listeta h e here.
caay to- teain Pythen has teco
key tooids Simple
Stxuchur a cteaurly detiaed Syntax. this
Student to pick op'the allocas fhe
(anquagi quickly
easy-to - 1e d- Python code Is mo
move ctealy
deined,eakt vlsible to -the yes

easya maíntain- Pythoo s0uIce_COde isa


o maiota n easy

A A board standaud libiaypythoni baebolK


ibiary is yery potable and athe
Cross-Platfo rm_
tepcompahble D UNIX, oindo cos 9 macnitosh.
PAGENo.
DATE

Toteractve mode ython has Suppoit farestion


a
ter acttve mede uhich attoos interactive esins
debugging sopeti e_cods
portable python tan Yun on a ide v9tiet.
Oicde vaiey
haxoareplatoms X_hashe came lotatare
Jotatace on
on
platkoms
xtendable -Voucanadd loa leel modules ta th.
PythoD oterpretey These madules enable
PLoqrammê rs_to add or cuSomise thejy_taals to b
Moe eticent
Database Pyth:on prOv ldes lAter
ceafo al
Mas or Co mmeilal_databae

GuL progiamminq Pythan supporfs


dul applieatH
hat con be reatedax_
parkedtamany ystto
Catled libraiesand taindoiose
Such
scch Sistmi
as coinda0s MECMaciatosh kthe
laladc
Susftm of unix

Scalable Pythoo PIOvides abetter stwche ahu


SupporttoY Lauqe Ynqrams than shell Sipti
Audience his_pythoo tutorial s desiaoedor
Sotuae proqrammeYs_Loho need to lear PyTho
proqramming lanquaqe fhan suateh

eequisites ou Shautd have basic understanding


Comp.üte proqkammtnq fermioaloqlef basic
Understandinq any the poqramming
J
language.
i saplus
PAGE No.

DATE

Standard data tpes-


The data stored la memnry Canbe ot manyt.
or eq aposoni age is stove4asanumeidc valy pe
hiyher dddesls toed as alphanumene charcte.
ers:
Python has standard data types
numbers Python has yanous Standasddt
Stnng ypes hat ave used fo octine th
is peraong _possibte On them and
at ctonar the sto raqe me t-ho d a r eaL6 the
Tuple
yhon_AumberS'
Numbe data types Store numenc
numbe a Objeck proicet Cn values
assiqn Value to the m ted Mhen yo0eteatyt
vare
va tO
atgo
you Can,detec dssinq le ag
Usiogthe delete tatemeot mu Hiple obue c ts -5y
r e
t d vaY
cevar-a:¥AYS var- b
PAGE No.
DATE

PythonSupports 4 dieent numericol types


i a t (siqned inteqers)
LOnq Tong tn kges Can also be epres ened octa *
heade dmal)
o a (oaHng potnt e a valve)
Complex Cno-s)

ex flere ave some exampbi numbes


N
lonq foat Compleex
5 24 & o 0
3-14
t o 0 ox{q323L tS 2
22 21 3236j

Python lto cOS yo0 to vse Q locoe rcade Loitth ke bust


TeCommnded
uPpeTCose
+s çaameted
avola
that you uSe only n Lale Lto
to calcd contkusion colth he ntimber l ythe
displays lonq lnteqes
J
LOith an uepertaici

pyhonstinqsi-
Stinqs io bython an ldeotitiedqOataNonontiouous set
charakers pres ente d in the qhetlea-aele.mork
Python altotós or ether palys Sngle oy doube qpoeg
Subses K Stdoqk Can oe taken bsina the slice
Operator[i and ti1) talth tndere S.tartioq dto inthe
beginning 4the trag_dnd 0okinq their caay
O M : a t th e end:
PAGENo.
DATE

The
The plus ) Slq s he stmng Concatent tiao
pe scLtor t h e asterisk ( ) ls h e repebton
Openatodr

ve /usY/bin/python
Str =teto Wovld

Print Stx prints complek sin4


Patot sh (o] pro
istchara t ker the sbing4
pintstr[2:5] prints charatkx staitngom idh
puintstr [2:] Prints stnq startin mård chara
pintsir 2 prat Stioq too tima
piot Str Test piok
Concaenatecl sbnnq
This ol psoduce fhe oll
ye ot:
Hetlo lorld!

Hetlo orld He tto talalel


Hello Woild TEST
PAGE No.
DATE

Pytho n Lists
Lists ave the mast versatite
data types A tist contaias o Pythoni compound
CommaS and enctosed_ items Separakd by
coithin 94pave brackek (
some_extent, Ifsts ae hmilar to ausay_in t:
Aeence betoean them is that atl the one
lng to a tist ems bt
long=
can be diftexent daa typ
Ihevdlues Ctored in a lisE
the slice Operator (CJ and ean
C:1)
be arcei scd usíq
dt 0 in the beqinnía o the lis olth iodexea StartiBa
to end 2Looktnq
the plutSiqn t's the tdot con their coay
OpetatoL, & the asteris k (t) 's he atenatiao
OpOrator
epeti don

/uSY/ bin/pythoo
11st
t abcd.", 786, 2:23, "John,
7o 2
toylist [123jo hn'J

plnt list Pints co mplete_list


pilot list fo) Priats
rlot ltt t8 prst element 4 the lisE
print list27
#priatS etements gtartioq trom 2n =
priak elemants Stcttnqom rdeleinen
plnt tinylls 2 Prot tist two times
palot list t nyl/s tprints con cotedakd (kts:
PAGE No.
DATE

This produce he otlocoing eUlt i


abcd, as 6, 2:23, iohn' To 2)
abcd
(7,22 3)
C2-23johoo 2)
Ca bed 786 223, John', to2(23 nbn'

ython Tuplés
A tuple ls_anoth er
scquen.ce daka type thatts
Slmilar fothe tist A tuple consist[
Vaus separated hy comas -d number
tuples ae enct0red totthin UAtte ictsbooee
pdranthere
The maio dktevene
ists eve encloce d in betoeen tsts tuples ani
Size can be brackets(CI) &ther element
changed, Lohitetuples ave entloso do
paventheses ) Cnd Cannot be entlosod (0
Can be houqht d as vpdated. Tuples-
epdated. TupleS
e'ad-onty tists
r osrbin/pythog
upte abed',
ny tuple Ct23 7s hn' c, 22.3 oh
o2)_
3, 'So )
PAGE N

DATE

pilnt tuple Pria ts the compleke tupl


printuplelo) Puiats Hist ee mentq t h e tuple
point tuple [!:3] Ë prias element te tuple startng tmm
* 3

ptiot tup le (2 2 ic tlementh thefzpletanibom elman


pm Hay tuple 2 P t conkns tple troice
Prit tuple tiny huple p i t concakred tuple
This produe the totlocoing esu it

tbe d s6,223 Sohn ' o:2)


abcd
(s62 23)
( 23
'Sohn ' 2 3 'Jo hr')
'abcd', 386 2.23 Sohn', o:2, 123, 'john)

the hotocoing code ith tuple, be cctuse COe


s hvaid o

tempteel t o tpdote atuple tdhich ?s notalbel


Sinilac Iseae
posstble o Ist

/Usybinl2ython
tupleC'abcd' 223 2.23 o 2)
tis abed, t6, 2 3 'john ', to 2'
tuple (2)- (oo0 Tnvauid suntax
list [2) =tooo # Yalid syntax with tple
tiSt
PAGE No.
DATE

Tyhon Dictlonciy

Python dictionares_ae kind 4 hach ta ble 4un


pe
they ooYe tike associat ve arrayr or ashe
in Perl he our
be
(onsls t e keyVdluu pCy Ys iA di cho
key can, almost dny Pyhon
numbes
tepe,boE ave Uual
er stmnqs Vallues, 0 tbe cther hand
h@ nd
Othe
cun
beany arbihoryPython obie ck

picionoresare enclosed by Cudy


and valuu can bra ces ({ })
be asslqned ard
Sae bracs CCJ)- Qresed Uslog
ere /us1/bin/pyihon_
dict
dict 0ne'] 'This
isone
dict2] Thts s tuo o
taydict lname joho' code' 6134,
Sales dept
Pint dict one']
pilnt cdiet D) Pink vdie o 'one
piint tinydict priot Vduw ar key-
2 ky
pint toydtct keys Pints comple t diciansury
Piint C pinb all
nydicB values C)= the keys
iats al the vdl
PAGE No.
DATE

his pooluce the o ttowfng reg utt

This is one
Thls is too
dept sales tode' 6734,naoe:ohoL
dept 'code' 'nam
sates G34John

Dictonanes hae no concept d arder amanq ele mek.


s inarec to saspthat the elemens an l Ouks
orde hey ahe simply unordeve d_

python ldentikiers

A Python ldeniier ts a name uSedl ta _idenHy a


vandble uncon classmodule or otht obicet_
An identlfier_stcvts_olth a letter A to 2 oyà to z oran
Onderscore l ) kolocoed by zero or more tetterr,undey-_
Scoves diolts co to
Python does not glotD punchoion charatkK suchas
, i f wtthlo ldenHiarsPyton s a care
sensitie_ Proqrammih9 anquag. fhes, NanercueR &
Mnpoce ae too ditewintlng- ldentiters in Pyom-
PAGE No.

DATE

ConvenionsfpLpython
Heve av namin9
tdenbkies
ctass name Uppercaieltfer.
stats olthg a0
Al othe identifies start d'h a lowercage ltHe

Startingan identHtley oith a Slngla leadioa


undersdde ladicates that the tdenteris pdvae.

Shartinqanicenthitler wlth tuoo leoding


Underscoves incdicate_a (tmnaly phvatë
llentitier
the denbfler dto ends oith too
Un derscove he ldenHfier traultng
ts a langage
deoed sperld namt

Ioteyadtive mode proqmamminq:


Tnvekin the
ioterpseter Laithoutt pa
le asaparamt ter passinq
ssinqAsip
a saipr
binqs p theo
Python
llainqpia
PHhon 2:u:3 ( Nov It 20lo, 133443)
GcC 41 2
20080to4 Recdtat
Ypbelp, topyrightcredittp.1.2-48 ) linu xz n

intormction >> ice nse tar more


Type theotlooin q text at the python piompt pess
the Entc

>priot "He tto, Python

you are Yunninq neo version Python then you uo uld


Deed to use_erint Statement olth parenthesls
s_asio
print"Hetto Python" Hoeoever to pytho0 Version 2
his pr Oduces the totlo smgegutt

Hetto pytnor

Seript Mode_DrngYa mming..

Takin dhe ioterpreléxLaith a seript parameter beqins.


ExetcetHon the scdpt and Contioues untl thc sciAt is
Hnished. lhen he sciptis tHaished, the ioterpreier is
no lnngeractve

Let us urite a simple Python proqram io sciipt.


athontles bave_extersion PYype he tallotai
SovICe code io aest py type
puiot Hel0 pythoo 1
l e a s Ume that you hMVePython fnter preter s e t l n
PATH Varable Noo,tylo YUnihis proqram as ollows-

pythentestpy
PAGE No
DATE

Thls p1oducesThe totlooinq Yeao1t


Hello Pyth0n)
Let us try anothe r
tOay fa ekecLLIC
He re i s the
maditied testapyle A_Pdhon n

usY/ bin /pthoo


priot Hetlo Python
e assume hat you ba ve
availabe tnus|Bio dire Pytho n 10terpreter
POgram asto|lotos ctor y No ta q to
ron his
Chmod tx testpy h s is to malks
est P- le executable
This procluces the ollotoinq ye
ot-
He tloPytho n
* TDStalltog pytbOD
a uartety
Lotde
Pyhon dictibution ls availdble tor code
You_need fo_do.onload only the lblnory
pattotmS
appicableoyour plaikasm
&ostall pyhan

Code for yoUr Plattarm s not a vailabe


hebinary
Ov neEd a l Compller to compilethe source codE
manuaily lompiling the source Coole akkers More
tealbilty lo tcrms cholce teatures that you
Veqsle n your listallaton
00
Here ts a quick dverviees instatling Pytho0
Nadousplaitorms

Unix and lInux }nstallaton

Heye qs Fhe slmple Steps fo install_python on Unix


loUrMachia

Open a coeh braLOser_ancd qo to


https1LowLpython.01q ldoconloads

taloto the link tn dotonloa.d zipped_20w re available ade


available Unlal liaux

DoLonloac and ex tia t [es

Editoa the Modoles Setople it yod (antfo


ostomize Some ophons
un:/coOkigue SCApf

make

make iostaL_

Tbis_nstatls Python at Standard locaHen


Just/1ocaj/tb/python Xx twheve XX Ls the
Verslon Pythan.

alindotos lostallablon
Here axe the steps fo install Pyth o n dn hllod ous
machine

Open a Lgeb b10.coSesand qo to


httpsYLsMaW pythonorq/do.0nloads
ollocothe llnk ar the dlndows jnstaller
iython-XY2moi file whee XY2 Is the
youneed to ioshdt versioo
To use this iOsta
lley _py thon-
Windouos ste m mest SUpport Xznmsi, the
Save+he tnstaller tle to ylicrosat jostai 2:0

hen 1ualt to tload you_ localm


machioe a0d
SupporsMS out i you machloc
PAGE No
DATE

Ron the doconloaded Hle. this bings Up the_ pytho n-


Statl wl2ard_whicb isreally éasy fo vse Sust
actept the deauE settioqs ait uáH Hhe îngtatl-
Is stais hed_and yoU Are do nC

Settoq path at lolx/llnux

To @dd the Python cdirectDrty to thepathfor a


particlar gcsSton fntrtH

I nthe (sh Shel-type Sete0v PATH


SPATH:/USY/ loca bin/python' and ress enter

Inthebasb eelL Sheti (liour-type export


PATH: $PATH /sI/local/binLpython od pre os entt r

Note usr/ 1o col/hinLpython is the path the


python dire ctory

z I n the sb ar ksh shell- type PATH-$PATH 4/Usr


ca t/blo/pythan " ond press entr
Jntegrated DevelopmentEovivonmeot.
You Can un pyihon 1omaaqraphiaal_Use.
Tnterace (u) envlonmnt as 0 ell, tf yau
a aul appliation On yoUY
System that Sp
ython

Cnix IDLE 19 the very irst Unlx 1DE tr Du


lindowsPython lio is the St Windaos
inteate oY Pytho n Ond is an tDE oith g Ga.
Mactoosh he Macintosh Aersio a_
ulth he IDLE
IDE is available Python dhsg
ae bsite doconloaddble tmbemalt
as either Mdc oary or
BinHex'd les:
Iyouate not ableH0s et up
properly, then yOu Can take helpthe enviionment
admio Make sure he fro.om you 3ystem
piopely 3etup and coorki0q Python environmeot is-
pesiectly toe:
Note All fhe
cbp are exetstte dexamples qveo io subseqent-
avaitable toitb pyrhon 243 versien
on Cent0s ttavOY
e
alveady have Set up linux
enviitnme nt
Onliar, So
pytbdn prq 1ammn
a
Vailable that youCaD execute
examplea onlloe at fhe all
hen you ae same Hme-
tea1ning
odie erample_and theoryeelree
and eKetute_Fonlioe i
eretute iton liae-
PAGE No.
DATE

History yih0n
Pyibon was de vetoped byp Guido van Rossom fo ihe
late e tahties_andeaIlydine tHes at the Natonat
Reseach Institute tor Mathe maHts and camp:Sci
theNethertandg:

ython Bs derived rom many other. languaes-


lotluding ABC Madula 3, ,Ctt_ Alqol*68, SmcITalk
un x sheti Qather Scdptnq anguagS+

Pyhon is copyriqhted tike Perlpythoo SoUa.ce


Dublic
Code_snoco aValoble unde r t he GNU General
license (GPL) **

Python is_noAmaiatatoed by a core develapme nt_


Rossum
team at the o stitute althauqh Guldo Van
SH holds a vital 1ale lo dréctioq (ts praqiens
PAGE No.
DATE

Pytbon lists

The is is a mOSt VeYsalite _datatype avaldble


Nthon Lobith can be arithen as a ist Co omoa
separdhed valus titrms) bettaeen qde biacke
Important thinq about a s t is thdttems in
tst need not hA be he Same ype
Cyeatinq alis is Vas simple as Puting_
dIerent comma-Separ atedvdieS befoeeo
Sande bratketsImportant thing abouta ist s
itemstoa tist need oatbe Same
Geatioq a list isa slmple as puttioq
Comma se paraked yclues betseen' dikereat
biacke fr or ex SqAJA Ye

list physics hemistn 1


lts42 L2,3,4.s J; 2000
lisd32"a*b " e"'d

Sinilas to
stuaqncdicesfistindice
and tists can be sliced
concate
Stalt_at 0L
ndtcdand s0 On-
Wo.

PAGE No. |
DATE

Syntax
de uoctionname paYameters):
unctio O-docstrinq
Kunction-s0i te
returo fexpiessidn.
deault, paramettrs have a posiHonal behavinur
And you need to iako roohem lo the Same thc
they aere clektoed.

Example

lheOilocoinq tunctio0 idee take aCtnng as


2 ioputt Parametyand Prints_itton standlard
SCre en

lepriatme (str)
Ibis priats a pase clsinq_inn tinís koncha
pzlnt sty
eturo

You might also like