0% found this document useful (0 votes)
4 views16 pages

Python Notes

The document provides an overview of Python programming, including its creation, features, and the use of various data types such as variables, lists, tuples, and sets. It explains key concepts like indentation, comments, and the importance of integrated development environments (IDEs). Additionally, it covers basic operations, input/output functions, and the differences between mutable and immutable data types.

Uploaded by

omm783901
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views16 pages

Python Notes

The document provides an overview of Python programming, including its creation, features, and the use of various data types such as variables, lists, tuples, and sets. It explains key concepts like indentation, comments, and the importance of integrated development environments (IDEs). Additionally, it covers basic operations, input/output functions, and the differences between mutable and immutable data types.

Uploaded by

omm783901
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

<br>

classmate
Date
Page

Python i 33L
It wasCaeated by CeLticlo van. Rossum in

swcb deuelopnunt(senvea:side)
• malkemahcs,systm soiping
sstaue developrand..

Alhy Pythso
- works on diffevre n platfoms (windous. mac linux Raspberny Pi
Simple , allows deueloper to clevetop in compaet lines code

-Kuos on an. intorpreer system. Code can be executed


ASA IE is wniten. Pootouping can be veny geice
Rython can be taeated in pótocedural way, an
obect -ciented way ar a un chional wuay

Inteqoated Developeut Envion mnt (IDE's)


-
- Thonny Rychaam Netbe ans -Eclipse

Hello-py peint ("Hello_, wodd)


:' C:\Users\ Srus hi eythoo Hello-py Hello, wotd|
Run onlCommand line
python --VerS)On
exit()
<br>

clsswte
Date
Page

Indentation Spaces at the


Indicate a
begining oo
a code Iine
blockk of code

2
if 5 i.
point ^5 is qratex th
than 2)
else :
pmnt (Ealse
<br>

e
art used to stoe data that can be meferrenced ,

manipulafed
Vnd pDgra ecttion. A Variable is essentiall g lessmt
assiqned to a value.
name Hat
is Date
Page
Variables r (meated then u, assign a yalue toi
can only contain, lett ers digts-(underscores)
dan not stert wilhn
digits
Case SensifiVe
"Srushti

Comments #-single line text


text
multili nnt
pontfpython is fun" Python is tun
pointl Keally")
Really
paint 'pythan i un")i point ("Really

print () unchonused ta clisplau autputvalues


predened iepython
-Rese
- uwith neanings
Keuaads
impat kesod key words ase
point ("The list
paint ([Link]).

The list o keyunads


, aod as aSsert aSync await ,bmeak
FalseNone Tne except, finally fex
del elif else,
class, contiouedef lambda nonlocal
foom
is,
qlobal, if,impat,ge in tay whilewi qield
tuxn.
<br>

Date,
Pone
Vaiables in Rylhao
Basic assiqeut Dynanie yping moliple assiqnmnt

x='Now a soinq pomint(a bc)

Gceinghe
vcriable
ype
S= lo"
(o)
paint(type <class iot
(type(cnt))
paint (class 'int
f= Eloat(cnt) point(tpe (f)Kclass Aloat'
age= 2s piat(ty pe(s)<class 'st')
S2E str(age) point( ty
peH)(lass 'la}
d=f 'key':'yakae poin(kypea)) <class 'dic
ds
bool ue piat(typelbol) Kclass "bo

ÔbijecH Refererce in Rython Suwappinq two varables


a
ea;b= b,
oe-
5
paint (ab) {0 6
Couning characteni in a sàig
nou) S Conmpukea"
lenqth f len(s)
now ntlength)
y=25
(zarbage
254
delx +removed foom namespaee
-
n5 ouput= 15 Explainauion =
I 2+5+ 4 +S =
I5
se
inieqer ofiod the sUm the fiost 'o'natunal
Given|3 inpufs that anestored in
te voaiables
he ed q a a
àbc seperae
10

point times and b b tinncs


tima in single line

44444 ss55
<br>

classmate
Date
Page

|Phining vsing Escope chanoctes Baint ( Pylhonn hoqoormingln Bosis )


prcint( Name t Coiiose )
Aqe H

Display Python keywosds impost keywod


pint (keyuwoxd kwlist).
Checking Total keyaords impost keyurd
print("Total keywovd:"len([Link])).

-Linecomment
Single This_ is comment
Mui- Line Comment This is
python
porogommning

sor
Asiqning Same value to moltiple vaiables.
point (a, b,c)
Mulliple Assignsant

Data ypes
in python.
C= Python
(a)
point(4pe

d =Toue

Using sepaator pint(Rython", "Javo" "tt, sep",

Paaameler paint"Hello", end =" ")


Using Eod
pain¥("Aordd")
NAme"Ravi
inhing fornatted marks= 85
name,"Masksi", maaks)
pint(Name

input fronm Users nê


name
==
inpu"Enter Youg Name:")
<br>

Dole,
Poce

Tnteqern Toput age =


intinpu"
FloatIoput
-float(input ("Enter Price
:
youa
Shring Tnpotcih =inputEnlex cityn
az intinput("Eatex na.
Two inpts sepamatel
1
"))
painl (´Sm at b)
Muliple ÀGt inputs abe
=
input("Entex two po")splk+C

olile integer inputs abmap (int, inpuh ("Enter two no; ") Spll(
point( Addiian :", atb)
Anea incle r=float input("Entea madius :)

Simple terntstp. mapEloal, inpu!("Enter PRT)Spl


=
SI (pKT*t)/10o
pint ("SimpléThteresk ST
= g
Swappigg 2
[Link] bi,
print(A}lex suappinq :"ab)
<br>

classMate
Date

List index
3
-3 -| <index Paqe.

myhst="apple","anana","che rny
Osec to stose onuliple ems in Sngle Naicbles
items
ms
ae oadasd, changcable 4 allow duplicale valks
ite index stats
Order uill not be change
We
ceunadd, emove anm ist bak order hako
be sane
paint (len (mylist ))
=
abc B4, Tue 40, "male"
type
point ( (H) Kclasss'
Iist ) Constouctos l= list((A 'B, 2)) doable (()
Access ist items paiat(r) B
ncluce tintlade point (I-1)
vong e, items -> paint (Ai:3|) 4, Toue
point (A[:2]) A'"B,
pint A1) 2
apple " in mylist :
pint("Yes 'apple is in the list)

Chapqe Ttem Value


"G0
70
liclear
Jil2:4 =False,
Ai
insert(2, "watermelos'
Jappend"oaNgp
ex tend(Ai)
i-memove (" mele")
Aipop)Aipop()
del tilo]
del i
<br>

dste
Date.
Poge

point (a)

nnge ( (ten (ai):


<br>

-3 -2
Tuple index 2
=
mytuple (apple"," bo nan0","chery")
- Qmdered immutable not abte to add/remove
4 we
unchanqeable items onCe tuple is creal ecl
-
Duplicae Allow

paint (len(mtuple))
tu= ("opple" <- tuple with t elemen pclass 'tuple')
ti-("apple"X shing typeclass. 'str
+ = ab, 34, Tue, 40 male")
constmuctocr =
tuple ( tuple tuple(("apple" "banang", "chermy")

Access Tuple Ttems print(my huplelil) banana


pini(m tuple (-1) cberry
print (t]2 : 4J) True; 40
pint (t[:31) 'iabc,34, Tue
paint (1[2:)
pin (th :-)
iF "apple" :
nytuple
poón! ("Yes,'apple ' is in tuple ")
<br>

Upelate tuple values (unchcuyorble ) "Kiwi".


peint (Y) = l'a, (O
y= istx)
yli ="kiwi"
a= tupley)
('a", " Kiwi", "
paint (a)
Add items a=(to ,20 ,90)
y= list («)
yappenDd"abc")
* =
tuple (y)

2 t =("A", "B", "c")


y("z")
tt=
paiat() 'A, "A","
" "
"z).

remove iterm
yist(t)
4remove")
tupleyY
poin! () "A","c',"z")
ale curenot able to upelate/add/vemoveifes om teple beCause its
Immuable" '. we USe
list to do these ninqs

deltuple
det myhuple
No. oh vcriables _must math the na
Unpack tuple t =("A "B,"c "
Values in tuple, jf not mus vse *

(qoeen, yellow, ed ) =t t collect nremaining values as lst


print(geen), poin(yellow)i poit (recl) >"A"8:3
Fruits"apple""baneana chenystsawberrytrasberny
(gne d yellow, * red)= foruits
Hgmeen) : pojnt( yellew) ; Prin (oed)
apple bancna L'themy","Storauwbery':*Nasbem
<br>

Loop tuples dassmate


:
mytuple
point (a) print(a)
Ofer i in ange(len (myhuple):
print (mutupleL:1)
)i-0
while i< lenlmytuple 1),):
point (myhple
=itl
Join tuples
(Ut
O t1 =("a,b','c) t3tI4 2
= >
2
(, 2, 23) point (t3) ('a''b','c2,3)
t t2 2
pin (t) (1, 2,3,1, 2, 3)

Tuple Me thods
count ) -Rctuans the no. timeS a specikiel valae occns in tuzle
fx aa specikied vclut 4 ehao position.
index()- Searsthes tho tuple fcr
<br>

clssmate
Set myset =
Date
Page

apple"," banana,"Cherry"

Unordesed,unchbangeable* 44
unindexed
*Note: Sel items ae unchanqeable bl yoL Can emove items 4

addnew items. :

not allouw cduplicate values


norederred - no index/key>Every imne ue will get new
indexkeyE
Duplicate Not alo wed

S =
apple""banana","Chery"apple" >
bananachesgy apple.
Iaue =1 3False ) =

Si ,
abcToue, False 1,2f
point (S1) e, False, 2,'b',a','c
Tue, 2

print(len (s1))
pint(type(st))
on
S= setCa'b'c'
|Access
tems fos in mset : prin"banang" lin muset
point (a) paint("bangnd" not in myset)

Change itemS - Once a set is created, you cannot chanqe its ikems
but
(2)
Add
set tems myset .add(Ononge")

Update C) 0
O
si update (s2)
set2 -["kiwi", "anqt"]
myset updae (set2)
<br>

classute
Dcte
Pace

Coemove myset remove(" banana")


>
i tem to oemove does not exist, gemove(0 will gaise_an e

discard() myset discavd("bonana")


Ly iR
lem to nemove coes not exist, discand () uoill Not Caice

pop ) mysetpop ()
L randoml pops
pops the item e
tusoi to a'Voiable
Clear () - mylist
[Link] an ()
Ls emptis the set

del del mylist

Join sets
updale
Intersechion) keeps Onlg duplicales.
3) Difference ) - keeps unique yalues only. nom 1 Jis!
9 Symmetic-difference () keeps allL items ExCÉPT the cduplicate
S= [Link](s2) S1
Se S

S= Slunjon (S2, S3,S4) S =


SI
| s2 S3s4
S =SI. intensechon (s2) S=S1 s2
S=S). difference (s2) S= St- S

S= [Link]-difference (s2) S=SI^S2


<br>

classmnte
Date
Page
Set Plethods
add ()
clecr_
copy
diEEerence)
differrence upcdae )
discard
intessechon ()
interssechan update )
isdisioint)
issubset()
pap
)
Symmetoicdiffenence C)
Union)
dpolate )
<br>

classmate
Date

Dictionaies/ Dictionary Page

myDict =
Brand:FordMode|":"Mustong'," Year" : 1964

Key i value
-ordeec"changeable 4 do not allow duplicale.

poiot(len(mybie))_

items cCan be
d. daa hype'
=
mDict "Boand ":"foxd"
"colos":red""whike""blue"
prin type (CmyDic))

Dict O
Coostuclos
dict name =Jobo
=
d aqe =
36,countmy "Nouay)
AcesSens
tems X =
myDict"model"
muDict qe{"Mode)")

myDict. keys()
Z =
[Link](
W =
myDict. items()
Chane
Walues
myDict"Year"] - 2001
mDick updae(] "Model":"Dusken")
Adcin
terns
Remaue
[Link](Model") myDictclean C)

[Link]()
del d[ hame1

del myDict
<br>

cdaccmute
Dete
Pope

Point fers [Link]:


&

in myDict
ey peint (a) point(a)
Poùnt
Value fos myDict [Link]():
point (myDict [o]) point (a
prntvalue!
key:
peint (a, y)
Copy
Dictiondisy [Link])
d =
dict (myDict)

nested Dichonasy
print( myfam I'chilà 2J[name])1
childi= hame:A, Year: 20dy
Child 2 "hame B"Yeas": 200}
child3 =R"nam: "C,"Year":20113
myfom ="child 1"; childi,
hild 2"chilJ2.
"Child3"i chilel 33

You might also like