0% found this document useful (0 votes)
23 views43 pages

CS TBK Class 11 Chapter 8 Flow of Control

yes

Uploaded by

tankerlolguy
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)
23 views43 pages

CS TBK Class 11 Chapter 8 Flow of Control

yes

Uploaded by

tankerlolguy
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
You are on page 1/ 43
In This Chapter 8.1 Introduction 8.2 Types of Statements in Python 8.3. Statement Flow Control 8.4 The if Statements of Python 8.5 Repetition of Tasks — a Necessity 8.6 The range( ) Function 8.7 Iteration / Looping Statements ‘executes its statements from beginning to end. But not many programs ents in strict order from beginning to end. Programs, depending upon to execute one of the available alternatives or even repeat a set of form their manipulative miracles, programs need tools for performing and for making decisions. Python, of course, provides such tools by providing {s0. Such statements are called program control statements. This chapter nents in details. Firstly, selection statement if and later iteration hich are break and continue. some jump statements of Python w! any kind of action, be it data nts form the smallest of the following to the computer to perform be it repeating actions. Stateme! tements can belong to one a As you can make init‘ one single Vine ate 3, Compound Stoterne A compound statersier statements executed statements of Pyther ‘as shown be ccompona sustener” ndented body staple and/or com That is, a compound stat in those instances: @ a header line Python does nothing and moves to next statement in: the flow of control. A pass statement is useful i where the syntax of the language requires : keyword and end i the presence of a statement but where the’ g body consisting fogitof the program does not. We will eet: = staiements, 2h in loops and their bodies. 2. Simple Statement single executable statement is 4 simple’ You'll learn about sore Any statement in Python. For example, following is : statements (if, for, fa simple statement in Python : : 7 si name = input ( "Your name” ) ‘Another example of simple statement is : A compound statement with a colon ( :) and a body « print ane) print function called: snemens atte sare ev ' 83 statement Flow Control “ “ina progam statements may be excited sequential, wlectvely oF rails Every progra ort TM dee pn pela ai selection or iteration. et suse what is meant by Sequence selection or iteration constructs Sequence. ‘The sequence construct means the statements are bei being executed p This represents the default low of statement (se Fig, 8.1) zi begins with the first statement of program. Each construct). When the final sraterert | Figure 8.1 The et construct on of statements) dependit ation fing upon a condi Siu abet fata) forrest ys ) if followed, This construct (selectio" ote decision about which set-of-sta! 8.2) explains re isted, then c ight is yellow if the signal light js ‘many such real life decision-making, coping) ts mean repetition depending upon a the time a condition is depending upon the ements are repeated As soon as the es False (or True), the The iteration construct 1g construct. (Fig. 8.3) illustrates examples of iteration or ou. For instance, you often see chapatis or dosas or appams for does for it: Every pr ig of CON default mode) constructs. that supp? create pros Condition 9 Fe } { [ Statement } i Which the execution or exit of the loop depends is called the exit condi so pro’ Pyinon! 2 sections Coming Seerervetection and for and while ts = af that SUP - rt iteration: ams as per your 229 ' ‘One course ction | [stant lsu] 7 | ' De 1 = The selection construct. t co, The ext condition | Tue Statement 1 | The loop body Statement 2 The iteration/repetition construct. ts that are repeated again and again is called the body of the loop. The tion or Repeat the adjacent process (steps ( (ii) for next chapati/dosa/appam. This is looping or iteration. ‘or dosa batter on flat pan or tawa (iii) once done take it off You can find numerous in your real life ¢ colouring book ete: ete. pgramming | natructs as the se ) is ina other examples of repetitive work | washing clothes ; colouring in language must support these three .quential program execution the problems we must solve ts that support these these Python idequate to the ement wides sta discuss sports se! Maing these statements you can COMPUTER SCIENCE WITH pry, on 4 jon. 8.4 theif Statements of sl suatements in Python and these implement sete, sag ‘The if statements are iS constructs (decision constructs): . if the condition evaluates 10 frie, a COU EOF. 44, tement testa particular cond? ee inexecited. otherwise (the cong is followed ic, a statement OF , evaluates to false), the course-of-action is ignored. that you recall what sroceed, it is im Before we proceed ll that will help you form COM ition you learnt in Chapter 7 in relation ditionals in this chapter. Also, pley - be we are using!rH¢ to refer to Boolean value True as well as tryy, nom ail iy similarlyflse here ‘will refer to Boolean value False ard truth yy oat collectively ; 8.4.1 The if Statement ‘The simplest form of if statem carries out some instructions and does nothin, ‘The if statement is a compound statement and its syn| if : aaa } The statements inside an if The statements inside an if are [statements] indented at same level. where a statement may consist of a single statement, a compound st ere ast : statement, or just the p eee ees pound statement, or just the pass look atthe iti Carefully pee it is also a compound statement having a header and a boly For ‘ f eerie ae illordng code fragment spaces += 1 ~ chars +=1. |— Body of if. Notice that all d s the statements aie ay ie se roe ion evaluates to true it ent tests a condition and if the conditi gin case condition evaluates to fal tax (general form) is as shown below it, if the conditional és “expression ia fice evaluates to true, 7 Hl ches whether uted, otherwise ignored. Nore “Not ; if it does nee Naracter variable ch ‘Indentation in Python is ve" kl? re the condition ch==' ' — '™portant when you ave vss? Tisai @re incremented by 1 O™PoUnd statement Makesu® ner in variable chars) are Re to indent all statements in 0” block at the same level. tes t0 ch does not store ' a space i, PP oman ition ch= =" ° evaluat getting Input th eh, con 1 compares its value ) if value of eh falls between & on evalinates to tue, and thus it will execute the statements in the Ifbody ‘message saying "You enter digit! example that usew (wo if statements one after the other a single character ;') I this condi following if entered a space") ches'9': entered adigit.") maple reads a single character in variable eh, If the character input is a space specifying it. Ifthe character input flashe age specifying, it xxample also makes use of an if statement (Enter First integer :") ) (“Enter second integer :") ) and B< 15: * (AB) result 1s", C) joven”) -———— Higit, This statements not part of if tater dat tho same level as that of boty of if statement print 6 aan if statement with two statements in its body I ‘a look at some more examples of conditional expr # comparison with a Literal did well") # comparing two variables (’Ahas more than B has") # testing truth value of a variable fe i has truth value as true") you can see this message-") about truth values and truth value testing in Chapter 7 under section 743A ‘as it will prove very helpful in ¢ a look at section 74.34 on expressions: test condition : not x will retu value as false ‘this time") again en True when x has a truth value as false only when ¥ fs fst jas ane False when x 18 Fie ui ‘will do nothing if the condition ‘evaluates to false and if-statement, ~ =0: Print (a, "is zero or a positive number") else: Print (a, "is a negative number") For any value more than zero (say 7) of variable a, the above code Will print a message lie 7is zeroora Positive number And fora value less than zero (say -5) of variable a, the above code will print a mes: ~5 is anegative number Unlike previously discussed plain-if statement, which does nothing when the condition reals into fase, the if-else statement periorms some action in both cases Whether condition is ine false. Consider one more example : x if sales >= 10000 : Note discount = sales * 0.10 An ifelse in comp else : Successive if statements discount = sales *0.¢5 ‘number of condition-checs i, else, the condition wil The above statement calculates discount as 10% of sales OM In conas toto amount if tis 10000 or more otherwise it calculates discount he” as 5% of sales amount, ——— Following figure (Fig. 84) illustrates if and if-else constructs of Python. ' + (o) Figure 8.4 (o) The f statements operation (6) The tf-lse statement’s operation. WY this Knowledge oy is ROME Programs, * mip BPH WMS MEME dn a BNE Homber is over oy 0 Mnpat ot and ») OC al a | Alterna (“Enter an integer - AES EVEN number») 6 aa ‘umd Ane tnpue( “Enter number a | RUR2= AntAnput (“enter number 2 : “)) Tahoe Po | Num3 = int Cinput( “Enter number 3 *)) dolow, | sum ca ‘Um + num? + nun | Ff numa 1 num and num t* numa Sum2 += num Af num2 t= num and num? t= numa OR Cove Sum + num BeBe three Integers ond pring | 4 UNS 1 nUM1 and num3 | numa the three, Make use of only if Sum2 + ums print ("Numbers print ("Sum of thre e", num, num2, num) ven nunbe | aaa | print("Sum of non-duplicate numbers a a TEnter First number :")) |" repair « “Enter second number :") ) bohepetrat. PEnter third number :")) | Sunt» sun2=0 | numa « int (input("Enter number 1 : *)) num2 = int (input("Enter number 2 : ")) | num3 = int (input (“enter number 3 : *)) | sum num + num2 + num 4 num == nud : Af nun3 1 num | sum? += num else : 4 num == num : sum2 += num else | if num2 «= numd = Sint fiputs three numbers om!) a Sums as per this | ag ; | ‘sum? += num + num2 + num syumbers are®, Numi, fund, 1UR3) sum oF three givennunbers 15°» $4) plicate numbers 15", sun2) numbers | print Beet woocuplione | rane’ se faat inp (“FiTSt ter t( “Second ~ me dapat ("Third mmrer "Fourth mer + ig meme for calculating area of a circe or perimete ie ern "atte ofthe circle “)) Calculate Perimeter”) igs int (Anput( “Enter your choice (1 or2) :* ) ice ==1: eae = 3.14159 * radius * radius of a circle Hus, "1s, area dius, is’, pera) Area te Perimeter jee (Lor 2): 1 With radius 2.5 is 19.6349375 - RESTART eee the circle : 2.5 ‘Area Perimeter ce(lor2):2 Fle with radius 2.5 is 15.7079 of if statement can be a ational expression or a logical statement false). The if statement is a compound statement, hence art of it must be indented below it. —_ if runs are more than 106 need to check another ‘then it is acentury Whe test-condition of i elsedfruns are more than 50 That is, you want to then it isa fifty when control reaches estin the form of Pree batsman has neither scored a century nor Fifty this, consider this given earlier, where we have used if inside another iffelse. 2 above iz, in else if form (or if inside an else), Python provides if-elif and “The general form of these statements s pssion> : ak if + statement [statements] else: statement [statements] ot program 63 using i6-elif-eise stssemercs Misomsced forms of f are met exwmgh. You muy reed to teot additional jstaations, Python also supports nested f form of if in elif's body or is ite dist’ s boty + = 2: rate = 0.05 Butif you name the conditions separately and use ther later in your code, it adds to readability and unts standability of your code, e.g., ‘eligible for_5_percent = deposit < 2000 and tine »=1 eligible for_7_percent = 2000 <= deposit < 6000 and ie eligible for_8 percent = deposit > 6000 and tine »=1 eligible for_10_percent = time >= 5 Now you can use these named conditionals in theaute* follows : if eligible_for rate = 0.05 elif eligible for_7_percent : rate = 0.075 _ f os" You can use named condi statements to enhance rea reusability of conditions DECISION ‘p Con: 5 gi +iP ees Progress In Pyto This cs sayié rae in Python’ session is aimed 3" : of decision constructs. ee a 24 5 WI AP atis/d for this task hy here y, as faye Ned to repeat same set of tanks ow spam" at home, as mentioned earlier, Would you do that, ‘OM a prepared batter, S/appam fp, ly the dosa/appam batter o, some second after some seconds, n the heate a he heated flat pan. after 20 seconds write at the place of ????, so that it starts repeating the process again there is no number associated with steps, how can one tell from where there is a label that marks the statement from where you want to repeat lay send the control to that label and then that statement onwards, d. That is, uisites : prepared batter flat-pan “ rf, batter on flat pan the dosa/appam after 20 seconds the dosa/appam after 20 seconds v ¥ it off from pan y 1 want more dosas then to Spread flows ars show hw te coma oer \ MN BEI ER SCIENCE ry, om ” 9 YOU a0. ty n th case above Prerudocon, sate ~ A 243 ica the Py s discuss the range( ) function of d with the Python for loop. The range () function of Python generates a list equence type. A sequence in Python is a succession of values bound together = rings, lists, tuples etc. (see Fig. 6.5). There (sequence types also but those a fs scope of our discussion. ee Coneains _ he Ss SD) toma eererts Hf ou ee 4 iy F eee Ae Atuple form range(l, u) will produce 2 g ig being integers). Please note that the lower limit is included in the list but Yincluded in the list, <2. — tee defekt sey vai in vals O123,41 in arithmetic progression (a p-) that begins with lower limit 0 and goes Lie, 5-1=4 —— defen sep-saloe = -4 ) produce mumnbers increasing by value 1. What if you want fhevlog gap other than 1, cou want to produce alist lke [2,4 That is, function range(1, u, s) #1, wand s are integers will produce a list having values as I, 1+, 1+ 25 ...<= 4-1 range(@, 10, 2) setae = 42 will produce list as [ 0, 2, 4, 6, 8 } NM range (5, @, -1)¢—————_ rvair=-! will produce list as [5, 4, 3, 2, 1). togeth Another form of range( ) is : Pe range() — that creates a list from 0 (zero) to ~ 1, ¢.g., consider followin: range(5) The above function will produce list as [0, 1, 2, 3, 4]. Consider some more funetion : 0123,4,5,6, 5,6,7,8,9 345.6 581114 9,8,7,6,5,4 lowes Operators in and not in Let us also take about in operator, which is used w To check whether a value is contained inside a list ith range( ) in for loops you can use in operator, ¢.¢ Bin | eemeceee This expression will test if value 5 a (,2,3,4] eee 2 = will return True as value 3 is contained in sequence [1, 2, 3,4]. The In operat 5 in (1,2,3,4] aiven values cot a tras Sienot contained in sequence 1,2,3,4).But "rave x96"? Snot in [1,2,3,4] —— ide? check for membership of a valu y ‘ib ‘operators, These operator """ te. For example, consider followins “ g type) “trade”. following code that uses the in operator : LT yt( “Enter a line :") a “ Operators in and not in are also ememeaneistring :") called membership operators ipline £<— 1 an ring i part of tne string, “is part of", line.) ring, “is not contained in", line.) make out what the above code is doing — it is checking whether a string is line or not. uw are familiar with range( ) function and in operator, we can start with Looping Statements ‘statements or repetition statements allow a set of instructions to be performed certain condition is fulfilled, The iteration statements are also called loops or ts. Python provides two kinds of loops : for loop and while loop to represent fo s, which are : the loops that repeat a certain number of times ; Python's for loop is a counting loop (or count-controlled loop). Joops the loops that repeat until a certain thing happens ic, they keep repeating as long as some condition is true ; Python's while loop is conditional loop. before executing the loop-body, i.e., before entering in the loop, the loop is Joop or pre-condition loop. And if the condition is tested after at least once, it is called exit-controlled loop or post-condition loop. To see on is designed to process the items of any sequence, suchas | k owp ecton ne by one. for loop is as given below = This determines how mary sm dhe lop wil get repeat > in : +.. ts_to_repeat .. Colon is must here om here the statements 10 be repeated wll be placed (bexty-of-the loop) r the following, loop : ri This i the boaty of the for top. Alt stews on bale bolt a he eT value of loop variable a, L¢. firstly fora ot: then for a = 4 and then for a=? courte scr, 197 Pro te eh raters mete, Seof our noes? Sum of hatural miners an of atu noc = Seacetnevrst nace ser io Ee er The ep re cena Neer nr otetaac ip eve. as oes tons with sl as gs The general form Python es the resul of wa true Thin eatement of loop-boly apa, Joly when the lil expr cates I igexcoute) Conese nse a us the oop by testing ncion ry Bod-o6tbeL00p (> et op “ fat a executed Tepstely 1s le oop, beore every ese ime gen ascent fact tate @ silo. peat ES oF hile oop | Progra ate given below oop variable must be peel wie Peale in way tat ae one comes fase others an endless loop Fini incre th counter leven integers 15", sa.) odd integers is", sa.) above code | as eres eta aor cote (howe Lint, per iit) I fo impor rion 0 {icone torn ren ante st Tre wing en cme ee Jor conto: q 259 Tiemann. ey leans = Thonn ep Earner print (ater eens a B15 = Ian to ete sre nats . = ah. Fe Creer cat, ae cae sectarian ase cer ner Pisa prime mater Ger aster 28 (isn a ime renter nd this, consider the a igs times. er re Gc wil price the ibe withthe hdpotowe moe camps of oop ale nested ao tse oop, Thefolowingseancraniea sorasnrnesa) : ‘orb seraeeS,7) ae Dros “The above reed op wl pts loving stp pforas0 bem is6 forest beets Foran? broviss fora? drois6 cr re snp sty eae 80 208 (00 np vines otpu vn above ae produc ry Tasch iis Herons ine op te ex ae sequence the ner wll gain ert ‘Ths me that fr ch etn ute opine op erates me (Genser some more examples nd Fanconi based on above Ln factor 39 for fora inrange): Btacrore 2) for 6 forbinronge(s.7) ees ana) pein () ‘Te cutpet produc would be iP roses In Pthon 8:2 sof nent ee? Fe id in lv forainrangeQ): ed of ths chapor i ‘orb inrange(s.) PrIRE (end *) ¢ rs print) x iirc gen ene perf oy i aon eb on ne of rep se eo np te tha eh Pn pe en semen ny ee repay ete 8 met fc bho nn ot i he, wate vss ean coat he Oe sl en rhe ran appears ina nests oo, a ne il ‘ery loop iin. Tat ic ch 8 Sn csigs mein ner lop then wil a the outer oop wil cntinoe = outer lop, then eae ee [Fin Python whi fhe ftowing wi TEBE) Bot inscompound stems? (colon [Wiemann ov sng (indentation i 2 fm Wat sgn the edo. tae re a ‘ite in Python WAcoms ©) ym previous ine ofthe flowing if sates xt sicily? 60.2) print) sea opus: ENTE on ane sue OL waa ree 181 be pine i the wer es. 2 Wonyx Woy “ag ons (9, Xand ami ms, be pis if the wer ere 25 Ft sng 5,2 yi an tee BP cepac ie OW andy Xt 10.8 1 on78 MW, and ¥ | oeem warn pred be we 1 a ange 5,3 yo tet Seeate orm | “hu omen (oWwand | oe ia aeem ied ewe 1 ce ta re hat Be pe pnts ann ha a wt et mi ye pape ant ‘Scrap wen hopent “Tautpiase Quesmons frum of conn than ht stmt i ave a de a ‘pcan he ne use ‘The ee de op sted oy Te came ie Kany ih el ne eae JS hen ep rane ma so Qnoprthan de nse cae be sernt eee el ae 0 yg ‘ The fot op i 9c works with sence fv he EAN) Fin ena, oll pe 2 Both Bresk a contin on sp Ihnen sti mc met (Daly while tops cin ie bat x any Kind ofa. utd 1 a funtion 2 (Criealy”) DB on ft io. The loops arable wile pnt ean! tobe an tre gec ater gas eu roy th rc 0 ns ru roy te ran vite by ie) 50 re renames sh ok l gs on eo rane(s = 10) is Fat (ret Mat thee percgs *) Corry, yu eed to 7) Ce sgn lori erin en ob 3) uc cease oe cen rms a0 Bee gary saizme teeter tal ™» aun) prime Cec, ame) ase frie Cw 18 fn ‘Seton. ea es tigre ms 00 fins Ptr ron ne Se nae , mee ~ 1/108 Totes a bes om tte ith ve a a tnt 98 feptio : Bean | restmebagt iat Meat wil be orites “Code wit print j I ib erm “toring een i tt he proprm| 5. Wiccan ea eto 2308 etn ft a _foinput es with the conto while wr ello 1265 ll never oe lb any af ese > iecsoqen tian mae fem mys tt) erat cman es ian ee aa a 1) = | fhincne tata e390 Finca ten), emer aa 3) | Femi tg rset eat) >) | Shae de athe it mie 9" alieN end po center mater) ese eum fiat er sand tote Teg TH. 0 er va tetera Ste wet ter Be eee i ty fom ron ages ec: prorat ist nes bers nprEoer see") | inti meson nas" Hiieatreter ele?:"Y) | Tersncen ty dopant") ae args) == 388 s oem, fore a erisnge.") ae oot fom a triangle") |) sat 10 mrsene nates a apt integers x ond |) 2.3738 316827 255530 | ” | 25. witeryen spp ening ton | sitive mate), Ns | Satna 12 ese raeet #2) pines) \ aco a pono 8 fap he aa od | hess i Peseta, “it mrtg mater”) Sotinn (A pandne manbe’s revered onde bs te mse) ans it inter abe") tenn eigen pero is ear are ‘rare a ema m slave gets veut’ When he a ed wth fs arother coon wen te onion wih wasn, freon genes on ie ewig he ann tat span eo. ts very handy ar tlt age whe nes Ses a an continue tater ae amp stakes, Whe he ek seme gs is loop completely and he ctl maces he sent nay om the other hand ermine oly he car ean fhe op By > eee exe ps the one whos ering conten ie ising ome oop keeps repsting ely an ie op Be fling program ses (ford snare, 9,32) esr) (ap carey» "OE for in oat sre) EDULE sce Pine tio a fy he frpt( “Eee naer er ner 3 anes 3) mt (emer 34g yer) Spo incor tow ear COWIE Sect yy, My, Ce) in range, 2). fe ny ge AA: SHORT ANSWER QuestionsiConcerrua. Questions ean of 2 whe op i yen? Teena ef el sn a of yon np? fe ee a of op Soe at et md? APPLICATION BASED QUESTIONS ae age at avs te ne ms tory (6 856 ery reer UTR seen es ed hh pie oe tree a rn ake an ese on pct ede are hs st ec with 8 nent with ta end wither Fauna msn cnremno Hepes hn ten eal Cte et = ot et sip ann deeb ho pit very tg me ym seven oo to un he ren sets Ties et °

You might also like