You are on page 1of 42
145) “Be aa eating Figure (Fig, 52) explains selection + eect a yoo opply decision-making or selection in nee wee Tl tie s0 sany times eg. ite Staenenta| # Yoo can think of many such real tife i Te Samples of selection/decision-making, | ae =~ ©. » etton feration (Looping) Fite 52 the section conte . ‘eiteration constructs mean repetition ofa setofsatement ent Beta coviton i True (or a dase eames sep pons tides ~ again and again. As soon as the condition becomes Fale or True) the repetition stg te iieration construct is also called ronsirit TE eee Bene ‘he adjacent figure (Fig. 5.3) illustrates an iteration construct. Soe The set-of- statements that are repeat Seat peated again ~ "ange ‘and again is called the body of the loop. The SI Tee _ me eS tondition on which the execution or exit of tue oe oe theloop depends is called the exit condition or aes . test-condition. | Statement 4 You can find many examples of iteration or Teteeh Jeaping around you. For instance, you often son see your mother cook chupats or doses or | ead appons for you ——_ E 253 he Heston epeton conn on Let's see, what she does for it () patrolled chapati or dosa batter on flat pan or tawa (ii) turn it23 4 (di) once done take it off. ) for next chapat/dos/appam, This is leaping or iteration. Repeat the above process (steps (0 (i. ( ¢2, washing clothes You can find numerous other examples of repetitive work in yout real life colouring in colouring book ete. etc Every programming lang = age must support these three types Si of constructs as the sequential program execution (the default mode) is inadequate to the problems we must salve. Python me 1 Wat isa statement ? How many types ent ? How many tYP25 leo provides statements that support these constructs. Coming PEE Ye glficance of 4 92 lection and for and while that support iteration, Using o a aa tr cive tee tatements you can create programs as per your need on ‘Glample of a compound Boat But before we talk about these statements, you should know WM ae the tives constructs that basic tools that will help you decide about the logic to solve a ‘mm statement flow ? given problem ie, the algorithm. For this, there are multiple BME the eed for selection and tools available ping constructs ? che input (“Enter a single character :+) ‘ elias Oe . it ee Ste hie co i ty ho ‘ print CYoventereda spacey n/m Pom th te ay if ch>="@" and ch <="9 in print ("You entered a digit.») ‘Theabove code example re. sample reads a single character in variable ch I he character input isa space, iflashesa message specifying it. the characterinputis cig ig, _Thellowing example also makes use ofan ifsotement i 4 A= int (input (“Enter First integer :") ) . Be int ( input (“Enter second integer :") ) | if A>30and Bc1S: | C=(A-8) * (A+B) print ("The result is", c) | print ("Program over") b: # comparing two variables print (“Ahas more than 8 has") () ifx: # testing truth value of a variable print ("x has truth value as true”) print (“Hence you can see this message.") You have already leamt about truth values and truth value testing in Chapter under section 443A. Til advise you to have a look at section 443A once again as it will prove very helpful in understanding conditional expressions. Now consider one more test condition if not x : #not xwill return True when x has a truth value as false print ("x has truth value as false this time”) The value of not x will be True only when x is false yj and False when x is tru a The above discussed plain if statement will do nothing if the condition evaluates to false and ‘moves to the next statement that follows if-statement, [Z- soremen. mu we Of oy ip ayneee Je froat CAnput( “Enter First number Bertier) ¥5 paoat (Anput( “Enter third number ==)” maxeX 2P) fom ry wom: mee prine (Largest number is, max) Beet tclver tas fater second number : 6.99 freer third nunber 7.533 Largest number is 7.533 5.8 Program that inputs three numbers and calculates two sums as per this ca De mm Stim as the sum of all input numbers ‘Sum2 as the sum of non-duplicate numbers; if there are duplicate numbers in the input ignores them eg, Input of numbers 2, 3, 4 will give two sums as 9 and 9 Input of numbers 3,2, 3, will give two sums as 8 and 2( both 3's ignored for second sum) Input of numbers 4, 4, 4 will give two sums as 12 and 0 ( all 4's ignored for second sum) Alternative 1 m2 int (input ("Enter number 1 un? = int(input("Enter number 2 nun3 = int (input ("Enter number 3 : yuma + num2 + num3 sunt if num !=num2 and numt !=num3 = ssun2 += num if qum2 |= num and num2 != num3 = sum2 += num2 if num3 |= qum and num3 |= nun2 + sun2 += num3 print("Numbers are” print (“Sum of three given numbers 15", 5! print ("Sum of non-duplicate numbers 15° ,, num, Aum, num3) und.) sun) ‘fum2-= int (input(“Enter number 2 : y ‘fum3 = int (input (“Enter number 3 : a ‘SUML = num + num2 + yum - i ‘numa $f num3 t= num : sun2.+= num3 else: 4f mum == pum sum2-+= numa. else: AF pum? = num sun? +=numt else: sum jun + nue2 + nuMs print("Nunbers are", num, nun2, nun3) print("Sum of three given nunbers is", sunt) print ("Sum oF non-duplicate numbers is", sun2) Samples fun a spore pres) ine below : “ Enter number 1: 2 enter number 2 : 3 enter nunber 3 : 4 Numbers are 23.4 ‘sun of three given nunbers is 9 sum of non-duplicate nunbers is 9 Enter nunber 1: 3 enter number 2: 2 enter nunber 3: 3 Numbers are 3.23 ‘sum of three given nunbers is 8 ‘sum of non-duplicate numbers is 2 enter number 1: 4 enter number 2: 4 enter nunber 3: 4 Nunbers are 444 sun of three given nunber: s is 12 sum of non-duplicate numbers is 0 iter davis nt (2. Calcutate Area) print (2. Colculate Perimeter) Af chotce area = 3.18159 * radius * raaiu print ("Area of circle with radiuc ve with radius’, radi perm=2*3.24159 * radius Print ("Perineter of circle with radius! radius of the circle ; 2.5 1. calculate area 2, calculate Perimeter enter your choice (1 or 2 rea of circle with radius 2.5 is 19,6349375 inter radius of the circle : 2.5 4. calculate area 2. alaulate Perimeter enter your choice (or 2) : 2 perineter of circle with radius 2.5 is 15.70705 [Notice the test condition of ifstatement can be any rs {ée,a statement that results into either trv or fuse), The itsboth if and else lines must 5.43 The if - elif Statement Sometimes, you need to check another 4 condition in case the testcondition of f enge tholce = int (input (“Enter yeor Test Enter your chotce (an) 2 yy WS, is, area) "rads, 4s, parm) relational expr logic ression or a logical statement ifstatement isa compound statement, hence. # end ina colon and statements part of it must be indented below ‘if runs are more than 100 hen it isa century {if runs are more than 5@ evaluates to false. That is, you want to chenietsacitey check a condition when control reaches else part, ie, condition test in the form of | ©15® ‘lse if. To understand this, consider this adjacent example. batsnan has neither scoreda century nor fifty Refer to program 5.3 given earlier, where we have used if inside another ifese Toserve conditions as above ifelif-else statements. The general form of these s ‘if : and statement [statements] elif : statement [statements] Bi in else if form (or ifinside an else), Python provides if-elifand statements is| if statenent [statements] elif JT (s)aueweze3s asta (s);uouane3s + > $+ ‘cuoyssaJdxa TEUOTITPUCD> 4112 (s)quowaze3s asa (s)auamazers uorssaudxa TeuoT3spuo>> 4 +: 4 p wio4 [squoware3s] quaue}215 asta (s)quaueyeas 4 > [squauase3s] 3uoua3eys > 41 13 (s)quawaze3s ast (s)auauaze3s #4 asi? [squaua3e3s] quawe3e3s saudxe TeUoF3Tpuo2> [sauewa3eas] juaw93e35 <> 31 ( Apog S252 episu {[syuowa3e35] 3uouo3e3s [squswa3e25] uswa3e3s +: cUoysseudxa TeuoyaTpuo2> 4112 (s)quewa3eas os12 (s)uawa3eas FT > #1 print ("For quadratic equation, Ant input (“Enter as") be ant( input (“Enter b:*) ) = int( input (“Enter ¢ :*) ) | WAX 2+ bx +e "24 DX +60, enter coefficients below") if ane: ee print ("Value of”, a, should Soiree kee print ("\n aborting 111111») > “i itn a math. sqr() # both Linits shouldbe integers ire pion in the form range(1, u) will produce a list having values starting from I, 1+, +2 vpper len ian m being integers), Please note thatthe lower limit i in the list but Upper limits not included inthe lst, eg, "(acca range(@,5) <~ ‘the default sep-atue in values will be +1 Ss also ta Tonk will produce list asta 49 ++ range(12, 18) + default nena < ot a will give alist as [12, 13, 14,15, 16, 17), my For such lists, you can use following form of ranger) funct range( ) that creates a list from 0 (zero) to ~ 1, «¢., consider following rage ) fun range(5) 7 “The above function will produce list as [0, 1, 2,3, 4]. Consider some more examples of rangel) } function: Statement __|__Walues generated _ Fane Dizsasenas | range(S, 10) 5,678.9 | 45,6 range(3, 7) 34 range(5, 15,3) [58114 | range(9, 3, -1) )987,654 42 range(10, 1-2) | 10,8, 6, (| Operators in and not in Let us also take about in operator, To check whether a value is contained inside a list you can use ino] uK which is used with range) in for loops. yperator, 6 ‘This expression wi te fale rained in th given sequen in (1,2,3,4] « ower spe rel OF OFF 100P 16.5 si. hey gorcvariable> incsequentes statements to_repeat fora in[t, 4 Been [, 4,7) tO ro Asis Print (3) <— ent Print(a a) Ter toerin Python is processed as ‘The loop-varable is assigned the Ges alle statements in the body of oe ° or (step 2) @ once step 2 is over, the loop-vatial value in the sequence and the loop’ step 2 repeated) with the new value my ‘@ This continues until all values in the s ‘hat is, the given for loop will be proce: @ firstly, the loop-variable @ will assigned first value of list ie, 7 and the statements in the body of the Joop will be executed with this value ‘of @, Hence value 1 will be printed with statement print(a) and ‘will again be printed with print(a*a) (Ge execution shown on right {i) Next, a will be assigned next value in thelist ie,, 4 and loop-b Thus 4 (as result of print(a)) and {as result of print(a‘a)) are printed execute: performed ed loopscs (ii) Next, a will be assigned next value in thelist ie, 7 and loop-body executed Thus 7 (as result of print(a)) and 49 (as result of print(ata)) are print Py (io) All the values in the list are executed, nly cove hence loop ends the wt Therefore, the output produced by Above for loop will be a string 161 are executed with signed the next Note is executed see nee fh tne, when th 3 Toop body are executed + print (1) print a assigned next value and oop body executed with a as 4 print (4) paint (4%4) ~ a assigned next value and oop body executed with 2 as 7 print (7) a t print (747) ee 1 io nore values: 4 16 J ‘Cansidter antler for Toop ft nd wes eng, for ehin‘caltt + revealed forthe stan ‘print (ch) sequence * above loop will produce output a8 + i) The for toop umber of : {or1009/s header ee ON iin, Pi ee aes ue in the list ferent baie forvin(1, 2,3]: ae Pe re she yi : : Tf hep ah wh ahs ypu il, it we eee ee eres faiy Tor good on readability. Then 2 Then what 2 Arey, our very own ranget ) represent a list as in for val inrange(3, 18) : print (val) Work peove loop, rage 1) will first generate list [3 4,5, .., 416, 17] with which for oop work. Isn‘t that easy and simple ?@ You need not define loop variable (val following code example that uses range) anction ip S11 Program to print table of @ number, say 5 above) before-hand in a for loop. Now consider for loop to print the table of a mum um = 5 fora inrange(1, 11) ; print (num, ‘x’, a, Sx1=5) 5x2= Six 3 =a 5x 4-20 "num * a) The above code will print the output as shown here NOTE YoU need not pre-define loop ‘arable ofa for oop, So eefit) Elo inteene Fieri siraemane nines) soveieig ecto -qhe above code will print the output as shown here 15.18 Program to prin sim of natural numbers between 1 to 7 sun=@ for n snrange(, 8) sum print ("Sum of natural numbers <=", n," 1s’, sun) ‘sum of natural munbers <= 7 1s 28 — Carefully look at the above program. It again emphasizes that Aone Bee etree nie adh celeron ral os voy merant one tothe value of oop cara fer te ‘he mpl enn the or opis nett highest elu ofthe list. Notice the above esto bea a Area elated value of m efter for loop 10 7, which is ce eae aaa maximum value of the list generated by range, 8) hela 57.2 The while Loop ‘A-while loop is a conditional loop that will repeat the instructions svithin itself as long as a conditional remains true (Boolean True of truth value ty). ‘The general form of Python while loop is while clogicalexpression> Loop-body where the loop-body may contain a single statement or multiple statements or an empty siatement (Ge, pass statement), The loop iterates while the logical expression evaluates to true. When the texpression becomes filse, the program control passes to the line after the loop-body ‘To understand the working of while loop, consider the following code This condition i sted. fist, the pba Fi ed Aer he lop-bodys aAatts wiles 6 peer print ("hello", a) condi is tr print ("Loop Over! !*) ‘The above code will print These fo ies the reso while ops bly hello 5 | acon ick end heno 2 | Loop overs) ¢—— Ths ni bss of rin starr fier the while lop, = : 18 Spor ol while Loop (Lop Conta Boren) Hee Byety while oop has its elements that control and govern its execution. A while loop has fou me yan aredsttnat have €iiferent purpose Naum call These elements are as given below ) Oine— pins {. Initialization Expression(s) (Stosting) — feforeentering na whillop, ts oop variable must be nitlized, The initatization ofthe loop — variable (or control variable) takes place under initialization expression(s). The initialization expression(s)give(s) the loop variabe(s) their first value(s). The initialization expression(s) for we decides wheter th oop-oay wfc orn GC mucartewin tenuis ein ciberse ep oe Beers steel pret pice Reta ieo ctynaan it meh ac A he no FO 3TH Dodyotthe-Loop (Doing) festa: Pn oe oa) 2. Test Expression (Repeating or Stopping) The test expression is an expression whose truth value In a while loop, the test-expression is evaluated before entering into a loop. The statements that are executed repeatedly (as long as the test-expression is true) form the body of the loop. Code agment ? is evaluated and ifit is true, the bady.of the lop is executed: Fort in range(@, 12) : if the testexpression evaluates to false, the loop is pass terminated. print (4) 4. My does “lio" nat print even once? 4. Update Expression(s) (Changing) for 4 in range(1@,1) : ‘The update expressions change the value of loop variable print (‘Hello") The update expression is given as a statement inside the '& Wate a for oop that displays the even body of while loop. sunbers fom 51 to 60. 7 Sone» sation whew an emp) Infeesting Fact ~ Win isthe sinnaty an aieenee & PO2M Wen about Python Programming between for and while loop ? 8 Why is wile toop called an entry ‘entrlled Loop ? ‘MW the testexpression of a while loop lusts to false in the beginning of Believe itornot, aman named Tim Peters has composed a poem called “The Zen of Python’ about Python programming. Simply type ‘import this’ into an interpreter prompt 10 read this | ‘entertaining poet. eam ara as bomen e (9) how many times is the loop ‘aecated? ©) tom many times is the loop-else iause executed ? ae “21021 pum 21) suo dupa persone» 0 uodn bpsoise sours 0 voy 7 *¥o-torpue> 0 uodn Buypuodep (sno, . 20} 0) ro : 2) p hae ops a) shan20}2s-(onasuo aouanbos ~ 27 wou 9 ‘sion Kida so mowers 880d silo vou auieis punoduea pu ruowaror 2 » yom sya aes: — oF (000'00'2 “su aunowe popu 000%: oooet: € 000 o0zt: sgt Questions Muitipte Cho sea thon progam «contol structure pvt the order of execution of the s what happens before the program y) aot sg deines programspecfic cat structures fp manages the input and output oF conto characters anempty/null statement in Python is go pass (Cover (i) the order of statement execution in the form sitap to bottom, is known as construct () repetition selection tion of fasequence ——_(@) flow thie Jj the construct allows to. choose. sistements to be executed, depending upon the result of a condition. (6) repetition (@) selection (sequence (a) flow 5 The construct repeats a set of ssatements a specified number of times or as long as a condition is true. (@)selection _(b) repetition. (0) sequence & Which ofthe following statements will make a selection construct ? (ait (i) if-else (4) while (@ flow (6 for 7 Which of the following statements will make a ‘petition construct ? iit (0 ifelse (for (@ white lnPython, which ofthe following will create a ina compound statement ? {colon ()Satements indented at a lower, same level (indentation in any form 1) O- —————_ 0T as Questions 9. What signifies the end of a statement block or suite in Python ? (0) A comment o) (end (A line that is indented less than the previous line 10. Which one of the following. if statements will not execute successfully ? (@ 4f@,2) (464, 2) rint(°Fo0" ) print(*foo") 44,2) wie: print(“Foo') print( Foo") TL. What does the following Python prog isplay 2 x=3 if x==0: print ("am There?", end=**) elif x==3: print("or here?”, end=**) else: pass print ("Or over here?) (@ AmIhere? (#) Or here? (0 Am I here? Or here ? (1) Or here? Or over here ? (¢) Am There? Or over here ? 12. If the user inputs : 2¢ENTER>, what does the following code snippet print ? x= float(input ()) if(x==1): print(“Yes") elif (x> print ("Maybe") else: print ("No" (a) Yes (H) No (a Nothing is printed (€) Maybe (©) Error “rs tO -o) Sins col Function range(3) is equivalent tp 3) (h) range(d, 3 ge(0.3. 1) rangedi, 3,9) (6) rang se(anput(“enter an integer ge(3) will yield aq 5 ger:*)) 21, Function en be ant Saou (“eter an ten sequence like ; Faced (@) (0.1.21 10, 1.2.3) bebe ou23) a) 10, “~ 22, function rangel, 8,2) Wl yd oy ay aes sequence like tfa>@andb> ea 13,5) eae (10125) (0.5.2) alifaye print (X*) Ranction range 5-2) wil ed ay gy ifb>e: sequence lke ' at (10,86) (6) 19,7, 5) ae 16HI — wis79 prerecresy 4. Function range(I0, 5,2) will yield an tej, * praanavare : 1) © 110,86) (a) Only w 0) Only X__(¢) Only Y OR58) (18,5, ea eect Consider the loop given below ML What letters will be printed if the user enters 1 F608 thats) fora and 1 for? a ie RORY ant ame val this loop ran? Mitac tee 5 (0 (infinite) Een re 26. Consider the loop given beloe (@Wandx — @)Xand¥ (oY and z for i inrange(2e, 5, -3) @XardZ (Wand z Print(i) 16; at eter vill be printed ifthe user enters 1 ‘HOW many times ll this loop run ? fora and 0 for b? ©3 2 @1 @inin iad x WW XandY (and 2 2% Consider the toop siven below @XandZ —(e) Wand ford inra : 4 inrange(a) : What eters vil be printed if the user enters oe “1 fora.and = for b? What will be the final vatue of y Will be the final value of i after this lop Mone 6 OO¥X ony io 1 @2 ws 1 Ware. OND ters are printed 28 Consider the loop given below re ts 8 Benerated when the fy for "mel 0-215 ecg 71 ction tees) 1, I 2 ae Diseagy en (6.16, 4,2) ‘What wil be the final value of after this bop? a © 16,4,2,0, a t) 5 Python > Rees Ets the hiase ex nee for © whe (©) an iterable sequence Osoita nil a range ) func e value 1 iCcsg 'e() function (c) a single val (@) an expression a w and 3 on and or 4 The repetition <9 ‘Three const * control ae - inPython, — 1. Anifelse te two success 2, A for loop i 3. The ranget A. The for loop executing th DRECTIONS Inthe fotiowis Mark the con (8) Both ©) Both © Ais @) Ais are toe ae falling code segment i 31. Whats ‘ Linrange(2, 4) cathy ~— peiee() a0 for satis) are printed when it executes ? Sin eee) * ws ose: emit sant print a) Bipea @s Os @io wie FALLIN THE BuawKs et statement forms the selection 6 An t hi : 7 operator tests if a given value is Se satement is @ do nothing 7. Th citementin Python. contained in a Sequence or not and statements for the’ 8. The twomembership operators are __and 2 Paton construc in Python, _ «Tee constructs that govem the flow: of 9 refers to one repetition ofa >. i ands: and 10. The _— lop iterates over a sequence, Wil f ~ « ntython,___— defines block of statements Wil | i) }— TRUE/FALSE QUESTIONS «anita tet es numberof contin than | 5. Therange( function can nl be uae nr two successive if 6 Am ifelifelse statement is equivalent to a 2 A forloop is termed as a determinable loop. DposiedfStAfement The range) creates an iterable sequence 7. A for loop can contain another for loop in it The for lnop can also tests a condition before executing the loop-body ASSERTIONS AND REASONS DIRECTIONS Bee esis ee state k the correct choice as = {@) Both A and R are true and is the correct explanation of 10) Bows A and Rare tre but Ris not the corset explanation of A Ais true but R is false (or partly true) wel | @ Ais false (or partly true) but R is true, (o Both A and R ar fase oF not ally tre cent of assertion (A) i followed by statement of reason (R) won. The sequence construct means that the 1 Assertion Python's pass statement is nm Rea ‘Statement. statements will get executed sequentially Renton, An empty statement does nothing. 3: Assetion, FYE statement “if represents ‘seletion construct. means the Reason. The selection construct Von of a set of statements, depersing ‘of a condition. 2 Assertion. The flow of control in a program can occur sequentially, selectively OF executi 7 ‘upon the outeome GIRTON 03 -¥ Ue poeu nok 0s.) supa £09 > 9908 asta Goi-vue yoa POA.) usd peu => 69 s119 De MISE ebsTeEA eae! Lipo Ams on aura 406 > 296.8 => o@ jt Gi + vue saew..) aut #6 = 9peu8 yy 9863U9>,ed apeu8 ava s\xeu1, )andut) 3201 = apevB 3 (Got ‘0) a8ued uF ¥ Joy ‘nate PayHEH STDSLIO9 ia ‘cjg uu peo Papua gy ‘wonnyos GiASsTenb 09 -y Ue paau nok “Ass0s,) gurl £09 apeud asro (ov ue 308 994) sunud 2 ape.8 > 93 st510 Pood A tead st yu, , .) 3urad 06 < 996.8 < 08 35 G+ vue s3eui.) aupad jgeion ue azinbas yoqyon ‘sd days “04s suusiantae oy 19Nq qua: “uon>e jo pury Aue - v5 > ine (TRUE = solution yh (input (Enter nunber')) @ for 4 in range (2, N41) 142 print (sum) Pep 7 mse the follwing Ryton progran be nt(dnput (“Enter N fms sun = fi for 4 in range (2, ") nine ° print (sum) {b) What isthe output ache the input wale i Solution. (@) 6 (8) 0 A Wrtea program to inet three mumibers ay the largest sullest number. Solution nud. = Float (input ("Enter 1st nunber una = float (input ("Enter 2nd number: ")) ud = float (input (“Enter 3rd nunber: °)) 46 (um > num) and (ound > umd) largest = num 14 (num2 > nut) and (num? > n4n3) Carpet f pales enter ist nunber: 45.2 kn tnter 2nd numbers 66 largest = num3 Enter 3rd number: 11.56 ‘The largest munber 15 66:0 print("The largest nunber is", largest) 3 “rae SU Rar aaah eb wc larson agi led SI a Shas SORA fiar 08 we ater 9) saat wo Co prittrtanes ences digse abe ior wet eres pall fred + mum 7/300 eufi 2 = ints 3 160 ifn nt2 » int // 100 3 = int2 100 Print("Three 2-digit runbers are:”, ni, n2, 13) Enter a 6 digit number : 678923 Three 2-digit numbers are: 23 89 67 10." Wee aprgram input a nuniter and then print its frst ad last digit raised tothe length ofthe mumble nuriber of digits in the number is the length of the number), Solution. import math fun = int (input(*enter a number: ")) Ten str(nun)) # Length of the number 1/ math.pow(28, 1n-1) 1) hum, "is", In) Print("The first digit is ", fst) Print ("The last digit is”, Ist) print(*First digit raised to the length :*, ath. pow(fst, 1n)) print ("Last digit raised to the length :", nath-pow(1st, 1n)) Enter a number : 326868, Length of given runber 326868 15 6 The first digit is 3.0 The last digit is 8 First digit raised to the length ; 729.0 (ast digit raised to the length : 262144.0 Wire a Paton sriptto print Fibonacci sere’ frst 20 elements, Sone tia elementsofa Ftonac series 0112358, Solution, First <0 Second = 1 print (first) print (second) for a in range(1, 19) : third = first + second print (third) First, second = second, thind « wet number fromthe 10 numb iWeite #7 input sitton. i to Find Lowest and second lowest integer from 10 integers feail = smadler = @ gor A in cange(2®) int (nnart ("Enter number :")) ifieee # First number read small = euftined 4 second number read ifn <= small sealer = 9 else: smaller = small snall =n else: for every integer read 3rd integer onwards ifn < smaller small = snaller smaller =n elif n < small small =n print("The lowest nunber is : “, smaller) print("The second lowest number is: ", small) run of above program (from the ten input numbers as The sample <6, 13, 22, 3, 45, 18, 99, -4, 11, 23) has been given above Write « Python script to generate divisors of a muaber, Solution, on = int(input("Enter an integer :" )) seid = num /2 print ("The divisors of” num, “are for a in range (2, mid + 2) if numa ==@ print (a, end = ° *) print ("-End~ Input three angles and determine if they form a triangle or 10 Solution, ‘check triangle from angles ‘anglet = angle2 = angle} = @ anglet = float (input ("Enter angle 1: ")) angle2 = float (Anput ("Enter angle 2 : “)) angled = float input (“Enter angle 3 : ")) if (angles + angle2 + angle3) == 180 * print("Angles form a triangle.) else: Print("Angles do not form a triangle.") ud as na jmapur, leat sr Bowrowe sms ] Par mH=uD OFAN | jouonsAnN # asta ror Na Ksrt0 ite (ava *,: aunowe 13, )autid (Wi ‘5 squaurTeasur 40 saquny (M49 (DY) 1 (Nos QW 1) 6 ah g a) = 20 S}uOULTeasuT 40 oqunu aun w23U3, )andut)auy = y ISBIOUE Jo 2304 Arynvow $ (00r « 2)/ a= (Ci uuue wad asovenur 40 2324 saaua_)andus)aeoty = (Ce Shunowe pedyousud ueaus, W SiuMIUTeSUL ATUAUOU! Jo roquuRL 2k P aq pinoys ayes 3s EE SL Jauod oy, 02 » £ £(u) Javod aya soa © 20 9vaqunu 9A.3 180d © sou (aeak deat © 300 ST, (utah deat sums aydures, OMAN mace 1 Fiow mr print(Moxlium of ruber enterey ite 0 7 20. Whites pram tft the rae of student he wAne("hiniaun of onbere Genes NeMy wei rie eae as he ne ble el print(*mini meers eter solution 8 s Sample run = st | enter a number :5 bererey [ Atove so enter a nunber :3 mane | s0% 10 90% enter a nunber :7 een 7M 10 80% Enter a number :2 a | enter a number :1. yrint (* (40% to 70% ° | of numbers entered : 7 taxioum eC) (Lieto an, Minimum of nunbers entered : 1 ag Percentage of th marks stained bythe student is 5 Writ #7 2. Following code contains an endlessly, Jtion, Input to the program. 2. Foll E P. Could yo, solu! Sie find out hy ? Suggest a solution pine" marks = float (input(“Enter marks : ")) pa fora ie ( arks > ans eae — wien >) i ELLE marks >= 80 aswer = answer +s 3 rade ere, print (answer) Cee Solution. For a while loop to termina, Pieter necessary that Its condition become fae a one point: But in the above. eode the we test-condition of wile loop will never beam grade = 2¢ false, because the condition is n>0 and ws Prine( For ranks", marks, "the Grade is", grade) always incrementing ; thus m will alway, Sample run remain >0. Hence it wil repeat endlesly, te. There are fwo possible solutions: c Enter marks : 90 (9 change the condition to some reachable 2. Write Pyth For marks 90.0 the Grade is a limit (as per update expression) 2g, ewcar ane: ap) ae while (n ¢ 108) For marks 80.0 the Grade is B (i) change the updation equation of es variable so that it makes the eondifion ja Enter marks : 69.9 at some point of time, e. For marks 69.9 the Grade is p white (n> @) Solution, " Write program tht pris ninun ent a. maxim 0 fie mane ened gh, Solution, 23. Write a program to find the sum of square of st number read ‘First 100 natural numbers, n= int(input (“Enter a number Solution. Pato Ssum= 0 for ta range(4): for num in pange(1, 101): = Amt(input ("Enter a nunber :*)) Sum = sum + nun ond ifm n I Sum of 1st 100 natural numbers 1s 5050 int the First‘! multiples of given numb fneCinput("MU1tsples upto? (n) :°)) Grin retest, n +2) wetptes upto? (24 ° t= at num First 4 multiples of 6 are: print(mal, end'= ",*) 612,18, 24 = ined | | Whee program to print only th 2 " nnbors from a sequence of numbers: (0,1,12,35,813,21,34) l print("Even nusbers from the given sequence are:") fora in [0,1,3,2,3,5,8,23, 21,34] sfax2 print(a, en print() Even numbers fron the given sequence are: d 0,2,8, 34 2K Writea Python program to find those numbers which are divisible by 7 as wll as by 5, betocen 500 an oth included) Solution. print("Nunbers divisible by 7 and 5\ between 508..700:") sae omse (520: 702), Numbers divisible by 7 and 5 between S00. .700: See ne 5 '=*.6): 525, 560,595,630, 665,700, print(x, end = ",") eh oe ole N aie print the result Ef > Wie Python code ton the odd numbers up to and including) Sehiion N= Ant (input (Enter number')) sum=0 é ina while {ce N: inivz print (sum) % Consider the following Python program N= AntCinput (“enter N 2" )) fen sum =@ while don Afik2==0: sum = sum + 4 feted Print (sum) . (4) What isthe output when the input value is 5? (0) What is the output when the input value is 0 Solution. (@)6 (by 0 TOMATO Consider the fot ate su umber = int input ("Enter number*)) 2, result’ number, 1 ing Python program intend ti while True oF n i result = resuit +n f rint ("sums =", result) 2) Wht happens wien the user enters a value of5? (4) How “olution. The problem is that the program will re The problem lies with the condition of while loop Correct condition will be any of these while n or whtlen > @ "would you fx this program 7 this condition will never go fats. mate rogran to count the mumber of even number which ae agp ultplsof6 in the range 10.100 9 ‘mumbers included), Solution, count = @ for x in range(20, 101) AF x2 count = count +1 Print(“Count of even numbers multi Ples OF 6 between 30,.100 45", count) 31 Write a program to calcdae the sum of odd muners divisible by 5 from the range 1.100, Solution ssum= 9 for x in range(, 101, 2): AF (KES =-0); Prank (Sun of od os. divistbeS betwen 1.100 is", sum) Sum of odd nos. divisible 5 between 1..100 +s soo Enter number :3 © White a program to print the tbe ofa siven munter, The autos ‘umber as to be entered by the user. Nat Solution 3x309 intCinpue("Enter rumben :*)) 3x4-2 for i Amrange(1, 11): 3x5=35 Print(n, "x", 4, *=*, (n+ 4)) 3x6=18 3x7=21 Given a sequence of numbers 1, 7, 5, 8) Write a program: that prints the 3x 8-24 Hite st element in line 1, sum of15¢ te elements tine oe of st 3x9 227 three elements in line 3 and so on 3x 10-30 sum 1 for xn (1, 7,5, 8): A unm = sum + FS print (sunm) 21 = 100 he beginnikg NCERT Chapter 3 “ i fddfe of, Ans sm=05 avg=0 while dc 3 num = int (input ("Enter a number :")) ieis2 avg =sm/3 print ("Average of 3 given nunbers : ", avg) 0 Wha isthe differen i a ‘Ans, The else clause gets executed when the condition tested with if is false. The elif clause tests another condition when the condition with if is false, (@) for 4 in range(20, 38, 2) print(i) (country = ‘1norA’ for 3 in country point print (sum) Ans. @o or © 2 2 x 2% . 26 r 2 A GLOSSARY Bock ‘A group of consecutive statements hoving some indenation level ae The block of stotements in @ compound stotement that follows the header lmpry statement statement thot appears inthe code but does nothing ‘inte 120p loop thot never ends. Endless loop hermicn Stotement.Sjtement thot cllows 0 sot of insucions fo be performed repoctely ‘coping Statement erciion statement, Also called 2 loop, te Some program-construc! within anather of same pe of * Bloc 0. ane(input( “Entor'an integer:* y) fora sn range, n +n) print (a / (1/2) else print ("Now quiting") py n= ant (Anput( “Enter an integer: *)) ifnre for a in range(1, n +n) print (a / (n/2)) else print ("Now quiting”) predict the output of the following «vd forxin(1,2,3-4.5} print (x) (® for x in ranges): print (x) (0 forpinrange(t 10): print (p) (_forqinzange(t00, 50-10): print (q) (@ for 2 in range(-500, 500, 120) print (2) () foryinzanget500, 100,100) print (**" @ x=18 yes for 4 in range(x-y * 2) print ("%", 4) (h) for x in range(3) for y in range(4): print Oy x49) @ co for x in range(1): for y in range(s): ceed print (c) Rewrite the following code fragments using for Soop 1-160 while (4 > @) : print (4) ina 183 (Oy sntte nun > 0 4 int (oum % 10) um = run/20 (© white qum> @ count += 1 um —= 2 AF count = 10 print (sun/#loat(count)) break Rewrite following code fragments using while oops @ nin=0 Af nunc 8 integers fron min to max for 4 in range(min, max + 1) () For 4 in range(a, 16) iFixa--0: point (3) Predict the output of the following code fragments (a) count =0 while count < 20: print ("Hello") cunt hile x> y: print (x, 9) k=x-1 yeyed (9) _keepgoing = True x=100 wihite Keepgoing print (3) x2x-10 1x C50: keepgoing = False xa hile x < 50: print (x) JOCK OK Suir beginning riddle 6+

You might also like