0 ratings0% found this document useful (0 votes) 77 views54 pagesPython For Data Science (Slideshare)
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
Python 4 a popular programming language. It was created by Guido van Aossum, and released an 1991.
nis used for
web developrent (enrver-side},
software development,
mathenatica,
syste scripting
What can Python do?
inte
Python can be uzed on a server to create web applications.
Fython can be used alongside software to create workflows.
Python can connact to database systens. It can also read and modify fil
Python can be used to handle big data and perform complex mathematics.
Python can be used for rapid prototyping, or fox product Lof-ready softwace developrent.
Wy Bytnont
Python works on different platforms (Windows, Mac, Linux, Raspberry Fi, etch.
Python has a simple syntae similar to the English language.
Python has ayntax that allows developers to write programa with fever Lines then sone other progran
ming languages.
Python runa on an interpreter syaten, meaning that code can be executed ae acon ax it ds written. 7
his means that prototyping can be very quick.
Python can be treated in a procedural way, an cbject=orlentated way or a functional way.
In 131:
DEInt ("Hello Word@: 17
Helle World
In LieLet's Check the Rules in Naming a Variable
‘+ Rule 1: AvVortatlo name must slat witha letter @ Underseare
‘+ Rule 2: A Vertable name cannot start with a number
‘+ Rule 3: A\Vartabie name can only contain alphanumeric characters and underscores
‘+ Rule 4: Variable names are Case Sensitive
print (Sting?
peint (stein
Creating Variables
‘+ Variables ore containass solely used for storing data values.
'* Python has no command for declaring a variable, le, there is no dectaration of variables.
‘+ Avariable is created the moment you fst assign a valve fo it
Let's Print the Variables
print ()
print (y)
peat (2)
Let's Check the Datatype of the Variables
print (type
print (type
a
Let's Assion Multinia Values to Multiola Variables at one timeIn (0)
Yr == 10, 186, ‘String!
peint (type (xh)
Drint (type ty)
print (type (z))
sclass tint!»
Let's Check how to Output the Variables
In 118)
¥ for Integer and Float we can use comma Fo output the variable:
y- 89
Brint ("The Value of x is", 32
BEint(*The Value of y int“. y
Tho Value of x ia: 1056.88
The Value of y is: 89
In (20)
@ for strings we can use both "+" end *,* to output the variables
vom "Seeing
print(*The value of «is: "+ 9)
Print ("The Value of x le 2", ™)
The Value of 4 fs + sting
The Value of x fe + String
Concatenation of Variables in Python
In (251
(let's Fizse eheck the 3b
> teytnon*
Arey
= *Love!
a= iyte
print (a)
b= xin tayet te
Print (b)
Pythonistove
Python is Love
In B1t
W how, let*s check the integer and float concatenation
x= 10
yous
a-Kty
printia) # heze,
ihe ‘++ symbol will act as an ari
je operation for additioa and not coacatena25
juces an extor beck
cannot concatenate a string and aa Integer
ate then
xo thy Age Li
print (x.format
My Age is @ and copa is 6
Global Variables
'* Global Variables are Variables which are created Outside ofthe Function, Bul, They can accessed from anywhere,
in (3815
def functions
print (x)
function() # here, we are able to access variable from outside of the variable
29.63
In 1381:
m= 8956454.23
deg function:
printtx)
function() # here, we
8
The Global Keyword
‘+ Normally, when you create a variable inside a function, that variable is local, and can onty be used inside that function,
‘+ To-create a global variable inside a function, you can use the global keyword,
In tat]
= "fantastic™
print)
function)fantasticBuilt in Data Types
Pyttven has tha following data types BulltAn by default, in these eatagories:
Text Type: str
Numeric Types: int, fost, complex.
Sequence Type: Hit, tuple, rang
Mapping Type: ict
Sel Typos: sa, frozonsat
Boolean Type: boot
Binary Types: bytes, bytearray, memoryview
Getting the Data Type of the Variable
print (type t
print (type (a))
b= (‘appie", *ball', ‘eat
print (type (o))
(Cappie’, “ball))
ype tb)print (type (ch)
in 16
d= (mama's tenn
print (type (dh)
"Age's 56, ‘Salary’: 78896.8)
In 181
e = (*dogt, acaes, (Parrot!)
print (type (0)
mane
f= frozenset ((*bog™, “cat™
peint (typetey)
jarrot™))
In [ayy
g = rue
print (type (a)
In 3s
b= Benelis®
print (type (hh)
eelasa ‘bytests
in tM
1 = bytearray (85)
BEint (type (4))
tn 16]
4 = nenoryviewtbytes (5))
Brint (type ty)
Setting the Data Types Specifically
In [aa]
x= inte)
Brint (type (0)
in (2515
w= 1stt(7, 8% 9)
BEint (type (xh)
colazs ‘list*>
In [26]:
x = tuple ((
Eine (type (3)
5, 6, 8)
In [6]:
x= range (5, 20)
Out teh:
range (5, 20, 2)
In 131}
x = dict (name="Jonn*, age=36y
pEAnt (type (x)
an {33}
x= aat( ("Apple") "Ball™,"cat™))
Brint (type Oo)
sclass "set!>
An (341:
x ~ Erozenset (("Red*,"Bluc™, "Green™))
print (type tx)
an 1361:
x = bool (4)
peint (type Gh)
in Te
x = bytes (5)
BEAnt (type (x)
Typecasting
x = w.astypa(" float’)
our(zilt
40
In (381
x= Float (x)
print (type (or)
selass ‘float's
in (2315
w= Ane (8.56)
out (23]
8
Random Numbers
In [ao]
Amport random
# printing a zandom number from 4 specified range
print (randem.randrange(l, 101)
saat
@ printing a random number in default range 1.e., 0 t0 1
pEint (random. candor ())
0,9128538599745194
In (ayeW printing a random integer number
print (random.xandine (2, 10))
In 156)
@ printing specific number of random nuumbers
print (random. randn ())
Ateesbuteceror Traceback (ost acent call last)
‘eapythen-Lnput-S6-971 8429800385 bn 0
1 0 pEAnting spacitia nunber of random nuusbere
2
so--> 3 print trandom.candn(})
AeeributeError! module ‘randont has no attribute ‘randn*Operators are used to perform operations on variables and
values.
Python Operators are divided into the following groups
Aritumetic operators
Assignment operators
Comparison oparators
Logical operators
entity eperators
Membership operators
+ Bitwise operators
Arithmetic Operators
‘+ Mor floor divison
5 -Wfor modulus
'¢ "for exponentsBrine te)
P= ly
2
¥
aoety
se
Assignment Operators
+ “= for assignmont
4 “+= for active assignment
+ fr subtractive assignment
+ "fer mutipeatve assignment
+ "fr dvsiva assignment
41 forfooraivsive assgneont
'¢ "=" for modulus assignment
4+ "T=! for exponentiation assignment
‘+ ">=! for tt shit assignment
1+ “<< foro shit assignment«= 50
kre Sf similar to x = x05
print (x)
35
an (ae
# subtractive essigneént
x= 50
eons
peint (x)
45
In (231
multiplicative assignnent
= 50
no S
‘peint (x)
250
An (351:
¥ divisive assignement
50
xin
print (x)
10.0
an (28):
¥ flor division assignnont
x= 50
xhln 9
print (x)
an (191
‘podulus assignment
print (x)
In 190)
# bitwise and assignsent
ees
ein
print (x)50
print (2)
fy
print (=)
2
print (x)
Comparison Operators
for aval commpariaon
‘+ efor not equal comparison
‘+ ">for Greater than comparison
“€ for lasser than eomparison
“>=! for Geeater than equal to comparison
for Lesnar than equal to comparison
print (e == 9)y
print (x!*y)
print (¥)
True
pee
int (xy)
sale
True
y= 9
print (xy)
eve
Logical Operators
‘+ "AND Retuons true, I both the statements aro True
'¢ OR’ retums tue, One of the Statements aro True
1+ "NOT retums true, wil Reverse the Resall,
# AN Operat
ee
xo yand x>5Identity Operators
‘+ fa, Returns true, if both the objects are same
‘© Is not, Rotums tru if bath the objects are not the same
print ( mis mot n)
Membership Operators
‘+ In Retums True if sequence with the specified value is present in the object
“+ notin, Rotums True if a sequence with the specified value is net prosent in tho abjectprint (y da x)
print (z in x)
print (a dm x)
Bitwise Operator
‘+ & AND Operation
‘+ |, OR Operation
'*§.XOR Operation
‘+ =, NOT Operation
'« >>, Right Shin Operation
'+ << Left Shit OperationInu
W Printing Strings into Fyehon
print ("Hallo")
print ("Welle")
Helle
Helle
In tthe
= “chocolate
xi-3-2)
ueiil:
toa!
in [21
V assigning Uaiuas to the String
a= *Helle®
print (a)
Hetie
3n 1313
W steinga as arzaye
a= tHello, World!=
print (a{i})
an (4)
4 Slicing
b= “Hello, ortd!*
print (b{2:51)
Ao
In 151:
VW Neyative Indexing
tn (61:
4 Steing Length
a= “Hello, World! \
kninial™
bm 1 eka
fokjnkj kjk}print (len(a))
a
a=" Hello, Horld! *
print (a.strip()
Hello, Worlat
in [8]:
# converting inte lowercase
a= *Hello, World!*
pEint (a-lower())
hetie, worl
In [911
vertitig dnto uppercase
a= *Hello, World!*
print (a.uppert)}
HELLO, WORLE
te 109]
# using replace function
a ~ Melle, World!™
peint (a.replace (i, *I"))
Jolie, Worlat
In Qs
# splitting a string
a “He:
peint (a
oy Bort}
phicts))
IHietio', * Wort! "]
In 10515
# String Formatting
age ~ 36
txt = “My name ia Johny Fam (9
Print (txt. format (age) )
My name is Johns am 36
Other Important Functions
‘+ capitalize() Converts the fst charaeter lo upper ease.casefolit) Converts sting into lower case
camter(} Returns 3 centered sting
count) Returns the number of times 9 spectied value occurs ina string
encode) Returns an encoded version of the string
endswth() Returns true ithe sting ends withthe spaced vatua
expandtabs() Sais the tab size ofthe string
fine} Searches the string fora specified value and returns the postion of where it was found
format(} Formats specified values ina string
format_mapt) Formats specifies values in sting
index() Searches the string for specified volue and rotums the position of where lt was found
isalnum() Retums True i allcharscters in the sting are alphanumetic:
isaiphat) Retums Troe ital charactors in the sting ara in the alphabat
isdacimall) Retums Tivo fall characters inthe string are decimals
isdipit) Retums True if all characters in the sting are cigs
iskentior() Returns Teve ithe string isan idenifier
istowort) Rebus True ial characters inthe sting are lower case
isnumere() Returns Trve ital characters inthe sting are numeric
isprintable() Rotums True if allcharactes in the string are printable
isspace() Returns True if al characters inthe string are whitespaces
isto) Ratums True ifthe string follows the rules of tite
isuppar() Returns True ital charactors inthe sing are uppercase
{nt} Joins th olarnonts of an Rorable Yo tho and f the ering
Hust) Returns let justified version of the string
lower!) Converts. a sting ito lower case
Istip() Returns a let tim version ofthe sting
makeirans() Reluns a translation table to be used in translations
parition() Retuns a tuple where the sting ks parted into three parts
replace() Returns a sting where a specified valu is replaced with a specified value
ffindl) Searches the sting fora speciiod value and retums the last positon of whore twas found
‘index(} Searches the string for a specified value and returns the last postion of whero it was found
Aust) Retuins-a Fight jusiied version of tho string
‘Parition() Returs.a tuple where the string s parted into tree parts
repli) Splits the sting al the spectied separator, and etuine a Hit
‘sirip() Retums aright tim version ofthe string
sol) Splis the sting atthe specified separator, and retums a list,
splitines() Spits tho string a ina breaks and rotums a ist
stariswith() Retums iruaif the string starts with the specified value
strip() Returns timed vorsian ofthe string
swrapcase() Swaps cases. lower case becomes upper case and vice versa
‘Wet) Converts the fest charbcter of ech word lo Upper cabs
transiate() Returns a translated string
upper) Converts a sting into upper ease
Zi) Fits the string with a specified numberof 0-values atthe beginningIf Else
Conditional Statements
+ Equals: a=b
+ Not Equats: 3 f=
© Less than: a
‘+ Greater than or equal bo: a>= b
b= 33
afb >a:
Print (™b is greater than a")
aes — be:
print("a and b are equel™)
a and b are equal
b= 3:
Afb >a:
print(*b ia greater than a)
enie a == b:
print(a and B are equal")
else:
print(*a 4s greater than bY)
at or than b
Ae a> br printita ts greater chan b*)
a ts greater than b
In [81t
er
Brint ("A") 4£ a> b else print("s")
In (6)
a= 330
b= 330
Print ("A") ££ a> belee print(te") Af a == b alee print ("8")fea>t
print
At least one of the conditions ds Tr
a)
tements as long as a condition is true.
2
3
5
With the break statement we can:
1op the loop even if the while condition Is true:white
ae
‘With tho continue statement we cin atop the eusrant iteration, and continue withthe next:
mnie i <6:
4s
With the sige statement we ean run a block of cade once whan the eenditian ne Jonger is true:
waste
For
‘A for loop Is used for iterating over a eequence (that is elthor a list, a tuplo, a dietionary, a sat, or a string). The is lees tka
the for keyword in other programming languages, and works more like an iterator method as. found in other abject-
orientated programming languages. With the for loop we can execute a set of atatements, once for each item in alist, tuple,
sot otc
apele
bana¥ looping through @ string
for x in “banana”:
eine ts),
e2e500
In 91s
‘using the Break stateaent
fruits ~ (Tapple
for x in fruite:
Beinets)
Af x == "banana":
‘break
banana”, cherry")
apple
banana
In (201:
W using the continue statement
fruits = (Tappie
for xin fruits:
4f x == “banana”!
continua
print te)
banana”, “cherry"]
apple
cheeey
an 12a}
using eh range) function
for x in range(?)
print),
°
a
2
3
4
5
In 1221
“VW uaing the start parameter
for x in range (2, 63
prints)In (2a)
factemencing the sequence
foe x An rango(2, 30, 3)1
printie)
2
5
8
a
aa
a
20
23
26
29
in (2415
4 fer ond olan
for x in range (6):
print in)
alse:
Print ("Finally finished !™)
nally €inished!
In [aye
adj = (red, “big
fruits ~ (*appio™,
“tasty”
“banana®, “chorry"]
for x in odj:
for y im fruits:
print bc
red apple
red banana,
zed cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherryIn fel
taking 2 Lise
List = [Tapple", “banana”
print (Lise)
wonerry"1
[eppie', ‘banana’, ‘cherry"!
an 1621
accessing the List
Liot = {*apple", “banana”, cherry")
print (ist)
banana
an (631:
# negative indexing
print (list (11)
cherey
na:
accessing a range of Lisi
I'cherry", ‘orange’, ‘kind
In 16515
print (1istt-5:-2)
Ueherry", Torange', "eiwitt
In 166]:
“, “orange“, “kini*, ‘melon, “mango*)
@ reassigning the items in the 1ist
Lise [1] = ‘iesezean!
print (List)
[tappie', ‘icecream’, ‘cherry’, ‘orange", *kiwi', ‘melon’, ‘mango*]
tn 161:
4 reversing the List
peint (atten)
[tsanget, tmelen', "kisi", torange!, ‘cherry', ‘icecrean!, ‘applet]
An {68}:
@ concatinating tvo Tista
List2 = [*patate*,, ‘tomato')
Aist3 = dat + diotz[rappie', ‘icecream', ‘cherry’, ‘orange",
in [69]
# appending dtens to the Liat
List -append(*caulifiower*)
pEint (list)
Lroppie', ‘icecream, ‘cherry’
Is (701+
WV dnserting deena to the List
List insert (0, “brinjal)
print (Lise)
['brinjal', ‘apple’, ‘icecrer
ne
@ renoving teens from the
List .romove(*brinjal*)
print (List)
Lrappie', ‘icecr
In (51:
@ extending itens to the list
List extend ( ("Covert tappt})
print (Lise)
Ltappie', ‘banan
te (73)
@ sorting the List
Lider sore (y
print (List)
[tepple!, teaulifievert, teherry',
green ty
In (7415
1 applying pop operation
List -pop()
print (List)
Lopple!, ‘cauliflower’, ‘cherry',
In (7312
Waiy ig a Se EEE
List. remove(*1")
List -renove(*r")
+ ‘eherry"s ‘orange’,
ym", ‘cherry', ‘orange",
y teharey", ‘orange’, tkiwi', ‘malont, ‘manga',
‘mango", "potato", ‘tomato"]
“cavlifiewer*]
ton", ‘nango", "cauliflower"
‘mango*, ‘caulifiower*]
ttlower', ‘appt]
‘14, tungs!, tmolon', tet, toran
"1%, tnango', ‘melon', ‘ot, ‘oranLine anova (tot)
print (List)
[tapple', ‘caulifiover!, teherry', ‘o', Miceeream', "ivi", ‘mango!, ‘malen', ‘orange’, 'r!]
In (7815
copying the list
Adsteopy = List. copy ()
print (Listeopy)
Ltappie', tcaulitiever', ‘cherey', ‘et, ‘icecream’, "kivi', tmango!, tmalon', ‘orange', 'r*]
worms
@ feversing the list using reverse function
List reversed)
print (list)
Let, ‘orange’, ‘melon’, taango’, 'ELML', “Sescceam, "at, ‘eheeey', “cauliflower, ‘epple']
In [7815
¥ counting the elemento in
x = List count (*orange")
print (x)
In 17815
using Maes az stack (#10)
stack = (2) 3) 4 Sy 61
stack-appendt7)
stack.appendis)
sek. appendi(o}
In [Bo]:
print (stack)
12, 3, 4s Sy be Te 8 91
in 1811
print (stack)
13 5 6
in (82)
using Liate as queue (lize)
from collections import de:
queus = deque({ "Ram! ‘Shyam
Print (quae)oeque | ‘nam!, ‘anyam’, ‘satay “etea' yy
ppand(*Rohan')
queue. appand(*Gopal")
pEint (queue)
doque((*Ram', *Shyam', 'Sita', ‘Gita’, *Rohan', ‘Gopal*})
In [EAs
queue poplefe ()
Reine (queue),
deque((*Shyan*, ‘Sita’, "Gita", ‘Rohan’, *Gopal"])
In 139]
Wclearing the iiar
Lise .cleart
print (List)
u
mi
@ printing the items of a List
List - [*apple", "bananas, cherry")
for xin Liar:
printen,
apple
banana
cherry
in rt
“V checking if the item oxiata or not
List = (topple, banana®, “cherry"]
Af “apple? in List:
Prine("¥os, ‘applet is in the fruies Lise)
Yes, ‘apple’ is in the fruits List
ie ahs
x= a4
y= ih 5, 6
outta:
134 G5, 6)A dictionary is a collection which is unordered, changeable and indexed, In Python dictionaries
are written with curly brackets, and they have keys and values.
+ Mustang’, "year": 1964)
2 ‘Mustang’, ‘year*: 2018)accessing ‘the keys
fee x 4n thisdicts
print tx)
brand
model
year
in 9}:
¥ accessing the valves
for x in thisdict:
print (thisdict (x})
Ford
Mustang
2018
In ae
@ unig the values) co access the values in a dict
for x in thisdict.values()
print tx),
Ford
Mustang
20n8
an (121:
V accessing both the key and values
for x, y in thisdict items():
Printoy yb
brand Pord
model Mustang
year 2018
in at
W checking if that particular string extats or aot
thisdict = (
Sbrandts Ford",
nodel": "Mustang",
Myeart: 1964
'
Af “podel™ in thisdic
print("¥en, ‘model’ is ene of the keys in the thisdiet dictionary")
Yes, ‘model’ is one of the keys in the thisdict dictionary
mn 31t
‘adding icons to the tat
thisaiet = (
thiadict("color™) = "red"
thisdict{“color™) = blue’
ehindict(teslors™) = "red™
‘BELnt (thLadice)(Mbeand': ‘Ford*, ‘model's ‘Mustang’, ‘year
In 3815
£1964, "color: thluet, teolers!:
"red"
4 renoving the Lame from the dict
thiadiet
"brand": "Ford",
model": "Mustang",
cywar": 1364
'
thindict. popttye
print (thiadict)
‘
(brand's ‘Ford", ‘model's "Mustang"
An (381+
@ renoving the ast item from the dict
thisdice = |
ehisdiet.popieem()
print (thiaaicey
(trand’: ‘Ford", ‘modal's "Mustang" )
feos
¥ using dei Keyword to renove the elenents
ehiedict = |
“brands "PoEd",
model": "Mustang",
vyeart: 1968
,
del ehisdice model")
peint (thiaascr)
(tbrand': *Ford", "year's 1964)
In [40]
@ deleting the dictionary.
ehiedice =
wyear": 1968
’
det thisdice
endadict = (
“brand": "Ford",
Swodel": "Mustang",
Syear*: 1964
'
thisdict.clear()
print (thiadice)ie 4315
W nested dictionary
ehsdat =
hase”; MERLIN,
yeas" 2004
’
eniid? =
myear™
'
child} ~
name": “Linus”,
year + 2011
’
chide =
name” + “Linus,
year"; 2011
'
myfaniiy = (
senilai” 2 chsidt,
wchildz" : chiid2,
wehilda* 3 chiidd
'
myfamiiy2 =
nenLldgmeniias,
’
family = (
‘smytantly” :myfanily,
tmytamily2" :myfamily2,
'
family
ue ta}
(nyfamily': (chiddi': (fname: ‘Emil, "year's 20041,
sehild2": (*name’: ‘Tobias*, ‘year’: 2007),
tehild3': (tname’: ‘hinus*, *year': 20110).
ymyfamily2': [*ehild4*: (*name': *Linus*, ‘year's 2011)))
Tn (2315
one dictionary containing multiple dictionaries
myfaniiy = (
child.”
syear”
a
meniiaz"
1
ventas"
nyear®
)
'
myfanily
Oubt231¢
(enitd' (thane?
Nebiid2'? (fname!
tehild3"; [tnane?
temilt, "year": 2008),
trobias*, tyear': 2007),
‘Linas', tyeor': 20011thisdict = dict ibradde"rord™) sodeleMustang™, year
4) year": 1960)
Dictionary Methods
‘+ cear(} Removes all the elements trom the dictionary
ony) Raturns a copy of the dictionary
fromkoys() Returns a dictionary with tho spocied Koys and values
ge) Returns the value of the specifies key
items() Returns a st containing the a tuple for each key value pair
heyst) Retums ast conisining the dlctonay’s keys
pop() Romoves tha element withthe spocitiod key
popitem() Removes the last inserted key-value pair
‘otdofaul(} Ratums the value of the spaced Koy, Its key does: not exist: insort the kay, with the spacifnd value
Update) Updates the dietonary with the spectied key-value pairs
values() Returns a Kat of al the values inthe dictonary
1A (0):
def primenuaer (3
Af x
for 4 in range(2,«//2)
A (ibe):
BELAE DACRE 48 ane BEIKEA)
break
aise:
print (Coumber is prise nom)
umber 1s peime ne
¥ erogran to display the Fibonacci sequence up to term
nears = int (input ("How many tora? *))
ese then
Af terns
print ("Please enter a positive 1
edd terms ~
print (*ribonace! sequence upto*,n
princ (aly
els:
print (*Pkbonaec! sequence:")
while count = nse
princénn)
nth =n + nd
0 urd
a= na
2 = neh
How
y terme? §
Fibonace! sequence:an Tl
‘tring = = 50M
> string.oplit()
ne tx(2))
our ga71
50
an (191
‘atring = 7% 50%
‘otring.splitt* *)
Our (a91
153, 150",
miaPython is an object oriented programming language.
Almost everything in Python is an object, with its properties and methods.
A Class is like an object constructor, or a “blueprint” for creating objects.
The Init Function
‘Tho examples abave ara classes and objects in their simplest form, and are not really useful in ral ie applications.
To.understand the meaning of lacses we have fo understand! the buitin init) funetion.
Allclasses have a function callod init), which is always executed whon the class is bong initiated.
Use the init function to assign values to object properties, or ether operations thatare necessary to do when the object is being
cova:piaaytunct)
Helle my name 1 John
‘+ The:solf parameters a reference to tye curren instance ofthe class, and ks used to aecess variables that belongs tothe elass.
‘+ ltdoes net have to be named self, you can callit whatever you Bike, but ithas to be the fet parameter of any function in the
‘dase:
In 16)
class Perasn:
def _init_(mysillyobject, name, agels
Bystllyebject.nane - name
nysillyobject.age = age
def mytuno (abe) t
print ("allo ay name 48 * + abe.nama)
pi ~ Person (Miche,
pl.myfunce)
0
Helle my name is John
In 161:
V madityling the ebject properties
pl.age ~ 40
peint (plage
40
‘Fdeleciag the object propert
dei plage
peint (pl-ageh
AtbesbuteError Traceback (ost acent call last)
ss0-> 5 print (plage)
Ateeibutezeror: "Person! object has no atteibute ‘aget
class cal:
dae init (eeif, ®, y, 2,
PEint ("addition :*, self x-self.y)
def subtocks):
print ("subtraction :7,
dae ul (o0!
print (*muitipiication ¢*, aelf.«
def divisolt);
Print (*Bivison s", self.x/selt.y)
def floor(seif):PELHE(TEIeor Divison 2", selt-a//melty)
ase oxpteeity:
pEinG(*Emponentiation 3%, aeif.a**selt.y)
a= can(3, 5 3, % a)
‘aacd ()
a.eub |)
acael ()
endiv()
a.fleor ()
ep ()
Addition + 8
Subtraction : -2
Multiplication 2 12
Divison : 0.6
Fleer Divison + 0
Exponentiation
in (0315
import pandas asp
in (2a1e
help (p.read_eav
Help on function read cay in module pandas.ie.parsers:
ead_eay(FLLepath or burfartUnion (ste, pach1ib.Path, JO(-ARYSte]], gope',", delimiearsdione,
headers'infect, sames~None, index col-Wone, usecola-None, squeeze-Palse, prefix-Hone,
mangle_dupe_cola~Trve, dtype-None, engine-None, converters-None, true_values-Nont
foise_values-Hone, skipinitialspace-False, skiprowa-None, skipfooter-0, nrows-Wone,
na_valvessiione, keep_dafault_naeTrve, na_filter=Tmue, vethase=false, skip blank_lines=True,
parse_datessFaiee, Lifer datetime format=False, keep date_col=Faice, date pareer=None,
Gayfist=False, cache daves«True, iteratorsFalse, chinksizestone, compres’ion='inter',
thousandamitono, decinil=b*.*, Lnsterminator=tione, quotechar='*", quoting=0, doublequote=True,
eacapechar-Norie, comment=Noriey encoding-Hone, dislect-Hone, orrer_bod_Lines-True,
xorn_bed_lines~frue, delim whitespace-False, low_menory~fiue, memory fop~false,
float _precisionstone)
Road 2 comma-separated values (cav) file into DataFrane.
‘Algo supports optionally iterating or breaking of the file
Ante chunko.
Additional Help can be found in the ontine docs for
‘10 Tools "_.
Paranaters
flepath_or buffer i stry path object or filevlike object
Any valid string path 43 acceptable, The string could be a URE. valid
URL echomes include http, ftp, 63. and file. For filo URLs, a host is
expected. A local file could ber E1le1//locathoat/path/toftable.cay.
Hf you want to pass dn a path object, pandas accopts any “‘on-Pathbdke’'.
Sy fEle-Like object, we feter to
a rile handler (e.g- via builtin
+ ate, default ',
DeLiniter to use. If sap 18 Rone, the © engine cannot automatically detect
the separates, but the Python parsing engine can, meaning the latter will
be used and automatically detect the separator by Pythoi"s builtin onifter
tool, “eav.Sniffer”’, In addition, separators longer than I character and
Gicforent from -*\o4'”’ will be intexpreted ae reguiar aupressions and
WiLL ala foves the use of the Bython parsing engine. Mota that regex
Geliniters are prone to ignoring quotes data. Ragex example: ~~ "\z\t"
sLiniter : ats, defavit *"Rone'’
Alias for sep,
header : int, list of int, default *infer'
Row number(s) to uso as the column nanes, ‘and the start of the
Gata. Default behavior is to infer the column mamas: if no names
are passed the behavior is identical to '“header=0'* and column
hasan ave 1nfecrat Prim sha Plrae Wie ne the le, 4¢ nélisin
jects with a “‘readt)"* method, such as
‘open"* function) or ‘°stringioaren ore passed explicitly then the behavior iz identical to
“vneader=one’”, Explicitly pags “"header#0~ to be able to
replace existing nanos. Tha header can be a list of integors that
spocity roy locations for # malti-index on the columns
eva. [Oe4)J}. Entervening rows chat aze not specified will be
skipped (e.g. 2 in this exanple is skipped). Note that this
Parameter ighores conmented Lines and empty Lines if
‘skip blonk_lines=True’’, 40 “"headersd"* denotes the first Line of
data rather than the first line of the file.
famed ; MEEBY-1ike,, gptiboel
Liat of column names to ude, TE file contalda no header cows then you
shoutd explicitly poss “‘header-None'', Duplicates in this List are not
allowed.
index_col : int, ste, soquance of int / ste, oF False, default ““None’*
Colimnts} to ise aa thé vow labels of tha” ‘UstaFrane’", either given ae
string nane or column indes. Tf a sequence of int / str is glven, a
Multitnder ia used.
Note: “index colsFalse’” can be used to force pandas to ‘not™ use the first
columa a5 the index, 0.9. when you have a malformed file with doliniters at
the ond of each Line.
usecola : List-like or callable, optional
Retucn a subset of the columns. EF list-like, all elements must either
be positional (i.e. integer indices into the docusent columns) or strings
that correspond to column names provided either by the user in ‘names* or
inferred from the doeuant hesder rew (2). For example, a valid ligt=llke
usacols’ parameter would be °°[0, 1, 217° oF "7 [Mfoo', Dae’, "baz"
Element order ta ignored, zo “‘ueecols~[0, 1)"* is the game as °'[1, 0]
To instantiate a DataFrane from ““data’’ with elenent order preserved us
“pdatead_csvidata, usecois={‘fos', ‘bart]) ({*fo0", ‘bar"]}** for colums
in "foo", ‘har*]"* order or
pa-road_esy(data, usocols«|"foo, tart) [{tbaet, 'foa"}1”
for “"['bae", *foo')” oder,
If callable, the cablable function will be evaluated against the colvan
names, returning names whore the callable function evaluates to True. Ar
example of a valld callable argusent would be *“lanbda x= x.uppex() in
[YAWR', 1RBB', 'DOD']". Using this parameter results in much faster
parsing tino and lover mensry usage.
squeeze : bool, dafwult False
Lf the pazsed data only coitdins one célumn then zétura a Seties.
prefix © str, optional
Prefix to add to column nunbers when no header, eg. 'X" for XO, x1,
mangle dupaeols : beol, default True
Duplicate coluans ill Be specified ag 1K?, "M.1', ,. THY, eather than
'R'...9K", Passing In False will cause data to be overwritten if there
are duplicate nanes in the columns.
type : Type name or dict of column => type, optional
Data type for data or columns. Bug. (‘a's np.floatés, ‘bt: np.ine32,
tote trated?)
Uso “str” or ‘object’ rogather with suitable “na x
to preserve and not intexpret dtype.
If converters ace specidied, they will be applied INSTEAD
Of dtype conversion.
engine 2 (*c", ‘python*), optional
Parser engine to uae, The C engine dn faster while the python ongine is
Gueeantly adve Feetilre—complece.
converters 2 dict, optional
Dict of functions for converting values in certain columns. Keys can either
be integers or column labels.
trpe_values : list, optional
Values te consider as True,
false values + Liat, optional
Valueo to consider as Falae.
oxipinitialepace + bool, defavit raise
Skip spaces after deliniter.
skiprows + List-like, int or callable, optional
Line numbers to skip (Q-indexed) or number of Lines to okip (int)
at the start of the file,
salues” soteings
Tf callable, the callable fuacticn will be evaluated againar the cow
indices, returning True if the row should be akippod and False otherwise:
An example of a valid callable argunent would be "lambda xz xin (0, 2]°°.
ekipfocter = int, default 0
Wiser of Hiss at batten of C116 te akip (Unoupposted with engine-tet).
nova : int, optionalnajvalues : scalar, ste, listelixe, ox dict, options
Additional strings to recognize ag NA/MAN. TE diet passed, specitic
pee-colunn NA veluos. By defSUIt thé folloeing values acs interpreted 45
Malis", 'WB/A', "AN/A AJAY, AMA's "91. HIND,
SLAINO?, SLACQNAN', HVA, OMA", NULL", "Hat",
saul.
heop_dafault_na + hoot, default Tews
Whether Sr not to inelude the default NaN values when parsing the data.
Depending on whether ‘na values" 4s passed in, the Behavior 1s as follavst
+ if *keep_default_na’ 4s True, and ‘na_values" axe speciticd, ‘na_values|
Ls appended to the default Ma values used for parsing.
+ Tf “keop_dofault_na’ is True, and “na_values” are not specified, only
the default aN Uslues are uned for parsing.
+ TE *keep_default_na’ ie False, and ‘ne_valuos’ are specified, only
the Holl values specific ues’ are used for parsing.
+ If “keep defautt_na’ 19 False, and ‘na_values’ are not specified, no
atrings will be parsed as Nal.
Mote that 4f ‘na filter’ is paged in as Fai
‘nA values” pAZARSters Will be ignored.
ne_filter : bool, default True
Detect missing value markers (empty strings and the value of na_values). In
data without any NAs, passing na f1ltersFalse can improve the performance
of reading a large file
verbose + bool, default False
Indicate number of WA values placed in non-nunerie column:
skip_blank ines + bool, default True
Tf true, skip over blank lines rather than interpreting as tiaN values.
parse_dates : bool or list of int or nanes or list of lists or dict, default False
The behavior is as follows:
the “keep_dafauitna® and
+ boolean. If True -> tey parsing the inden.
+ List of int or nanes. e.g. If [, 2, 3] -> tey parsing colums 1, 2, 3
each as a separate date column.
+ List of Lists. e.g. If [{1, 311 => combine colunns 1 and 3 and pars
te column.
+ ("fee + (1, 3]] > parse columns 2, 3 4 date and eal)
pesult "£36?
Tf a colunn or index cannot be represented as an array of datetines,
aay because of an unparseable value or a mixture of tiezones, the column
oF index will be returned unaltered as an object data type. For
nan-atani Jrotina parsing, uso “"pd.to datetime’ after
“‘pdexgad_cov'*, To parse an index or column with a minture of timezenas,
spocity “‘date_parser’” x0 be a partially-applied
*pandas.to_datetine’ vith ““utcsTrue’". See
10.csv.mixed_Cimozones’ for more.
Motor A fast-path oxints for eeG601-formatted dat
infer_datetine format + bool, defwult False
TF True and ‘parse dates’ is enabled, pandas will attenpt to infer the
format of the datetine strings in the columns, and if it can be inferred,
awitch to a faster method of parsing then. In sone cases this can increase
the parsing speed by S=10x.
kesp_datecol + bool, default Palos
Te True and ‘parse dates’ specifies combining multiple coluans then
keep the original colunna.
date_parser : function, optional
Function to use for converting a sequence of string columns to an array of
Gatetine instances. The default uses ‘“dateutil.parser.parsor™ to do tho
conversion. Pandas will try ta call ‘date paraar’ in threo different ways;
advancing te the next if an exception occure: 1] Pass one or more arreys
(aa defined by ‘parse _dates’) as arguments: 2) concatenate {row-wise) the
string values from the colunns defined by ‘parse dates’ into a single array
and pass that and 3) call ‘date parser’ once for each row using one or
nore strings (corresponding to the columns defined by ‘pares dates’)
arpingnta.
daytirat 7 bool, default False
DD/MH format dates, international and European format.
cache dates : boolean, default True
If True, use a cache of unique, converted dates to apply the datetine
conversion. May produce signifieant speedeup unen parsing duplicate
date strings, sapacially ones with tinerone offsets,Return TeatPileReader object for iteration or getting chunks with
get_ehunk ()
chunkslze”s dnt, opthonal
Return TextFileReader object for iteration.
See the “10 Tools docs
chvtp!//pandas. pydata .org/pandas-docs/stablefio-ntmi #lo-chunking>"__
for more information on iterator’ ’ and \ chunkeize
compression + ('infert, ‘gzip’, ‘be2', ‘zip’, ‘xst, Hone), default tint
For on-the-fly decompression of on-disk data. If ‘infer’ and
‘filepath or buffer” da path-Likes then detect compression fron the
Following extensions: *.gz", ‘.br2*, ‘.rip', or *.xz" (otherwise no
decoapression). If using ‘zip', the Z1P file must contain only one data
file te ba read in. Set to lone for no decompression.
se wersionadded: : 0.
2 aupport for ‘rip’ and ‘xz’ compression.
thousands ste, optional
Thousands separator.
‘ate, default *.*
Character to recognize aa decimal point (e
Lineterminater + str Uength 1), optional
Character to break file into lines. Only valid with ¢ parser.
quotechar : str (length 1}, optional
The character used to denote the start and end of a quoted item. Quoted
items can include the delimiter and it will be ignored.
quoting + int or cev-QUOTE * instance, default 0
Control field quoting behavior per ‘‘cav.QUOHE_**' constants. Use one of
QUOTE MIRLIMAL (0), QUOTE ALL (1), QUOTE_NONWUMERIC (2) oF QUOTE NONE (3).
Goublequote 1 bool, default ~ "True
nen quotechar Ls specified and quoting 1s not "QUOTE NONE"-, Indicate
Whether oF nat to interpret two consseutive quoteehar Glenanta INSIDE
field as a aingla ‘“quetschar’’ elesent.
eacapechar z etr (Length 1}, optional
One-character string used to escope other characters.
comment : ate, optional
Indicates remainder of line should not be parsed. If found at the beginning
of a line, the line will be ignored altogether. This parameter must be a
aingke character. Like empty Lines (az long as "'kip blank lines~True’ "hy
fully comented Lines are ignored by the parameter “header” but not by
“skiprows". For exasple, if “‘conment='1!'", porsing
fespty\na,b,c\nl.2,3°* with ““headers0"* will result in tasbsc* being
treated az the heador.
encoding t atz, optional
Encoding to use for UTP when reading/welting (ox, "utf-O"}. “List of Python
standard encodings
shttpst //docs. python.org/3/Library/codecs.htaldstandard-encodings>'_
dialect : #tr or cev.Dialect, optional
Tf provided, this paranater will everride values (default or not) for the
following parameters: “delimiter”, “doublequote’, ‘eseapechar’,
skipinitialapace’, “quotachar™, And ‘quoting’. If it is nacasaary te
override values, a ParserHarning will be issued, See cav.Dialect
docunentation for more details,
error_bad lines : bool, default True
tines with too many fields (e.g. a csv line with too many conmas} vill by
default cause an exception to bs raised, and no DataFrama will be returned.
Tf False, then those "bad Lines" will dropped from the DataFrone that is
returned,
warn_bad_lines + bool, default Tru
use ',* for European data).
) is True, @ warning for each
‘WILL be output.
ee: beol, default False
Specitie vhethec ot nok whitespace (0g. "°F 877 98 18 8p WiLL
aed an the sep. Equivalent to setting *'sop-‘\o+*"", TE this option
is set to True, nothing should be pasged in for the ‘delimiter
parameter.
+ Worakonadéed: © 0.
1 support for the Python parser.
low _menory : bool, default true
internally process the file in chunks, resulting in lower menory use
while parsing, but possibly mixed type inference. To ensure no mixed
types oither set False, of specify the type with the “dtype” parameter
Note that the entire file is read inte a single DataPrane regardless,
se the “chuoksise” or ‘iterstor” parameter to retwrn the data in chinks.
(only valid with ¢ pazser).
menory_nap : bool, default FalseAk Lemp as poUvsUe Lok LLLep oh URN my nt aaa MyeeL
Girectly onto mansey and access the data directly from there. Using this
option can inprove pestormance because there iv ne longer any 1/0 overhead.
float_precision : str, optional
‘Spocifies which converter the C engine should use for floating-point
values. ‘The options are ‘None’ for the ordinary converter,
igh” for the high-precision converter, and “round trip” for the
round-teip converter.
Returna
DataFrane or TextParser
A commasseparated values (esv) file is returned as tvondimensional
data structure with labeled axes.
see Also
Eo_csv t Write DataFramo to a comarsoparated valuos (csv) file.
read_cav 1 Read a comma-separated values (csv) file into OataFrano.
esd fuf ¢ Road a table of fixed-width formatted lines into DataFrame.
Exasples
>>> pd.read_csv(‘data.cev') # doctest: +3KIP
In he
det funk, ¥)
In (261+
welt, x yA
def add (net):
print ("addition 2", self.x + self.yb
deg subteets) +
PEAnt(*Gibtraction 2", self.
Ley
a= cai(3, 4)
a.add()
‘alaub()
Addition : 7
SubtractionA date in Python is not a data type of its own, but we can import a module named datetime to
work with dates as date abjects,
Peane (x)
2020-02+25 19205:00.483050
import datetime
print (e.moath
print (e.¢ay)
print Ue 12 (MRAP) )
Print (x ateftime ("8d") }
2020
2
uesday
Other Date Formats
1+ Sa Wookay, short version Wed
{%A Weekday. fall version Wednesday
‘iw Weekday as a number 0-6, O%s Sunday 3
%4 Day of month 04-31 31
‘kb Month name, short version Bec
568 Month name, full version December
Sim Month 98.0 number 01-12 12
‘uy Year, short version, withaut contury 18
S6Y Yoor, fll version 2018
SH Hove 00-23 17
‘et Hour 00-12 05
Sp AMPA PM
eM Minute 00-59 41
4S Second 00-50 08
Sf Nicrosecond 000000-980909 548513
‘kz UTC offsat +0100
2 Timezone CST‘+ SU Week nuriber of year, Sunday as the fist day of weak, 00-59 62
'*SiW Weok number of year, Monday as the fit day of week, 00-53 52
‘+ Sic Local version of date and time Mon Dec 31 17:41:00 2018
‘+ Sx Local ersion of dato 1231/18.
‘+ %X Local version of time 47:41:00
+ 896 A % character 9A RegEx, or Regular Expression, is a sequence of characters that forms a
search pattern.
RegEx can be used to check if a string contains the specified search
pattern.
pyects
Meta Characters
‘+ [A set of characters te-m|*
\ Signals a special soquonce (ean also be used to escape special charactors) "a
Any character (except newiine character)
Starts with “*helleT
“dollar sign” Ends: with
‘sar sign’ Zoro or more occurrences “ai”
‘One or more occurrences “aie”
(Exactly the specified number of eccurrences *alf2)"
Ether or “as{tays™
+ (Capture and group
Built-in Function
Fecal Retums. a ist containing all matches
search Retums a Match object theres 2 match anyahere inthe string
spit Retums a lst where the string has been spit at each match
sub Replaces one or many matches witha string
Special Characters
‘+ WRotums 2 match if the specified characters are atthe baginning of the string "The
15 Wh Returns a maten where the specified charactors are at the boginning eal tho end of a word Main"rainly”
\B Rotums.a match where the specified characters are present, bul NOT at the beginning (or at the end) of a word -\Bain*
rans"
\d Returns @ match where the string contains digits (numbers rom 0-9) "a"
\O Returns a raich where the string DOES NOT contain digits “OD”
\S Retums a match where the string contains a whilo space character "s"
1S Rotuing a match whore the sting DOES NOT contain a white space charactor "S*
\w Returns a match where the string contains any word characters (characters from a to Z. digs from 0-9, and the underscore __
chacacter) "wr"
|W Retums a mateh whore tne string DOES NOT cantain any word charactors "Wr"
'* 2 Returns a match i the specified characters are at the end ofthe sting “Spalin\2"sets
[orn] Returns a match where one of the specified characters (a. r. orn) are present
[ern] Returns a maten for ary Inver ease character, alphabetely between 2 and
[Pam] Returns a match for any character EXCEPT a, ¢, and n
[0123] Retums a match where any of the specified digits (0, 1,2, oF3) are present
[0-9] Roturns a match for any digit betwoen 0 and 9
[0-S][0-9] Returns. match for any two-digit rurnbers from 00-00 69
[aeziz} Ret a match for any character alphabetically between a and z,iower case OR upper case
[+] Insets, +,*.. J (8.0 has no special meaning, s0 [+] means: retum a match for any + character in the str
str = "the rain in Spain
Iali("ai", atz)
str = “The cain in Spa
X= re.search("\s", str)
ce character 4s
print ("The feat white: ed In position:™, x.atare ())
The first waite-space character is located in position: 3
Amport re
x= reeplitt
print (x)
U'fhet) feainty “n'y 'Speint)
import re
ote = “The rain
x= ee aub(m\e"
print (*)
Thesealnoingspain
amport re
ate ~ "The rain in Spain"X= re-searoh(c"\bS\wt", str)
print (x-spanQ)
az, 17)
an ait
Y printing the group where
Amport re
ate = “the rain dn spain
w= resgearch(c"\bS\wi", ete)
pEint (x.graup0))
Spain
in [Mls
xx = *quru99, education Ls fun"
sh = re, Eindall (e"*\¥*, 2)
print (rl)
ren)
An 130
sx = Tgurui9, education Ls fun"
1 = re. findall (e"*\we", ee)
print (rl)
[*gueu99")
feds
rogex = *
dag chock (email)
AM, 3) 98"
(pass the sequalar expsession
f and the string in search() method
Af (research (regex, email):
peine(*Valid Email")
alas:
print ("Invalid Baal")functional Programming
def function tnd:
ec
dat functions
return 3
dat function@iay
be alt
z= function? (y)
a = functions (2)
B= funetiond (a)
setaes b
in 011
alli)
ue (22)
36.0
In (3215
a1 195)
our12)Q1. Write a Python program which accepts the radius of a circle from the user and compute the
area
2. Write a Python program which accepts a sequence of comma-separated numbers from user
and generate a list and a tuple with those numbers
Q3. Write a Python program to display the first and last colors from the following list.
Q4. Write a Python program that accepts an integer (n) and computes the value of
nénnénnn
Q5. Write a Python program to get the valume of a sphere with radius 6.
is within 100 of 1000 or 2000,
Q6. Write a Python program to test whether a numb
Q7. Write a Python program to count the number 4 in a given list.
Q8.Write a Python program to test whether a passed letter is a vowel or not.
Q3. Write a Python program to concatenate all elements in a
t into a string and return it,Q10. Write a Python program to print out a set containing all the colors from color_list_1 which
are not present in color_list_2
color ist_1 = selWhite, Black", "Red colorist
‘SallfRed", "Green"])
Q11. Write a Python program that will accept the base and height of a triangle and compute the
area,
Q12. Write a Python program to compute the greatest common divisor (GCD) of two positive
integers.
Q13. Write a Python program to get the least common multiple (LCM) of two positive
integers
Q14, Write a Python program to solve (x+y) * (x+y).
hg Write a Python program to compute the distance between the points (x1, y1) and (x2,
16. Write a python program to find the sum of the first n positive integers.
Q17. Reverse a StringQ18, Swap two Numbers
Q19, Write a command to get the documentation of numpy module.
Q20. Write a Python program to find the available built-in modules.Q1. Take a User Input and Print the Fibonacci Series until that number
Hint: inpet> 2 Output> 0.1 2
Q2. Take a User Input and find the Cumulative sum until that number
Hint: inputios Oupuetezeaeaes = 15
Q3. Take a User Input and find the factorial of that number
Hin opus Outputs 12945 = 120
Q4. Take a User Input and rerurn the Inverse of that number
Hint input Output
Q5. Take User's Name as input and Greet that User
Hint Input > Roshan Quiput-> Hi Rochan!, Hope your Day ie good.
Q6. Clean the String: $ 50 M to 50
Hint: ipod» String: '§ 0 MF Output.» Numba 60
Q7. Take First Name, Middle Name and Last Name from the User and Return
the Full Name
Hink Input > Amar lnguta-> Singh Input3> Chauhan Ouiput- Amar Sirah Shovhan
Q8. Take a List and Compute the Sum, Average, Standard deviation, median,
maximum and minimum values
Hin: Inout (2.8.8, 8, 8.7.4] Quiput> Sum 43 Avorage: 487 Standard Deviation: 7 Median: 7 Max: 8 Min: 2
Q9. Take a Number and check whether a number is Prime or not
Hist Input'>9 Output-> Not Prime Input.>1 1 OutputPrie
Q10. Take a Number and Return the Table of that Number
Hint: Input->2 Outpt 2,4, 8,8, 10, 12.14, 18, 18,20Lists
Write a Python program to sum all the items in a list.
Write a Python program to multiplies all the items in a list.
Write a Python program to remove duplicates from a list
Write a Python program to generate all permutations of a list in Python
import itertools
Dictionary
Write a Python script to sort (ascending and descending) a di
Input: (a: 96, b 89, c: 78) Output a, b,c
Write a Python script to add a key toa dictionary.
Sample Dicionary : (0:10, 1:20} Expected esuit : (0:10, 4:20, 2:30)
Write a Python script to concatenate following dictionaries to create a new one.
Sample Dictionary ;dict={1:10, 2:20) dicd=(8:30, 440} dic¥-(5:50,6:60} Expected Resull (1; 10, 2:20, 9:90, 4:40, 6: 60,6: 60)
Write a Python script to check whether a given key already exists in a dictionary.
Input: (89, b:00,c:88} check fore
Write a Python program to iterate over dictionaries using for laops and add the values
Input: (8:20, 8:70, 90) Output: 180
Write a Python script to generate and print a dictionary that contains a number (between 1 and1h) in the form (x, x")
‘Sample Dictionary ( n= §) : Expected Output : (11, 2:4,
4:18, 5:28)