You are on page 1of 356
Choa Sheet Jing with Python Intro to Program Software Programming code The steton hat we wie to crest sofware ales Code Syntax Simla Grammar ues in English Hind, ead programming language has unique sto ules. These ules ate aed the Syntax of» Programming angusse Why Python rage Weh Pinon, ts posto ceate programs nth minimal amount of cade, Look atthe cadena and Python used for printing he massage “Helle Werld Java: Python: Applications of Python rea intligance AD Machine Leasing Oy smart Devcevntemet of Tings aT) Cyber Seurty Backend Development te non developers have plenty of opporunies sss the wo Sofware Developer Machine Leaming Ml Engineer + Alscont te. Hello World Program in Python eres simple Pytion code hat you can us to spy the message “Hello World ouput Posse mistakes you may make while wring Python code to spay the message Helo Wold Printing Without Quotes ouput ouput Calculations with python Addition + sign, It gives the sum of two numbers. ‘ouput Subtraction sign. It gives the difference between two numbers Multiplication is denote by sign, ouput Division 1 sign. Submit Feedback Intoiton ion» Vaile and ta Types | Chet Sheet Choa Sheet Variables and Data Types Variables ‘orbs are ce contains for storing value, Values consider tha vale ar he containers for storing information. Data Type Inprogramining ingusges every vali or dts han aesocatd ype titan a dt Some common) ued data ypes + sng + Ineger + fost + Booesn ‘his data ype detemines how the vale or daa can be used in the progam Fr examale, mathematical operations ca be done on Integer and eat iypes af ata su Asting ea steam of characters anclsed within quotes ‘Sue of Charactrs + Copia tater (A=2) + Soa eters (9-2) + Digis(0-8) + Speci characters 1 #523 + Sesce Some Eames + Hel won + ‘somedienanslacon” Integer Allwhole numbers postive negative snd sao} without any aconal par come unser Integers amples B2.01.23, Float Ay ube ith dc pont 245, 545.210, 52185 lean Ina general sense anjthng tat can take one of se posible values is coniered a Bookon Examlesineide he data that can take ales ke + Wusorfase + YerorNe + nero te As perthe Python Sta ‘ine and. filzo are considered as Boolean values, Notice that both start with a capita letter “The flowing the sya for aesgning an integer value 10 toavatiable age sign is called as Assignment Operator as its used to assign valves to variables. Submit Feedback Choa Shot Sequence of Instructions Program Defining a Variable code code ouput Ifyou intend opin vl, dono ncoge he vale in quotes. Order of instructions code age is not created by the time we tried to print. arable Assignment Examples of Variable Assignment Expression An expression a vid combination of values, variables and operators. examples Bopmas The standard onder of evahting an expression + Brackets (8) + orders (0) + buision 0) + Matiptetion + Addin + subtaction Step by Step Explanation Grarers 29) + «ay code © waned as compet: Submit Feedback Choa Sheet Inputs and Outputs Basics ‘Take Input From User pwd allows flexibility to take the input from the user. Reads a line of input as a string, code oupet Working with Strings Sting Concatenation ‘concatenation Errors an only conesterate str (not “int") to st Sting Repetition + operators used f¢ for repeating string J any number of tim f times as required. Length of ting feng returns the number of characters in a given string, code oupet String Indexing ie can access an indivi hacer in sing ving the postions hich ta fom Pearce ee code —_— enc Submit Feedback Choa Sheet ‘Type Conversion Sting Slicing Obtaining» par ofa sing ie ale srg code + erd.inder is ntincudedin these code fend indie not specie sing stops at the ene of he sting, Irsamindoxis not speci ling tnt fom the index code Checking Data Type Printing Data Type ‘Type Conversion Comerting the vale of ane data pe to another datatypes called The Conversion or Type Coting + Seng to neger + Floto sting and soon String to Integer 19 converts valid data of any type to integer code Anvelia Literal for int() with base 10: ‘5.6 Ineo tSng sed converts data of any ype toa string Input ouput ‘Summary 1 i) > Camere integer dat pe 2, Boat) = Conversa fat dn ype 5. seg) > Coowersto ating a pe 4, tel) Conse totes at yp Submit Feedback Choa Sheet Relational Operators ‘ue oF fale as the result of a comparison, y I greater than < le tese than Isequlto Ieee than orequalto g Is greterthan requ t> iS Ist equal to code Mistake -2 is not valid in Python. Comparing Numbers Comparing negers and oats ode ouput x (Capital letter) and x (small letter) are not the same in Python. Stings and Equality Operator heat Sheet Logical Operators Te oF fake as the result Logical AND Operator we ifboth the booleans are true else, it gives Fate Step by Step planation @ 3) a 2) True and (2-¢ 2) Logical OR Operator ue ifany one of the booleans is tue els, it gives rae Step by Step planation ener acy Tue or (2 ¢3) Logical NOT Operator Examples of Logical NOT rotta <3) rorcrree) ‘Submit Foodback ‘penton & Conon Siemens» Conon Samet | Che Shee. Cheat Shot Conditional Statements Block of Code A sequence ofintutons a cal block of cose, Python exacutes codeine sequence, the condition is False code Possible Mistakes in fee code output yd © sarkevas compere: Submit Feedback Cheat Set More Arithmetic Operators Modulus * oe Exponent cose ‘Swbmit Feedback Choa Set Nested Conditional Statements Nested Conditions if condition B: ' 1 | Block 2 —> Nested Conditional Block Block 3 I Block 4 _ output ouput Nested Condition in lee Block Inthe belw example Blok 2s nested conditional block if condition A: | Block 1 else: oe | if condition B: ' Block 2 output Elif Statement Use the elf statement to have mil condition statements between if ane, The ef statements options if condition A: elif condition B: else: Multiple Elf Statements We ean ad ay number of cit statements after conditional block, if condition A: elif condition B: elif condition C: else: Execution of Elf Statement Python wl execute thea block who expstonevlates to tre Haile cit conditions are true, then only the first elif block which is True will be executed. if condition A: elif condition B: elif condition C: else: Optional Else Statement lee satemantis not compubor ster alt statements. if condition A: Block 1 elif condition B: Block 2 elif condition C: Block 3 Ean ouput Divisible by 5 cannot we anal statment afer ke statement. if condition A: elif condition B: © sunxeDasconmiete Submit Feedbeck Chest Shot Loops So far we have seen that Python execatescodeln a Sequence and each lack of cde i executed once Loops allow us to execute a block of code several times. While Loop ‘lows ut to erecte lack of code several tina a lang a the condition i Ape N ZU + while termination_condition: r I ' Lock of Code 1 1 , lie The following code snippet prints he net thre consecutive umber tera given numba. Possible Mistakes, 1. Missing initialization code 2. Incorrect Termination Condition code Inpes ouput The above code rane into infet oop. ‘he block wil ieep repeating asthe vain contin variables 3. Not Updating Counter Variable De Inpet ouput Submit Feedback oop For Loop Chet bet Choa Sheet For Loop ‘or statement iterates over each item of a sequence -» for each_item in sequence: 1 Loe Examples of sequences code Range Sonertes sequence fingers artng fom 0. angen) Stops before n (nis not included), ouput “Generates 3 eaquenes of numbers string fom Syntax: rengeitan, end) Stops before ena (end is not included). Submit Feedback Loop» Approach fr allow putes [Chest test Approach for Hollow pattem |Cheat Sheet. [Approach for Hollow pattern problem Inthi chest sheet let's hove to int he Hollow ght-angled rng ptr slow the pater ofthe Holo right-angled angle Now, lets 08 how to prin the 77 holo ight-angled range pattern Inthe above image, ech empty box contains 2 pace Soule space 9, an each saris llomed by 3 space ¢* + While wing the code, © you noesta print 96" flowed by space © younsed to pit 2 sacest 1 inplace ofa single space 1+ esecond vow has S spaces and the fst tar and the second te ‘+ The hi, fou), th. ana sith rons have dering spaces, floes bythe fst str wth increasing hollow pace. then he saan te Here inthis problem 1+ soace is denoted athe "(Double Spaces 4 sar set denoted a theta folowed by space! Lees now sess Ine by ne Frattne 6 Double spaces taster ” Second ine SDouble spaces tats") 2nd ar o Thine Double spaces Tetmarset) Hallow apscas 2nd ar oa Fourth fre Doublespaces set starset™) 2 Hollow spaces 2nd star soe Fivine —2Doublespaces atte") Hollow paces 2nd star . . Sith Ing 1Doublaspaces = atatarettr) A Hollow spaces 2nd star . Seventh Ine ODoubla spaces Tess") + We an dvide the above patter logic into 3 pars 1 Part we have spaces and star") in isting © Par2:we have spaces, star, hollow spaces, star idle nes) © Parcs we have star set(’*") in thelastne _ = Now se he explanation othe for loop ection, step by sep Part fst tn oupatis art -2 (oie to print he Second ln to Sixth in 1 value fromthe value. spacers (EIS seen CD) Ae ouputis Inet rom, we have space fllwed by the fie star ne low spaces follows bythe scond str. In der to get 4 nf spaces we must ub and 1 value fromthe value. spaces = 8 (WL) 8 meapeces (1 (4-04 ies Inthe fourth ow, we have 3 spaces flowed bythe fist tar and hallow saces followed by the Second tar. horde o get 3 nat Spaces, we must subuac and i value fromthe value. spoces = Ea) 2a hotiow.ssaces = (°° * (4-2) ouputis Ine th row we hve 2 spaces followed by he st star an hall spaes fle bythe scone star. In ordorto get? oof spaces, we must sure and value fromthe value. spaces Wa) = 2 hotlowspaces = (°° * (1 = 2)) 23 Inthe shh row we have space olowed by the fst tat and hallow paces followed by the Second ta In ode age space, we must subtact 1 and i value fromthe N- value. spoces EI) FT hotbowspaces = (0 (1 = ay) 8 ouputis st Seventh ine ins ouputis ‘Submit Fedak Choa Sheet Extended Slicing and String Methods 142=3 34255 54257 Methods They simply the mest common pefomed operations a: 1g Methods + igo + stip + tower) + oppor + sanity + edwin syne stcacisaigita ‘we ifall the characters are digits. Otherwise, fee sep Removes athe edn an aling spaces om: ourpet Wie canals spectycharactes that ee tebe removed OO Removes al spaces com ane fl stot} hat ead or vall testing the cat and tne dog Sy scnatsithiaie) ‘ue if the string starts with the specified value. Otherwise, rate we ifthe string ends with the specified value. Otherwise, Fase code Upper stevacupper ‘Gives ane tring by contening each character ofthe given string to uppers, code Ges sno sing by converting character of the given sting tolowercase Submit Feedback Choa Sheet Nested Loops The Inner Loop wil be exested for ach tartion ofthe Outer Loop. 1>for item in sequence A: ==>» Outer Loop 1 | Block 1 | ' ' >for item in sequence Bim} Inner Loop ; I< | Block 2 1 tn ' | Block 3 Nested Repeating Block ‘The ne highlighted inthe ble dotted ine he repeating block of ——> Outer Loop n_ sequence B: i! Inner Loop Block 2 co i? | Repeating Block Block 3 Block 4 Inthe above example, the below tn ith epeting block of the nstd loop, ouput Examples - Nested Loops Example - 1: While bop inside sor eop > for item in ® while condition: Example - 2: iil bop inside awhile loop ‘> while condition: Pm while condition: 1 ‘Block 2 Submit Feedback oop Cone Steen oop Con Steen |e Sheet Choa Sheet Loop Control Statements contol state ns aor the seovential erection af progr. vamples + itelitelse + while, for + break, continue Break Break statement makes he program exit loop «a while condition Using Break Generaly, oreakis used to ext oop when a condionis suse. for item in Sequence: value equals to 2 the break statement gets executed and stops the execution of the loop further Breakin Nested Lop Breakin inner loop tas the exciton of te nme lop. + for item in Sequence A: Continue Contin makes the program skip the ering sateen inthe cureteation and beg the nt teaton ~» while condition A:<-- continue General, continues used to sip remaining Satemansin the tet teaion whan cond i sts -» for item in Sequence: ¢, if condition: continue e- Inthe below exape,when the varable value equals to 3 the next statements in the loop body are skipped. ourpet Pass Pass statements used as» syntactic placeholder When tis execute, noting happens. ‘Generally ved when we hiv to tet the code belore wing the complete cde, if condition A: elif condition B: pass else: Empty Loops Wie can we pas statements to tet code writen sf, before wing op logic while condition A: for item in Sequence: pass pass Submit Feedback Choa Sheet Comparing Strings Every charctr he unique Unicode vale "AN "on Unicode - 65. Unicode - 122 qn ny Unicode - 49 Unicode - 42 ord ont cxdcharscte) gives unicode value of the character. To fins the character wth the given Unicode vale we se the Cévlunicoe)_ gives character with the unicode value, Unicode Ranges 48-57 > NemberDighs 03) ‘est > Spec Characters Ober Languages Printing Characters a toz Comparing Stings As nicode vale of | is 65and & is 66,which internally compares 6s <6 . So the output should be we character by Character Comparison, InPthon Sting Comparisn i done character by characte. code se code Best Practices + copia Levers(A-Z1 + Sal eters (2-2) + ips 0-9) + underscore) examples ge ot bil Naming Variables Rule #2 + Commas.) Cleesne rate) ‘aril name must begin with + copia tenes (AZ) + Sma letters (22) + Underscoret_) “Cannot ute Keywords hich ate erewed for speci meaning Keywords ourpet fire 48 2 2ist of the Python kenwords, Enter ny keyword to ant sore tel. True centinue gio pass —peeperser_ der " raise od aa sngort return a aur in ty syne acest tameda sen await finaly onlocal yield case Styles + pascal ate: Total + Soake cate: total Snake ee i prefered for naming the varelesinPshon Submit Feedback Choa Sheet Round Rounding Numbers inomber dighsoptonal Rounds the float value to the given number of decimal digits. agit -> define the number of decimal digits to be considered for rounding, oupet Floating Point Approximation Flot vals ae stored appronimatey printto.t + 0.2) Floating Point rors code Comments Submit Feedback Choa Sheet Floor Division Operator To fn intra part of quotlent we ue Flor Dison pertor + ano ‘Compound Assignment Operators a += 1 | Compound Assignment Operator Difeent compound assignment operator are Ly me sect issimilarto s-a47 code Examples of Compound Assignment Operators Escape Characters, Single And Double Quotes ouput code ouput Escape Characters Wie got anew dng \y_ escape character. Escape Characters tar ith bach in Python +) = Ta Space oA asec + = Sine ore + > Double quote Pasng Stings With Quotes The bacieh \ character here tells Python not to consider the next character as the ending of the string ouput Cheat Set Data Structures ata Suctues low sto store and organi dt ecient: Ths willow uso easly acess pd perorm operations onthe dit In Fyhon thre te our bulin dats structures + Tole + set + Dictionary ust List inthe most ete python data structure Creating as ‘rates by enclosing elemenss within quae] bakes. sch tem is separated bya comina, a, (5) °Sie, 2, 8.21 ode + operator concatenates lists. ouput Adding rams to Uist rere) 1, 2. 3] ‘Operator repeats lists. code te 2s Ye 2s Ye 2) Ctsning apart of at ale it Sting 5, ste] exended hang ing eended i's v0 lnaquene)_ lakes a sequence and converts it into lst. + Unecan be mode 31 2s 25 3, 4] Strings ate immutable Sings are nmaable a coe Typeterors “ete? obgect does not support Sten assignment © MARKED As COMPLETE ‘Submit Feedback se Wooing with Li [Cet Shee (Choa Set Working with Lists Object Inger anything that cn be atgnd os visable in Ph ard to at an obec Stings teers Feat Lit tee objets Semple os wa35 +123) Identity of an Object \Wenever an obec stated in Python, il be given 3 unique enter “This unique can be tere foreach ine your the program. Every cect tal you we in a Python Program wil be stored in Computer Memory. ‘The unique id willbe raltd othe loation where the obec s tren the Computer Memory nan Id - 140035229724336 Id - 139630925071104 Finding ss0 to find the id of a object code EE ‘ouput Modifying Liss Modiying tet -1 tas and tis will be referring to the same object. ouput Modifying Usts-2 won assigned an oiting Ht oth the variables Ita and tic» will be referring to the same object. list a: 16, 71 Lest bs (4, 2] code ouput art 2671 Mise: 1, 2, 6, 71 Lponting mabe obec wil ale eect he vale nse it. a he rafrence change, Baa ouput (2) 21 Submit Feedhack Choa Shost Usts and Strings spliting Spl singin ast at every spaces spat Ifo seprtoris peti eau separators whitespace rr, aay tiple whitespace are considera a gle whan song |v and tab space \\_ are also whitespa Bxonple-t re, Space a8 Separator Te String as Separator code ouput rpytnen 15° proge’s “mmtng 1°. "neu", "ae" example -2 [roy aye execution of code") ‘Beas lhe ams ina Sequence of stings ad jis therm nt one sg Dythan is 2 programing lngtage Negative Indexing sing a negate index cet the nth ten ron the en oft. list_a[-1] <1 for step will reverse the order of items in thelist Vist.a[=3:-1) 4,3 5 1 Lo-4---te <5 3, = = -4 code 43 Negative Step Size vaableta Bxonple-1 Ba xomple 2 ouput 1 for step will reverse the order of items it ouput 1 for step will reverse the order of the characters code Indesing& Slicing - Stings string_1[-1] ‘piprlo!giriaim! ~-t.-J---L.-4..-0a Le “7 -6 -5 -4 -3 -2 -1 ouput example 2 ‘Subot Feedback heat Sheet Functions Reusable Block of Code Input Reusable Block of Code Tea The functional lk oc exc any whan the function alld def function_name( Tele ese rane at tine 2in place of the > es Desired output fr hese pes of scenarios def function_name(args): Reusable Block of Code ses fncon cin one ued nt Returing Value resun keyword def function_name(args): Reusable Block of Code return value ‘eun statement will not be executed, tes tte Teja Buti Functions We ae steady ng incon which re pre-defined in Python Buln func re rly aval for ee Choa Sheet Function Arguments def function_name(arg_1, arg_2): Reusable Block of Code Keyword Arguments Code oupet code ourpet Typeteror: greet() alssing 1 required positional argument: “area Positional Arguments ‘oles cn be pasted thou wig argu name, + order ofthe arguments mates here oo Horning Posible Misses -Poskonsl Arguments Mistake -1 Input Ieee eee eta etic ete erat eee ee Mistake -2 Tpetcror: greet() missing 2 required positional argunents| Defale values example -2 Tejs Teja rample-5 Non-setulaguments cann follow et arguments Teja Passing immutable Objects Even though var names are same, thy at fering tot erento Changing the value of th ribs he freon wil ot fet he vale outs, Submit Feedback. Choa Sheet Passing Mutable Objects se and tnx Peete] the function is died, not each tne the funcional Det age are evaluated on once wh code Perret 31 331 Built-in functions Buin functions are eal vale or ese arses ucng functions which re pea-tne in thon oo) ‘xing returns the smallest item in a sequence or smallest of two or more arguments. vample-1 code rin, 2) +P sotunode) code sox) returns the largest item in a sequence or largest of two or more argume! ‘vample-1 ouput Finding Sum sumjeequence)_ returns sum of items in a sequence, Ordering Uist tems soredueguencs) returns a new sequence with all the items in the given sequence ordered in increasing order. evurseTua)_ returns a new sequence with all the items in the given sequence ordered in decreasing order. 64 Bey 3, 26 1D Submit Feedback Choa Set Function Call Stack & Recursion sack Stace dt tacts tat tres tes in an Lak IFst-Ovt manne Calling a Function cating funcion.19 inside funcion 20 def function_1(): def function_2(): oupt Inthe above code cling fnctins are feng and maxd inside getargest.sa0 Sum of Squaca of List ems get_sum_of_sqrs([1,2,3]) code Function Call Stack Recursion function cling tet icles» Recursion def function_1(): Lats understand recon witha sinole example of muliping N nombers MuhiplyN Numbers output © anceps compere ‘Submit Feedback (Choa Set List Methods Ayton provides Ist methods hat allow us to wotk with st eam fe among them + append + extend + pop + deo + removed + son + index Istappendivalee) Adds an element to the end of the list, output ‘ouput 1 23, 5 6 Fexneertindexsaue) Element is inserted to the list at specified index code ouput i231 ep ixpopp Removes last element. code output Lecromovetaha) Removes the first matching element from the list. code output lee tsxdeang Removes all the items from the list. ouput u Isundeaue) Returns the index at the first occurrence of the specified value oupt count lexcounthatu) Retus the number of elements with the specified value. lesson Sorts the list. ouput sor Modifies the list code ouput sored Creates a new sorted list code ‘ouput a7 ‘Submit Pedbock. Tope Set > Taps a Sequcees Cet het Cheat Set Tuples and Sequences None None is an object which isa datatype of its own (NoneType) Function Without Return ‘ety statement, the variable will get the value None Function That Retums Nothing example 2 output Tuple 1+ Holi an ordre sequence of tens 1+ Crests by encosing lemons ihn found) Brackets, + Each tem sseparated by aconma eee) G ste, 2, 2.2) ‘Accetng Tope elements i ako snub sting nd et cessing an aig, coe + tend + eting Converting to Tuple twplosaquance) Takes a sequence and converts it into tuple Stung to Tople 23) Sequence to Tple 4203) Membership Check f ven data eben prof sequence ot example coe example-2 coe Packing & Unpacking Unpacking Number of variables inthe eft should match the length of squnce Errors in Unpacking Valuetrror: to nay values to unpack (expected 2) valuetrror: not enough values to unpack (expe ‘Tuple Packing 0 brackets are optional while creating tuples. G23) Choa Sheet Sets Unoxdered calletion often + Unique ne dutta) + Mustbemtble creating a Set + Crests by encasing slements win curt brackets + ach tem separated by 3 comma, oupet 0.2, 2, ‘six’, 5) No Duplicate tems code opt eee Immutable tems Setzems must be imme Creating Empty Set set) to create an empty set. code set) converting to Set sevsequonce)_ takes any sequence as argument and converts to set, avoiding duplicates code = a2 string to Set OV pi te aD Tupleto set an Accessing Items As sts ate unoedate, we cannot accessor change ante of Typeteror: ‘set object 1s not subseripeable ‘Adling tems setaddatue) adds the item to the set, ifthe item is not present already. 122,367, 9) ‘Adding Multiple tems setupdsteaquence) adds multiple items to the set, and duplicates are avoided. code 2139) Removing Specific tem setsscardialu) takes a single value and removes if present. code ouput setsremouehaln) takes a value and remove if it present of raise an erro, Operations on Sets Submit Feedback Choa Sheet Set Operations CH) Union @) Difference CH Intersection @p Symmetric Difference Union Union afta sets i st containing lllement of both set. Sela [seb OF seLaunionsecuence) soiong converts sequence to a set, and performs the union. Code ouput ouput Intersection Interecon of wo see is containing common element of bot ste Seta BSED OF seLaintesectonsequence) iveseciong) converts sequence to a set, and perform the intersection. co ouput 2) code 2 Difference Difleence of wo sts ia et containing alte lenient ine est set but ot secon set_a - set_b converts sequence to a set. aa {8, 4} oa Symmetric Difference synmette ference) converts sequence to a set. oupet oupet Set Comparisons + superset + iin Subset set_1 = {1, 2, 4} set-2 = {2 2} sewisutselsett) Returns nue if all elements of second set are in first set Else, fake ‘xample-1 code ouput True set_1 set? fa" 4g Sy ST {'a', 1} (>) set_1 = {4, 6} = {2, 6} w @ o I ho " code Superset set_1l = {1, 2, 4} set_2 = {1, 2} ‘ettisnperetiet) Returns Tue if all elements of second set are in first set. Else, fee setic={'a', id, 8, SF set_2 = {'a', 1} True comple -2 eC) set_1 = {4, 6} set_2 = {2, 6} ouput Disoint Sets settisdjoinuset2) Returns tue when they have no common elements. Else, rate Submit Feedback Choa Sheet Nested Lists & String Formatting Nested List ‘Accessing Nested List 5 "Six" [s, 6] 8.2 ° 1) 2 im 8 6 Q 1 NXT wiv 208 61 ‘Accessing ems of Nested Us ouput code String Formatting code acl Sting fematting simplifies this constenation nereass the eadbity of code and type conversions not required [Add Placeholders string needs to be formatted. ee errr en Numbering Placeholders Numbring phiceholders wl vale ccorsing to the poston of arguments se HL 20, You are faju years old Naming Placeholder Code ayy | i eat Sst Dictionaries cy stony toi Key-vale pit nxt wave 4 Creating a Dictionary rested by encoun en win (curl brackets Se (Crane's "Tela" "2g0' 28) Immutable Keys Creating Empty Dictionary ‘Accessing ems 11 alongwith the key to obtain its value [Accessing ems - Get get) method returns None ifthe key is nt found, 1b tovaccess the key-value, KeyErrris raised in case a key is not found in the dictionary, ewe ete squice bakes (|, Kefror iersdincce key ieotoundinth dctonay. On the aterhan the ge mathoetune None the key i Operations on Dictionaries + ating akeyele pa CCnane's Tea Saget 18, Sehty's “Go8") Mostying Exiting tem As dicinars ar male, wean al th ales ofthe hye {noness “Tesars “ages 26) Claes Ome [Ch St Choa Shost Classes and Objects (dot) character. Wecan ao access ané update properisin ota methods ———— i ii Ils tecommanded to upcate struts tough methods Modeling class + date quantity fa ter ereeeceeetes cents perio pire amore [ree noduton Obj Orel Pogranming> Ate and Mths | Chat Stet Choa Sheet Attributes & Methods + Uses can ald ferent esto shopping cat and checkout + Thetotalvaie of the at should be mare thn 3 minimum sount 100): forthe checkout + Duing Ofer Sales, ll users get at diszount on tar at ad the minima cart vale il be RS. 20 rosy atibutes can be ateporizd 9 + Instance aster + chase atebutes items min_bill Attributes flat_discount ‘and more. wr \ wave 20% Instance Atibter _Aruibtes whote vl cadre ach tance of cl are mde a inetance atte. = Cart Object -A Cart Object - B NXT. Wave 2 vibes whose values stay commen for athe objec are modeled as Cs Abts. |e Minin Co Bi FHatoiscount Instance 5 = . cenes Attribute | "ems min_bill min_bill |, Class Attrit flat_discount flat_discount PaO wr | 4d wave 4: Accessing instance Aber Instance atts con ony be accessed using insace of as selt sell_ passed to method contains the abject, which is an instance of class. oe Accessing Using Sal Pee reece ere) earn ment ee eee) oer) pear entero) 4 5 Perens) 5 coe coer) » Accessing Using Css prverrrronireestrret Actributednror: type object “Cart” has no attribute “Aten Accessing Clas Abutes ode code Updating lass ateibte Motoa Bondy methods canbe categories at + clase Methoos items min_bill flat_discount add_item() display_items() Methods update_flat_discount( ) NXT pA wave 40% Instance Mathode Instance methods can acces ll trbutes ofthe Instance an haves as parameter, items min_bill flat_discount add_item(self) Instance display_items(self) Methods update _flat_discount( ) xomple code peers » rece preety, book" 3) yh Cas Maths. Mathods which eed aces to cls trues but ntinstanc tbe cha a parameter indicating we are passing the class items min_bill flat_discount add_item(seLf) Class update flat_discount(CLS) Method NXT wave echsmmetnos decorator marks the method below it as a class method. Accessing Clase Method Sate Motos ‘Wie might eel ome generic msthogs hat dont need acest ther instance orcs tibstes. These ype of methods ae called Static Methods. Usual, stati methods ar set reat uly unetions whch make more senso be parte cass Cexstinethos decorator marks the method below it as a static method. Wi wales more abou decorators in upcoming sessions. items min_bill flat_discount add_item(selt) update flat-discount( Pye Sandi Lira [Chee Sst Choa Sheet ‘Standard Library Builtin Functions ‘iin functions are Realy aval for ruse Some ofthe bik Functions are 1 pia 2 max a) 4 tad) andmary moe Standard Library Python provides sever such set values conan, sss an fanctons “iscolestonofpedeSnes tes refered sethe Python Standard Library ‘i these onctonies ae gai int dren modes + Intron content any fle conaning a Python code scaled » module + These modules se further organized inte fers own ss packages Dieent modules ae Working with Standsed Library Math Module math madi provides us to acess sme common math fancions al constant Variable / Function / Class defined in the module math. factorial(5) Module Name Nxt pa wWAVG oo. Importing 2 module nd ging new nme ing code Wie can moor just spect dfinitin fom 3 module, code Alsing Imports oupet Random module Aanomessis taht n whenever rca ee For example: ling» de taping 2 coin ee, andom module provides us utilities to create randomness. ‘andintd_is 2 function in random module which returns a random integer in the given interval code Baal is a function in random module which returns a random element from the sequence. ouput To know more sbout Python Standard Library, 90 though the authentic python documentation tpi Hdocepython org ivy! Map, Filter and Reduce Win word th ferent sequence i ps. ‘Empl working wth sguencs we cn se sas), ther) and reduced functions. Map ‘map applies a given function to each item of a sequence (lst, tuple etc) and returms a sequence of the results. 1/2/3)4 1/2,/,3)4 1/2/3)4 1)/2/)3)/4 Square(1) ——s Square(2) — Square(3) i Square(4) —_—— 1 a 1 9 i 9 | 16 Sie adh code 1, 2,3, 41 Fier ‘vod method filters the elements of a given sequence based on the result of given function, The fection should tur ree Elements of Sequence is_positive_number(num) Filtered Results (Positive Numbers) mie wave 208 oupet ie 31 Reduce ‘edueey function is defined in the functools module. 1)/2)3/4 Nxt ga wave 20: Submit Feedback Choa Sheet ‘Scope & Namespaces ‘Object Ingerarat anything that ca be signed to warabinPyton refered to aban object. ‘Sings, tears, oats, Lists, Functions Module a are alobjec Identity ofan Object \inenceeran objects rested in Python, it willb given unique identifier (id). Ts unique an beet foreach me you run the program man Id - 140035229724336 Id - 139630925071104 NXT wave #5 hat you usin Python Program wl be sored in Computer Memory bo rbd tothe leation where the objet ie sored inthe Computer Memory, Name of an Object Name or Identifier i spy» ame gion ton objet a a = "Hello" L b = “World” "Hello" Id - 140589619285168 Namespaces Amamespace colton of cunentl defined names alongwith fonation about the objec hatte name ferences Teersues at names ae nique and wont ead te ay conte b L "World" Id - 140589619285182 NXT wy wave #0 "Hello" ~ "World" Id - 140589419285168 Id - 140589419285182 Namespaces ow usta have the same nae refering ferent things in dfferent namespaces, Namespace Namespace a b Cc N "Guys" "Hello" "World" "Hey" wr x wave 4 ouput Helle ‘Types of namespaces As Python executes a program creates namespace 36 necessity and forgets them when they reno longer needed. Diferentramespaces are Buin Namespace ‘rete when we at executing Python program ane exis longa the program sunning “hiss the eason that bullsin functions ke, Int) et are abnys avaable tous om ay par ofthe program, _loba Namespace ‘Tis namespace nudes sl names defined clin s module ouside ofall retort iis crested when the mod loaded, andit ats wt the program end NXT wava 40 Local Namespace Modules ean have vious functions and classes ‘Anew loca namespace is cteted when uncon scaled whic ists utl he function tus nxt wave 20% ‘Scope of a Name ‘he scope of a names the region ofa progtam in which that ame has meaning, Python etches fos mane ro the nse ou ooking inthe Built-In Namespace NXT wAVa local, slotal , and finaly the built-in namespaces Global variables Inrthon a varale defined outs ofl function iknow a8 global variable ‘hievarble name wl be pat of Global Namespace, sample code def foo(): ocal Variable" foo() print(x) Scope of x nage 4 53 wAVva oo is not declared before assignment, python throws an error. Local Vrsbles & Global Varibles slobal_ keyword is used to define a name to refer to the value in Global Namespace, Submit Feedback Choa Shost Errors & Exceptions Syntax Erors| harngt Python Syntax. prt of cade nt sed greet function, which is not used in rest of the code. Exceptions ven when a statement or eession syntactically correct may caus ror cetected ding execution ale exceptions ample Sanaio + We donothave space fon the device to download the video Divison ample code Zereosvistonerror: division by zero code ouput “ypetorors uarupporteg operand sype(s) for J: ‘ett! and ‘ate omsidrthe folowing code, whichs edt update the quantity fiers instore senate) Working With Exceptions ‘The application/program crashes. en you develop sppeatone tht are dialyzed by enurrs you needs handle diferent possible exceptions in your code so ths the appation win at, Wien you develop mses that re sa by the developers you shoul alse exceptions for teen scanaiog that the devlpers can handle hen Money Transfer App Scenario Develop a Class Use Bank Account class to model Bank Account _to implement Money Transfer = romples Balance 250/- Balance 100/- transfer_amount(user_1, user_2, 50) Balance 200/- Balance 1 50/- wavs 2 ea ee cee ey errno) veer) emer) ance) rs) sy ers) Balance 25/- Balance 1 00/- transfer_amount(user_1, user_2, 50) x] Balance 25/- Balance 150/- Penny ree ares ee eee ten peer) aout eeeetarn) aurea) nt cae eee eee) nt canny eee Pee) ee eee eee a) nee weeny) oan eee reaereeey)) User 2 Solance: 350/ Raising Exceptions NXT. wave 408 Buin Exceptions Diteren exception classes which are aedin dierent scenarios —> ZeroDivisionError — >» KeyError — > §0OFError — >» Exception —> TypeError —- OSError — ValueError — > = ArithmeticError and many more. uC A argument Balance 25ie Balance 100/- transfer_amount(user_1, user_2, 50) Insufficient Funds ; A eee es peers eet} oa eeeeere eer) femeetrny a arene eater ouput User a salance: 25/~ Handling Exceptions Python proves 9 may to each the exceptions are aed So hat they canbe propery hand + aceon canbe handle with ry-exeept lock + Whenever an escopton osu st meinen yb the escaton pa ths ne an jump capt ace Taster moun Balance 25/- Balance 100/- transfer_amount(user_1, user_2, 50) 0 Balance 25/- Balance 100/- mt ga wave 20 reenter ee eee een Tepe ery praesent wey (200) cae nee etary) eee ceny)) Serre eet) nee wearer) pay oe ireetionty)) Reusable Modules End-User Applications Handling Speci Exceptions iecanspeciialy menion he name of exception to atch l excepts ofthat spece ype example object Taper) ara reerey) praetor) eur weneetra) eer ener rts) nt cane eree eee creyy) nt peer ene remarry) Cee eee YY me cert ery) nt een ene ee eS) Handling Multiple Exceptions \iocan rts multiple exception black ohana deren toes of exceptions feet ‘Sob Feedback Choa Sheet Working With Dates & Times Datetime Python hs builtin datetime module which provides convenient objects to work with dates ad nas. Datetime classes Commonly used elassesin the dtetine module we: + dre ce + daretine case Working with date’ cass _Acate object canbe used torrent any valid ate ies month and day code ouput code Todays Date ‘ody returns a date object with today’s date code rene _Aruibutes of Date Object Working with time’ Class Representing Time code ouput ‘Working with ‘datetime’ class ‘The dtetime cles eprasets vale date and time together ‘vample-1 mero) earns) ans ts) (catetine_onject) code ere Formatting Datetime stetimeormay) method to format the datetime into any required format like + mild Year without century ta aeropaded decimal mambet 13,20, xv ‘Yesrith century 6.2 decal number 2019, 2000, xe Month a fl nme January February oy ‘Monmhas a 2ero-paded decimal number 01,02 12 wa Day ofthe month ga zere-pced decimal umber 01.02 3 Ea Weekday a abbrevited name Sin Mon, a Wook a fll mae Sunday, Mendy oH our 8-nour clock) a. zere-pacied decal number 00,05 23 ” our (2-nour coc) a zere-paied decal number 01,02 0.12 ot Minute 3 rrp decimal number 00,01, 058 xs Seconda» et-paed decimal number 00.01, 59 ode Parsing Datetime ‘eptimeg creates a datetime object from a given string representing date and time, ‘Working with timedelta’ Class “Timedely bject epesens duration. code fxample2 Submit Feedback

You might also like