0% found this document useful (0 votes)
5K views100 pages

Python Quantum Latest 2023-24

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
0% found this document useful (0 votes)
5K views100 pages

Python Quantum Latest 2023-24

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
2019-20 + 2020-21 + 2021-22 * 2022-23 ter Cer pee rfc otte Farad oe Weft eit, georrerit, atten I 1 oe wa qe eager ele he repftay oer STAT THT OTT fede 3 feet ot aertiy eat araTera secrrraisil a foros aaten fot urge: rerits Utes aie ara, HEA (ahi) a APRRAT TS Fev G1 23 Fee, zy q sierra Aart @ fir aan ie fftage secier & TAT & sit ett + cafes fafsra tial» saiem Geral wi sector wfc a eer AT care Fran aren eH eC erat (a ae I aT ere a 3) aaa MT ating ae, Shin, GTEC, ferret 3k Ferre aw aaten gers Sa fared A orga seein a secterractsH ae aaien a ude fafade ore Start site ongaties arlene Ts a areh fences ene nec eee eee ey QUANTUM SERIES Pradesh Technicdl University) Python Programming By ‘ Ritika’ Bhardwaj VATS Att ancr eo" DEPOT 1 Maan Kony my » Mob No-08073 e569” Quantum — Page — QUANTUM PAGE PVT. LTD. Ghaziabad @ New Delhi a 2 uantum Publication: Fr a we tea) ‘Sahibabad, Ghaziabad- PUBLISHED BY? (© Quasrun Pace Pur LaD, No part ofthis publication may by produced oF in amy form orb : ‘Au. Ricus Reseavep Trlonnaton contained is Wark bs derived from sous {cheval be reliable Every effort has een made ® ensure iceuney, however neither tbe publisher nor the aihors Jrovantethe acuraey or completes ofan iormation ished herd anl either he publisher not the authors Spal be pond for any eres, omieions, oF damages aig out of use of ths information. Python Programming (Common to All Branches: Sem-3 & 4) 1 Edition : 2019-20 ee 3% Edition ; 2022-23 4° Edition : 2029-24 (Thoroughly Revised Edition) Printed at: Narula Printers, Delhi Esa CONTENTS ——- a BCC302/ BCC402: Python Programming UNIT! : INTRODUCTION To PYTHON (-1'V to 1-23) Python v. 1on basic Operators) Understanding python blocks. Python Data Types, Declaring and using, Numeric data types: int, float ete. r UNIT-2 : PYTHON PROGRAM FLOW CONTROL CONDITIONAL BLOCKS ; Python Program Flow Control Cond and el oop using ranges, ° oops in Python, Loop Pass, continue, break. and’ else. ional and loop blocks. UNIT : PYTHON COMPLEX DATA TYPES >>" (3-1 V to 3-39) {Using string datatype and string operations, Defining list slicing, Use of Tuple data type. String, List and Di Manipulations Building blocks of Python progra manipulation methods, List manipul. tion, Programming using string, list and dictionary {in-built functions. Python Functions, Organizing Python codes using functions. UNIT-4 : PYTHON FILE OPERATIONS (41V to 4-201) Reading files, Writing files in python, Understanding read functions, read(), readline(), readlines(). Understanding write functions, write() and writelines() Manipulating file pointer using seek Programming, using file operations. pit Ln PON MCHA cn rea Ep rag Go oe Python programming with IDE. (SQ-1V to SQ-31 yy ‘SHORT QUESTIONS ¥ SOLVED PAPERS (2019-20 TO 2022-23) (SP-1V'to SP-20\) Introduction to Python CONTENTS Python Variables -1-2V 40 1-4V_ Python Basic Operators... IV to 1-12¥, Part-3 1 Understanding Python Blocks ZV to 1-130 Part-4: Python Data Types 1-14V to 1-18V, Part-6. :- Declaring and Using Nomeri Data ‘Types : int, Float ete, 1-18 to 1-23 1-1V(CC-Sem3.&4) = 1-2V(CC-Sem-340 Introduction to Python Fython Variables" ee SEESHaI bac ait hv ea artes tate == Variables: 1. Avariable holds a value that may change. Sp> namevtAlbert™ . {3 9 ‘The fos pren matements reservetie memer$ spaces with variable names year sof name D016 and Albert are stared in tbewe memory spaces Goes | What do you understand by local and global variables in Python 7 Give difference betweea them. ewer] Local Variable: “A leeal variable is declared inside a specific function and ean only be accessed by the function in which itis declared ‘Example: Lo def > 2 local variable 3. Se*Tlove Python” Iya Programing L3viCCSemae4 &# Driver nde 6 Inthe above example, wp fothes ple, ‘ave declared § inside the function Hi eran oo it Alot vara i oe that ie roe se tot nth declared outset fncion in eign ertore te aces’ by any of the emt 8 Prana 2 print Tneide function”, 8) Af 3 ¢Global ope % 4 S2"Llowe Python? 5 8) 6 printi"Ovtaide function’, §) | tocal variahie =] de the| Declared within the fartioms el Offers Data Stare ‘Scope Can be ace |e SP Soc needed Se aa 2 zi 5 [Parameten | 6 | Storage A fixed location selected | Looe Bey ar 7 Once the value charges it] O is refectd throoghout the 7. | Value Introduction te Python wav CCS SE sasabers without gram to swap FOB Geers | Write prtbes s Prompt the user for input, esting Inserneciann TES POSS Wags Ss, Semi Marks TO Bret sumberis: (numi!") pe second number is: faum2”) PART-2 ; Python Basic Operators. ae Qusid, | Define the term operator. Answer 5 “an operator is s > a™*2>> beegaces3- 7 According to operators precedence we will évaluate the ‘expression as So, the expression becomes b >>.9 >>25%ct*3 Step $:c**3 is 10°*3 which is 1000 So, the expression becomes b >> 9 >> 25°1000 Step 42b <<9isa bitwise right shift of 5 by 9 position which recults in 1 st 1>>25 which is 1 expression becomes 11000 191000 which is 1000. 7 1-6V (cC-Sem-3&4) GuelG] Discuss arithme! jon such as Introduction to Python ison operator with tic and comparison Pe ce used to perform arithmetic jon and division. python Programming 1-7V (CC-Sem-3& 4) Explain assi é plain assignment operator with example, [Answer ignment operators : This ope jn the lef side operand. ator is used to store right side operands ‘Table 1.7.1. List of assignment operators, ope “Table 1.6.1 List of arithmetic operator Tn Beam ator] Description ple (Operator a “rR [Addition operator to add two operands. s| 10+ 2020] = __| Store right side operand in left side operand, = TT sabtraction operator to subtract two operands. 10 ~20 = ~10 += | Addright side operand toleft aide operand and a=bee x Tication operator to multiply two operands.|10 x 20 = 200 store the resultinleftsideoperand feta eg 7 [Division operator todivide left hand by, 5/2=25| ca eee right side operand to left side operand |a—=b or Penthand operator.’ 2%, WO" store the result inleft side operand |wza~b Te [Exponential operator to calculate power. for = | Multiply right side operand with ot sds operand] a «bor = store the result in left side operand oe [Modulus operator tofind remainder. 5%2a1 ee azar se rordvisonapeabrofid hoquotientand | /°6//2=2] sndetorethe renga cerns [ela bor [remove the fractional part. oe Find: 7 a=alb = a = Find the modalis and ttore the remainder aa =>. Comparison operatora These operators are used to compare inlefaide opereka texbor also called. nal operators. The result of these, operator. =e “ a=a%b Belcan value ue true oe false. ht Finds ciponsatisandworetheresat, 1-]o t= or ‘Table 1.6.2. List of comparison ope , oo ft, alata sh [operator Description Temple dion andstoretheegult | // = or operator to check whether twooperand | 10==20,fals| are equal Ain Taare |Operator to check whether two operand | 10! = 20, true| are not equal. wa Answer | y > | Operator to check whether first operand 10 > 20, false! Bitwise operators : These operators perform bit level operation on. {treater than second operand, Lat us take two operand x= 10 andy = 12. In binary f Tormat this ca bo < ‘Operator to check whether first operand 10 < 20, true} ton sax = 1010 andy = 1100, isemaller than second operand. >= Operator to check whether first operand | 10> = 20, fals| is greater than or equal to second operand. Ta. | Operator tocheck whether first operand | 10<=20, true isemaller than or equal to second operand. | troductionto Python python Programming 1-9V (CC-Sem-3& 4) In fi ee Table 1.9.2, List ‘Table 7 é ‘Example Description ‘Exampl ‘Descrip' is Return true, if| eer operator] see ey results ifthe operands hey Pein true are same. | xisy, results fein Fis operat ar ies bt “0 Return false the operands are not y, results false veveen operands. OPET! x ~ on Stats inboth operands eT notis [Return false, ifthe o es, forms Ofvoperation |* | Fe 10 Return teu ita cberands are same. |x notisy, resulta tra TBiewee ‘Operator copies i mae ee Y ner operand Ay results 0110 I Biewise Bicwise — |etrercen operands, Operator coPi [ee inie exists only in one operand. or used [= 2 Feeults 0101 I piiwise [This operator fs a unary operat Biorise [TM te then of operand: SSI [Tis operator isused tosh the.) |x <<2renulte 101 if bits towards eft a ight shin This operator is used to shift the [x >> 2 results 0010 its towardsright | “Os FeaI [piece oc an ety operator with ane a é we Answer R,* el? check two or more Logical operates wre : These operators are used Faitant of this operator is always a Boolean value. Herex jue 1:10, | Explain mem a il bership operator with example. EeEEl Membership operators: 1 These opersloreare aed to che astring, alist or a tuple, i 2. Amembership operator reduce the list. “ae 3. Suppose x stores a value 26 Suppose x stores and yis thelist containing items Theazisa parol twlsty because the veloc oie he Mee Table 1.10.1, List of Membership operators. [Operator Description Example in [Return tree, ifitemisin ist orin ~~] ¥in, sequence, Return false ifitem i not) [nae Tene eve ick an item or an element thats part of the effort of searching an element in copeitons. The xe= conditions Tp perand thot etre ether true of false Boolean values, = 4 © ‘Table 1.9.1,Listoflogical operators. = , Footing reouta rod [operator Description na [nnd logical | This operator perform. “AND ojretion ‘x andy results falsd ANB | petween operands. When both operan jue Ll: ah 4 aoe trve, the resultant become true. & od | es short cireuit evaluation ? What is printed by 1¢ following Python pro; Grlogial |This operator perform ORaperation | x ory results true @=0 Fa ‘OR [between operands. When any operand baz is true, the resultant become true. en3 a logical | This operator is used toreverse the | not x result false area a Print (=) [ARTU 2020-21, Semi Marke 10 operand state. Identity operators : These operator are used to check whether both operands are same or not. Suppose x stores a value 20 andy stores a value 40. Then sis y returns false and x not is y return true. hon Programming zr us 7 1-11 V (CC-Sem-3 & 4) F 10 Pytho E Introduction to Python sem-3&4 rove couse the overall ion stops becou eee] uation of « os reiterate en te evaluation 6 ined by evaluatin + SIStv serine ohana ae detects that there 1 ee itseval 2 1 2 Togical expression- son guth as = Band uh ee a logical expression uae ofthe definition ‘When Python is procens son from lef to Fight. the — csthe exec rapremon >= 24 Fes eo the whol ‘dless of whether (s/) si eed to identify the sion bas two more operate woneed ent otanea to evaluate these operators, This is because resutof terrect ession changes depending on the preceds ; aaa sConidr a natetalen expression: For example: : 200515 pretinnine hie f to rsh. the al sae he the given expe eed ight to left, the final answer expression evaluated right oe, the Seal ase dvr fe thows thet changing the teqence in which th vecomes valuated in the given expression also change Speretars are e¥ solution. ‘When an express s the condition that specifies the importance of esch, eto the other. Table 1.12.1. Operator precedence f rom lower precedence to higher. ‘Operator os g nator! Descripiion NOT, OR AND Logical operators not in Membership operator is, not is Identity operator £5.55 45;*= am | Amiga Equality comparison operator Comparison operators » Bitwise XOR and OR operator Bitwise AND operator Bitwise loft hift and right shint ‘Addit ‘and subtraction, Exponential operator > Que 113. ] Explain operator associativity. Txne H { ity 1) aS ty decides the order in which the operators with same . left to right associat Precedence are exeeuted from the lef in right toleftsasoci Precedence are executed from the right 3. Most of the operators i 4. Left toright asso and ** operator is right to left associati 5. When two operators have the same precedence then operators are evaluated from left to right direction. For example: >e>3*4i/6 2 # Output the operators of same first. the operators of same first, Python have left toright associ operators are multiplication, floor division, etc, jotroduction to Python 1 python Programming 113 V (CC-Sem-3 & 4) = SlagleUne Ino. lock 1. | Syntax 1t containa statement ‘a recedence an ni py operator P id typically weitten on 1 mean the same ln (22, Sem-4; Marks 10 eens er OAT. Bem control no! get ; statement, ; 2.| Readability — | Suitabtetorahort aca ial rage 1-20Y ‘simple operatic “Anew age 1-11V, Unit-) erations 3 | Indentation [eae janding Python Ble = Unders' ing. 4. | Maintainability define a block of isl Tow do you xplain Python bloc! cm Expl statements” ; needed or morestatemente that perform a 5: | Clarity Cleab when the groupofone . [operation iv concine cd by their indentation, which provides structure tg Sijand a 2 am f we acope of a block 6 Might be, mort ji is important as it defines the scope of moré|Basietyto identity and Sone code organized fhalengin’ =” to conrcterronnte tothe 4 ‘ample, consider the Following code : rrors within a sing! ifx>d é reitela po 7.| Example |ifconditionsx=5 xextl block is dofined by the indentation of the two statements 5, Iathis eg within the back wl oly bo executed ithe condition clam. In this example, both x = 5) Jand y = 10 are part of the /same block because they are indented under the if| statement, Introduction to Pythoy python Data Pe 4 je1av co-sem3& ‘can be of manyitypes. Forexample, inthe na se a Nisadeas oe seed as an alphs! 2 3 4, Tuple 5, Dictionary 6. Boolean exam on a >>> numl =2 #integer number eal number (float) ponum2= 25. #real number (oa >>pnuml 7 # Output >eonum2 25 # Output String: 1 Spe uses erdbule ques arured to represent strings. 2._Astring in Python can bea series ora sequence of alphabets, numer "and special characters. Python Programming 1-16 V (CC-Sem-3 & 4) For example >>> sumple_string = “Hello” 4 store string vatue pp>sample string 4 display string value ‘Helle’ # Output Queiae] Diseu: Alist can contain the same type of items, Alternatively, alist can also contain diferent yee an order me ed and indesable sequence, in Pythoo, we ned tsa -m within square brac} at and enclose the jean are done on Also ed to store sequence of items)” items separated by corimas. #related within parenthedes rather than within square (7,"eight’, 9, 10.0) # Output Que 1.19. | Explain dictionary and Boolean data type, A Python dictionary is an unordered collection of key-value pairs. 2 When wehave the large amount of data, the dictionary data type is Keys and values ean be of any type in a dictionary. 1a type into another data ‘ype. For example: asd b=55 sum=a+b print (sum) IATV (CO-Som-3.& 4) ‘Traceback (most recent call last): File : % ‘TypeError: unsupported o} 300 »perand typo (s) for +: "int! and ‘sts? In tho given example, the variable a i type and variable 6 is ofthe string dat en We try to add these two integers an: ‘variable named result1, a TypeBrror oc Perform this operation, we have to use explicit We have converted the variable b into led variable a and , The sum is stored in the var ‘named result2, and when printed it displays 300 as output, is of the number data, at it type casting, ng 1-19V (CO-Sem-3 & 4) expression A be cor False. ‘Typo ofe: Quetas] what iz be the output statements ? the outputvatter the following GaSTSE | How do you declare numeric data type in python ? Es Drintex/»9 ‘Answer . x 1 The numeric dlityps in Python represents the data that has. mere ‘Answer ¥ 20 2 Acniumérie value ean be an integer aM wOIEE What) will be on statements ? the output after the following ing Humber, oF even a a. (Integers ‘This value is represented by,int class. i. It contains positive or negative whole numbers (without fractions or print(x/y)" decimals). Raa ji In Python, there is no limit to how long an integer value can be, 4 starimnle! TET] wom w statements ? print(“Type of a:", type(a)) ements be the output after the following x=5 Output: yea ‘Type ofa: Print(x% y) Float : aa] 1 ‘This value is represented by the float class. itis areal number with a floating-point representation. Itis specified by a decimal point. BR Ee acl SB steers ey Il Dar at Din) oie ae ll eal Introduction to Python, 4-20 V (CC-Sem-3 & 4) Gael or the followin, GusiZe] What will be the output after ty é statements 7 x= 30 print(x) ‘Answer 2 @Qausi27] What will be the output after the following statements ? x=8 yes ay print(x!= 9) 2 Answer ‘True an Quei26)| What will be. the coutput after the following vas statements? By € x=83 * 4 in e y=57 é S&S, & printixey) as Answer o 7 True’ 4 - ae ‘Gucias,| What! will be the output after the following statements ?, a z= True yo False prints and y) ‘Answer. Queis0,] What will be the output after the following statements ? x= True y= False print(x or y) Answer ‘True Python Programming 1-21 V (CC-Sem-3 & 4) Que131:| What wil be the out, statements? x= True Put after the following Printinot x) False Que132:] What wil be the out statements? x= True fs y = False f printinot y) put after the following [Answer the following | Whatdwill be the. output’ after the following statements? ( 7 y=53 Que135.] What will be the output after the following statements ? Introduetionto Python, qeg2v (c-Sem-3 & 4) statements? xa 2d +16 print) Answer, 2n6 Queis7 statement if input entered x input(Enter a number?) “Answer Integer Que 139. ¢ followin, What will be the output after the f 7 What will be the data type of x/after the following 18? What will be the'data type of y after the following if input entered is 50? ‘nter a number’) What will be the data type of y after the following What will be the output after the following What will be the value of x, y and = after the following Python Programming 1.28 V (CO-Sem-3 & 4) 5% 2234,5 ‘Answer = ill have the value of 3, y wil Z tui have the value of 8, will have the value 4 and = will have the value ‘Qhe'1-42:|] In the order of precedence, which of the operation wi be completed last in 3°6+5-4/2 i the following statement 2 ] Subtraction Que ras: : What will be the order of the following statement ? 10°4-148/5 7 Precedence of operations in e Multiplication, Divis Queias, Addition, Subtraétion : | What will be the datatype of x after the following statement if input entered is 64 = =floatinput(Enter a number: | : i statements? 0227/3862" 4009) print(a) ag i ; statements ? a=3/3.47-3*3 print(a) i ©00 Program Flow Fee col Conditiona] Blocks ee 1. and Dictionaries Partly Parts: 5 ‘ming Using Python. Ft eal and Loop Blocks 21V(CC-Sem-3 & 4) ‘ython ? elp in making a decision based on certain ‘Wot of conditional stateménts having to true oF false, lsoknown ayidcrision-miking statements, An if statement consists of a Boolean expresei restatements, ' condition is provided; ithe eondi nt written in the If Booleah expression) : Block of éoda tSct of statements to execute if the condition in true 4. Flow chart : f Statoments of if block rest of the code 2-3 V(CC-Sem-3 & 4) Programming of expression is 100 value of expression is 100 Good bye! GaSEET | What do you mean by if-else statement 7 EsPisin with the help of example. peel eer eT tem can be allowed By An i at can expression Fal aaeen dition is used when ie have tajudBe one statement onthe reefer ‘ ibe statement, which of code #Set of statements to execute if ‘condition is true sats to execute if condition’ fae else : Block of code #Set of stateme! Working and execution? * ‘Tae condition wil be evaluated to a Boolear expression (true or inside the if eat eondition false th ESSE Bac wits erste & Flow chart: % .entS or program present Condition ? False Statement of if block ‘Sratement of else block rest of the code 24 V (CO-Sems Sem8.& 4) Python Program Flow Control Conditional Blocks For example : num = 5 "Numberis greater than 10") Print (Numbor is le print (“This statement wi Output 1. Nested-if'statement seetaa iy Statements are nested inside other if statements. That is, a ‘statement is the body of another if statement. "ments when we need to check secondary conditions the fist condition executed as true. 3 Synt iftest expression 1: # executes when condition Lis tr body of if statement2iin, iftest expression? 7 # executes when conditi Bodyofnested.it else: J body of nested.it; print (“ais smaller than 257) else print (“ais greater than 25°) else: Print (“ais not equal to 20") Output: ais smaller than 25 a Py 2-5 (CC-Sem-3 & 4) Flow chart Body ofc atement ar te onditionals Guess, | Explain elif statement in Python. Different types of conditional statement are. statement: Refor Q. 2.2, Page 2-2V;Uait Irelae statement: Refer Q, 2.8Page 2-SV, Nested iftatement: Refer Q, 24;Page 2-4V, Unit-2 Elif statement: y a Blifstands for else ifin Python. b. We use elif statements when we need to check multiple conditions only ifthe given ifcondition executes as false. Working and execution: i. Ifthe frst if condition is true, the program will execute the body of the ifstatement. Otherwise, the program will goto the clifblock (else ifin Python) which basically checks for another ‘statement. ii Again, ifthe condition is true, the program will execute the body of the elif statement, and if the condition is found to be false, the program will go to the next else block and execute the body of the else block. V (CC-Sem- EOVICOSem-284) Python Program Flow Control Conditional Blocks a Body ofelso Flow chart: Body of if statement [Body of clit statement] | [ Body ofa ‘Statement just below clifelse statement For example: a=50 f(a ==29); Print valu of arab ai 20 elif (a == 30) ree print (value of variable ais 30°) cuir QR, Cvalve of variable nis 207 print Cvalue of variable ais 40°) else: Print (‘value of variable ais greater: 7 a Ereater than 40°) value of variable a is greater than 40 Write a pro a Program to find whether a number is even or BTV (CC-Sem-3 & 4) or) ser an integer purabe Output to check the largest among the given GEST | Write a prosram three numbers, ewe] 2) soo x= int Ginput (Eater the first number“) il u hs seo the cecil wombat“) 1 (input (“Enter the: Spo secca umber! 2 ° Bote Spat Ener ie hirdmanber) Enter the third number £20 poo if(x> sand (> 2): 1=x elitey > Vand >=) 3 aey else: 1=2 ‘pop print “The largest among the three is", ‘The largest among the three is 21 QueZE!] Write a Python program to check if the input year iss TARTU 2021-22, Sem-4; Marks 0] #Output leap year or not. “Answer >>> year = int (input (“Enter year o> if (gear % 4) == 0: if (year % 100) == 0: if (year % 400) : print (year, ‘isleap year) 28 V(CC-Sem-3 & 4) Python Program Flow Control Conditional Blocks Enter ayear: 2016 2016 is leap year Output: Enter ayear: 1985 4 1955 is not leap year 2 QEEZET] Write a Python prograit'so aijtay the Fibonacci Saeaen a tene : ‘OR Write a program to produce Fibonacci series in Python. ‘ARTU 201-22; Sem3j Mark TO “Answer - >>> number = int (input “Enter the value forx ‘first the terms * pooxi=o c poeaz=1 » ye" >>> count =2 # check ifthe aumber of ter >>> ifnumbers <= 0 Print (“Please enter posit elifnumbers == 1: print (*Fibonaeei sequence is”) print (x1) else: Print (‘Fibonacci sequence is 2”) print (=1,5,%,x2) while count < numbers xth = x1 4x2 print (xth) wo 2-9V (CC-Sem-5& 4) a Programing pythor opine vals utr cau for nmbare n> 29730 Pitonacleaene® 0,1, 1,2, 35,8, 13,2194 GaeaAs, | What wi x=70 itz <= 30 or x>= 100: print(truc’) elif'x <= 50 and x == print(not ruc’) elif x >= 150 oF x <= 75: print(false’) f s1be the output after the folowing statements? else: Print(not false’) << false “GasZAT:] wut wibe the outputafter the following statemente? x=40 y= 25 itx+y>= 100: print(true?) olifx+y == 50: print(not true’? else: print(‘not false’) Gnewer | false Qucdid. | What willbe the output after the following statements? 210V (CC-Sem-3 ‘$4 4) Python Program Flow Control Conditional Blocks | What win ‘be the output after the following statements? Que2A5.] what wi bs Bae Al be the outp: ifx>10 and x <1: Print(true}) olifx> 16 and x< 25: _ Print(not true’) ouez> 26 and xcs, Print(false}) ut after the following statements ? ol Print(‘not false’) not falue g-11V (CO-Sem-3 & 4) Mowing statements? qanaae] wh xel5 Tes 10 ands printers) lige > 16 and x < 26: “print(‘not false”) [eant2] im Python, For Loop Using Ranges. true Simple for Loop’ euiss the purpose and working of at ogrsing rreturethat repeats eauenstfinsiroetans specifie condition is met. * statement allows usto execu! ‘multiple times. 9, Python programming language provides, looping requirements: a For b, While Nested % 44. Purpose : The purpose ofloops isto repeat the same, or similar code Purp oreitimes, This number of times could be specified toa certain numer or the number oftimes could be dictatedby a certain condition being met. 5 Working : Consider the flow chart for a loop execution Inthe low chartfthe test condition is true, then the loopis execs, wei iritis false then the execution breaks out of the loop. b. . After the loop is successfully executed the execution again starts FT hhe loopentry and again checks for the test condition, and this Keeps on repeating until the condition is false. oastatemontor roapot statements {rising Sos ofoopato hands 2AZV (CO-Sem-3 & 4) Python Prog locks ouththaep QeFAB] Exptan or top with thee “Answer 1. For loop in pytl several times ui 2 We use for k loop, 3 Synt for variable in sequence: Body of for loop 4. Flowchart : Ip of example. te. block of a cagaree@ Block of statements or code Entering for loop for bee 9p for Gach item in Exiting loop Body of for loop Statement atert for loop es ed opt Nese oop a 333 55555 7777977 te oe thee op. gra ¥ (CO-Bem3 & ay 214V (CCSom-I.& 4) Python Program Flow Control jot the fol Que 220.] Write a Python program to construct th torn, using a nested for loop. TAnewor |] Program : thas any factor between 1 and iteclt. yes, then the number is not prime, and it will move to the next Step 4: Ifno, itis the prime number, and the program will print itand check for the next number. ‘Step 5: The loop will break when itis reached to the upper value. Code: 1, # First, wo will take the input: 2 lower value “Please, Enter the Lowest Range Value: ")) 3. upper_value =i put (“Please, Enter the Upper Range Value:”)) 2-1BV (CC-Sem-3 & 4) hon Programminé sme Numbers in the range are") uppervalue +1): Py jn range (lower value, f print (number) inction. How d6 you une i for loop Q00222)] Eeeael ae range () fu Poi, Pe cceance ner bed vale af tha ciegeela?” Beart Willman sp sind nanttpn st tat rorvonta chet bes 2 cone cept tick of co focall Lis PeahStin.a ranged 4, Example i fi 2 for xin range(6) : printix) ‘The range) function defaults to 0 as a starting value, however possible to specify the starting value by adding a parameter: range(2, ‘which means values from 2 to 6 (but not including 6) PART-3 String, List and Dictionaries. (Que 223, | What do you mean by the term strings 7 2AGV (CC-Sem-3 & 4) 1, Strings are created by enc quotes. Python doen not diated bY enclosing various characters within quotes dist ns a“ between single quotes and doublequoten Te walug Tal oF salar type, The Python interpreter treats them Pon Program Firw Control Conditional Blocks. Strings, in Python, can be used as can be accessed in parts, This make isle data type, or, alternatively, handle in Python, ings really useful and easier to i >>> print varl renee Hello Python! # Output 4 >>> print vara ‘Welcome to Python Programming! Que 2.24. | Write short nota on itet: ‘An # Output ies in Python, of any type, Fe called elements Fitems or elements, ordered anid can be accessed by their 2 # Output >> is 4 # Output Que 2.25. What is dictionary in Python 7 “Answer | ‘The Python dictionary is an unordered coll I other compound data types i ements or items whereas the diction L it : lection of items or elements, & The progras fret evalustes the while vp eonAition, Trae en te program exer the lop and exten the by of the while loop, © SRauRe 1 exscute the body ofthe while Lp as long as the condition is true & RSE St Ge, the program comes out of the lop and stops Pepeating the bdy of the while len For example: <== ent = orant «3 — = et a Que227.] Exptain the Use of While Loap in Fy pA SE gedeuitebleexamplen, FG ‘Continue, Breck and Else, i For f = cL ees ‘Answer _ 8 L%’ 4 | PRS & <3 } Feoer: Beer Q 23a Page 2 az, Unie dD $ Beswers fier ace so egy Ea B While loop tite 22, Pose? ay, Von 2) © Seca ws fn ence omnes — ee 22 | Whee id break ratement in Pyenie? Scie, ea Seemaere the exalt the = E Se exseiors ie matemoncs ht x Seana foliage vp, $0) Prtton Program Flew Coctrl Conditional Blocks Program: # Function to convert the date format def conrert2uietrt): a Pa stegtinee nie she parpore! = = with example. Write = Python program to conve _ = eben format ‘Sime foam 27 hor: Print (laside the elee statement”) ae (ARTO 2019-20, Sem; Marks i] ‘Que232 | Ditterentiate between for and while a ee Ee p21 V (CC-Sem-3.& 4) python Programming [Answer 2 Propertics| [Format ‘top of the loop. fuse The fr loopis uscd only when| The ‘while’ loop ie used only roe day knew the number | when the number of iteration ofiterations. tre not exactly known, ‘Condition | Ifthe condition is not given for’ loop, then loop iterates infinite times. in ‘for loop the initialization Jonce done is never repeated. he continue, break, and pass statements with, [AiCTU 2022-23, Sem-3; Marke 10] itable examples What will be the Wi ie sist Output after the following st stator printly, ends”) E Mynyxey [Anewer) 112368 while y <3: Print(y, onda! yer yy Cog on {break and continue with a suitable example, AKTU 2021-22, Sem-4; Marks 10) Taewer | ) Continue : Refer Q. rage 2-19V, Unit-2. go 2-18V, Unit-2. Explain the une oF 1. The pasa statement in uscd as a placcholder for future co 2, When the pasa statement is executed, nothing happens, getting an error when empty code ix not allowed, ut you avoid. ons, class definitions, or in f statement, For example: n=10 & 86. | What will bo the output atte print&xty, endat) xte3 vend ieee al Pars ining Using Python Conditional arid Loop; Blick 2-23 (CC-Sem-3& 4) BAAN (CC-Sem-3&4) Python Program Flow Control Conditional Blocks ‘number = int(input("Enter the integer number :")) ‘Initiate value to mull reve_number = 0 4 reverse the integer number using the while loop as while (number > 0): Ts remainder = number % 10 i sckera® SP ners more wba? vrevs_numbor = (revs_number * 10) + remainder Checking ifa> number = number //10 with for oop 4# Display the result given numbet a 4 Teerating over the = 00 for} in range(2,inx(a’?) + 1 print("The reverse number is Output: Enter the integer number: 12345 ‘The reverse number is : 54321 or not ¢ Ifthe given number is divisit Hae —aO ip ‘print(e, “isnot a prime number") break eElseitisaprimenumber eke: e printia, “isa prime nember ‘ifthe given numbers 1 / else: — luation and float representation Program for how to check if a given » [ASTU 201820, Sema Marks 10 me noxber") je Senet 2 prime P reking an input number from the user a= intGinpot(Enter on mput m defisPerfectSquare(x): s=intimath sqrttx)) biesgipucereee ve return s*s== 5, # Returns true if'nis a Fibonacci number; else false de iFitonacciny te the reverse of any enterei_ “GasESE | Devctop a program tocalesls eee return isPerfectSquareS*nta +4) or fPerfetSquare(Statn 4) [RETO Soa as Sema MEAT) a # Autility function to test above functions fori in range(1,6): “Answer if GeFibonacei(i) == True): Ack Sor emer the sumber from the use 2-25 V (CC-Sem-3 & 4) python Programming printivis a Fibonacci Number" else: print icisanot Fibonacct Number” Output : 4s a not Fibonacci Number 5 ina Fibonacci Number tring Data Typen String Opecationg Pet and Defining List and List Si Manipulations Building Python Programs, Sito Methods, Lit Dictionary M + Programming U; and Dictionary Python Pua, Python ‘Code n Complex Data Types S-2V (CC-Sem-3 & 4) Python Compl Typ [east] Using String Data Types and String Operations. Que Say] What is len() function? oR Explain length of the string. Answer f ction in Python. When used with a string, len returns the the number of character in the string. 2. Blank For example: >>> var = “Hello Python!” >>> lentwar) 13. # Output Here, we took a string ‘Hello Python! and used the len functio Ten Rinction returned the value 13 because not only character: Tia spare and exclamation mark in our string will also be counted ag elements. ¢ GacZ | Discuss the concatenation and repeat operation in Python with example. 5 ‘Answer Concatenation : é 1. Concatenation means joining two operands by linking them end-to-end. 2. Inlist concatenation, + operator concatenate two lists with each other ‘and produce a third list. - a ‘concatenate two lists asterisk (*) operator. Python Programming, 3-BV (CO-Sem-3 & 4) Wlist alist repeats three times *aList multiplied by 3 and printed three times. ‘Que53] What do you mean by string slices ? ‘which Consists ofletters at index but ereluding thea pl [ello Python >>> print var (0: 4) me hi ‘extend till ele isa, lement, then 4 clement and then Tl my_list = my list Lfor_in abodefighil range. 6. Python also allows negative i GaETET] Demonstrative ferent bali funet ‘example thi ceees my-] indices start from—T- ere are Ql index from snplox Data Types then it thro the end of the list using a negative dex fromptart counting from the Fight instead rptibn grimy i charactors a tho atring ure lurne"Truo fall charters inthe tring are Return Truo all lowercase, I charactors in the string are| strisupper Returns True ifall characters in the string aro ifallch f ho airing def isPalindrom: s=*malayalam” ‘ant= isPalindrome(s) ifans: Output: Yes Progeam print(*Yes") print(*No") isNa Converts the first charact vupperease. of the string to Convert “Characters in the string tl lowerease. [str upper’) Converts all characters in the string uppercase, iy arte Converts the first character of each ward to uppercase a str-strip(lchars)) ‘Removes any leading (spaces at the beginniti and trailing (spaces at the end) characters.—| ste replace (old, new!, count) Replaces occurrences of a substring wit another substring. You can also specify i naxinnum number of replacements." ‘True ifall characters in the string str isdigit) We can make a duplicate or copy There are two ways to make ry ofan aging li, ; y of alist. Using] Operato 1 # Using . >>> print list_eopy rlphiaiine 11,2,3, 4) Using built-in function : Python has {2m be used to make copy of an existin function, first we have to import it. For example: ‘n copy funetion which >>> fromeopy import copy # Import library Date Types senta are deteted (08 alist? Wawa tow oe asle Methods of deleting ¢ 1. popoperator! Pesye 2] # Output ore opersor: 8 Rem tn remove operator ow th a from the list. e item that we wantte >>> print list {20,30,40) # Output tk Inorderto delete more than one value from alist, deloperator wi shcingis used. £ For example: ppolist= (1, 2,,4,5,6,7, 81 ctition operator repenti the list fora given number mn is performed by tho * operator. ‘True # Output >>>"World’in list False # Output Que 8.9." Write various built-in list methods. Explain any three with example, eludes many built-in methods for use with lis bays yy built-in methods fo ith list as shown in = python Complex Data Typen “Fr compares the elements - and ist2 = rns the iemthat has the maxim, A ancien ee Tesorts the elements inside the ist. ues : on fonction ifprovided Extend method : This method w: concatenation. It takes alist 2 rend tad adds it tote end of another ist, S-9V (CC-Sem-3& 4) ac—V—~'—~A—X_ FOV CC-Sem3E 4) #Outpur ‘9:10, ] Discuss list data structure of pythoa. Explain various inbuilt methods of list with suitable example of each, ‘AKTU 2022-23, Sem; Marks 10 Explain the list comprehension with any sence scture : Refer Q. 2.24, Page 2-16V, Unit’. methods : Refer Q.3.8, Page 3-7V, Unit: aa |] Define te term list comprebeniton, oR 20, 30, 40, 501 (20, 30, 40, 50, 60] poolist = (4, 2,5, 8, 1, 9) Using list comprehension, example, the output for both without list comprehension, >mprehension is the same, python ComlexDate Type, code and also runs factey, Python Programming requires lesser 4 a stist omapeebenston PRETO omprebension contains: senple we can SY SUIV(CC-Sem-3& 4) expression ris pineal cope or output variable oe oreturnlist of number, \ any ansument like Initial, End or Indes metion lessthan (st,®) the use of default values: al Ie ace nf laggewertnane Sees feast valoes ie Oas inital ngth ofthe list as End and teas than E from ali ree Eeample: oyreturns(-2-31 5 i = Jeasthan ({1,-2, 0, 5,-S1 0) ret ARTO 5020-31, Sem3; Marks ip} PART-3 5 Use of Tuple Data Type, Si ting. List and Dictionary. Que8.14 ] Detine tuptes. How are tuples leated in Python? ‘Answer a 1. Tuples are the sequence or & fom bby commas () Sea eit with an example, Fatuca'l 4 n ine list stiging and illustrate it with. s 2 Values in tuples can also be aecessed by their index values¢hich are Que 81S, | Define list slicing 2 integers starting fem ee ralues, which of different types separated tuple, all the jtems ot elements are placed inside Separated by commas and ascigned toa variable. number of different data items (that is, integer, discs utnder bad ata tep ste inden. Esanple: ‘nile it >>onested_tuple = (*Python”, [1, 4, 21, [ohn*, 3.9)) Python Complex Data Type, g12v (CO-Sem-3 & 4) ‘Quesi6.| im to add an i QueS.Ab,] Write a Python program to L >>> print nested tuple Ceython’, I, 4, 2h (58 ‘Tuple can also be eres 49, 6, house 9) # Output , without parenthesis = pootuple = >ooprint tuple : i use), # Output : 49, 6, 0 em in a tuple, che values in'a tuple There te a aca ei | For example : Using square brackets ut >ootuph ‘Chemistry’ ‘Mathematics! \ >>ptup2: ), 40,50) i 0 >>oprint Chemistry # Output >ooprin up? i] 50 # Output 1 Weean also use slicingin orderto print the continiious values in atupé For example: >>otupl = (Physics’, Chemistry’, ‘Mathematics + >>atup2 = (10, 20, 30, 40, 50) @ >>ptup2 (1: 4] (20,30, 40) # Output ‘isneckssary to use winder Python Programming S-BV (CC-Sem-3& 4) ‘Que3.17-] Explain tuples as return value -s and variable-length arguments tuples with the help of example. “ Eze ‘Tuple as return values : 1. Tuples can also be returned by the function as return values 2 Generally, the function returnsonly once Feturning: function can return more than ene valu oe Cu Petr tuple, 8 For example If we want: e time, Two values will be byuusing the tuple as the return >>adef div_me quotient = aft remainder = a%b Feturn quotient, remainder. # ‘function calling pox = 10 poy =3 >ppt div modix, y) >>>print t GD # Output >>stype(t) # Output Variable length argument tuples : 1. Variable number of arguments can also be passed to a function, 2. Avariable name that is preceded risk (*) el Arata ‘byan asterisk(*) collects the arguments # defining function function returning two values the given example, we have which means it can take +h of them one by one, >>odef traverse (*t) : 5 izo defined a function traverse any number of arguments

You might also like