C6 Selection

You might also like

Download as pdf
Download as pdf
You are on page 1of 9
Giapter 6: Selection 6.01 The Need for Selection sytem oten need to be programmed io complete diferent processes depencngon the Inputrecived For example, on automatic door wal pen it detects that someone wishes toentarandwllhut when no presences detected Expert systems provide arshets oF ‘conclusions based on the ser esponseto previous questons.Sstomsthe these appear to bbe able to mske dedslons based on input but the elt sthat he systomhas been leg aly designed to compete a certain process based on expected input tn eytnon and many oer languages this chewed by the use of progrenming techniques known a5 F statements. ay languages aso have CASE statements mile to ‘them and, although Python does pot, youl eet be fami wth thisconsructin your exams hen prograniming yout oltionsn Python you wil usualy replace CASE Statomentswith 1f....e14f...else [see Section 606, 6.02 IF Statements ithe process fran automavc doar was writen down, might appear a: presences ‘erected then open the door others dost insimpleterms, this very sil tcading {aniF statement. The program wllned to provide a condition to evaluate presences number: ‘print (‘Second’) prime (*Pirst') Task 1 old the same output be acieedbyevesingthecondiion onumbert < nunber2? Task2 ‘The demo taschar ben reworded very ght hts Desgnasjstem tat wil tke ae put two wholenumbes.thesacond numbers these ‘rng than ters, he system wl oupat Seconds nol he cutat shold be Fs How wouldttisimpactonthechokeelagcalepeatt couthecondtionstl beresrad? Multiple IF Statements Ihe prevous example expanded to provide thi output hen the numbers are the ns singe tatement wold note sient osohe te polen Probes a Ns scanbe sheet seca same each which ends torte ingone star's 2s nthe example below. onbert = Sot Wupne('mnter first momar")! umber? = (inpa: (Eater second number: "1) poner? <= nomber]: SUsane") snuner? > aumbert: weno (*Seeend!) © umber < number: een (Riza! _Athough th approach achieves the requtedoutzome ts inficient. Consider the situation ‘Nrorboth nabs ate equal Theft statement would have produced the appropri ‘Dieu but even though te conditon nthe following statements ease, the code ‘asta erect them The algprit praduces the required outputbuttwo statements have been executed unnecessary 6.06 Nested IF Statements “Toavidtheinficency of mule Ftaterents tis poset place one ormor Tenens ently thin anche Thesecond and subsequent statement ilar be crthoua te istcentinn praveta fae These arekrown asrested statements Figure 6.04 shows how a nest F approach coulé be api to the neficiet sequence of FPettements shown in Figure 2, Because the second statement wl ony execate'fthe Craig the frst statements ase, umnecessar execution of statement acide, number} = int (inpot (Enter Firat numbers *)) funber? = ine (.syor(*Bater second munber: Sf number? <= number rine ("Bane") | munber? > nunbert: print (+Second? Deine "Piety jee how the colon in Python eplaces the THEN nthe pseudocode and tat theres na ow fo ave an ENDIF statement. When wring pseudocodein Cambridge IGCSE and vel Computer Science papers tisveryimpertantto include ENDF clases, ake sure you donot ret 6.07 CASE Statements CASE statements are considered an ficient ateratvto multiple F statements Creurtances where mary choices depend onthe value single arable Conse th situation whee 9 ver mustinput A Bor. The code is equed fallow ‘fren ithe depending on which etter as been input. The pseodocadein Figure 6.0.) ‘shows sppreach hat woud be taken usingnestedF statements ard igure 6086) Shons CASE statement. Wn peta DA tie ops TEN espe pet CTE ist fe OUIPUT meat Eu Neste and CASE) toterents Beth approaches achieve the same outcome but the CASE soterent simpler code and SSE Lo ead han the NESTED F. Homers CASE statements a not 2ualable in Python 16.08 Coding CASE Statements in Python are are statements in Python anc theres te possibly to have nested IF statements, buttetesrofacinyowate CASE statements Thee, however astructce that seaer loread than nested statements and more ibe than CASE statements avaiable to ton oogrammers Instead ofa series of nested statements, Python prograrimets Joaulduseens¢ (or or ELSEIF eee secton608)) thon {risishow the pseudocode in Fue 6.038) would look'n Py weet sept on Lerneorrect teput') vinen trying pseudocode CASE solutions inPython, ise the Sf const. G Task3 Bad ros truss: 1» Youtee ‘sxovenceot eh bb oware Pythons ats statements mre case tatemensare actualy themost fin code struct Sfescngatterent ootcomesbasedonthevalue ota srg var the the vale ae an index and 39 SEE, else construct equieseod ‘one seach and then theres are shned “Theflowchart for ested IF statements an THonchart rte eeudocode in Figure 8030 can be ini flowchart in Figure 604. ar lot forthe soltion ung CASE staterent setter pres aus nthe CASE statements aemorefiertthana ees of statement “SSetnements just o eer 2s CASEstate mets re enblethanCASE tanner? strait that ne of code, noting thes. Pt revaluation to be madeuntlthecorect ) Thsisthe same sivation asfornested alse 6.09 Drawing Flowcharts for CASE Statements ture we haveretior ie Tannen the Python solution a thus the same. The eenin Fgue6.ola The pseudocode ste bythe ie o Fgwesc4 Exam ew ple lowchart sing este F statement) and using CASE statements) 10 Programming Tasks Calculator (Optional) Gates castor tat wrsninway 4 Usereputs unter 2 Users ont eur atnecoeaars 2 ernpits seconde # Mesoyi augue ss the lawchar for this taskand gue 608 shows the pseudocode option Te following code implements an appropiate text-based Python aplication: gure 05h onbert = Ant ({npvt ("Enter Plyoe Munber: ')} fpMine etriege co maintal pein ( [iocse one of the following options: A for Kad for weolesply jeperstor = inpue () umber? = int (input (Eater Second Munber: )) £6 operator == ‘A! Dein (number snurber2) sis operator == 18! ‘print (number -nuster2) 06 operator == 1" ‘eeine (numbers nunber2) ‘print (nomber2 /euster2) ‘print (‘Incorrect operator) Ifcoded as U1 application the trace might ooklike Figure 6a Producing Sut based appliations ‘soutsgethe sylabus Ve ewe S07 Imecacefora Gul version of calculator Task 4 ~ Simple Calculator (Optional) Wirethe coder a working leit ththas aU ntatae sino hat shown ing that aes numbers with he ea cata type ater than eg. Wins: + “oparator wil nsedtobe a ob arte + oul neds separate furctn or eachoperterbttonin your cleltor These Iedtose operatar io, MoD asiequtd Fal umbers calles Phe, Faure 6.06 Pseudacod focaleltor algorithm E) Task 5 - Examination Grading System ask 8 - Improved Calculator (Optional) oateses ED spisywnarepindtaesstgusaer te runir frat sar teed be By Semperernd esc aptemen sasape | eee ae a produce a GU appcationin Python that mplerents our algo. Task 6 - Parcel Delivery System ‘for delivery ifthe parcel is Skg.or below in weight Forlocal deliveries this charge is £20; for 6.11 Connecting Logical Operators. learnt ancthen pple pope ght forms cca the Python jn common with many other lnguages,usesthelogical connectors shown i Table 605, Task7-CO, Calelator Tm Yen > ey tery wih anasto et ha {stowacudent user o= Trueman athe conaton 2ives.The veil sip iapulthe stance vee in tecarnlanaves Theemision este {alsin toes of CO, pert homes te shown Tae. cs fone clhecmecasd | 1! enoke_detacted oy Trov or Coperature > 70 Tablet pedir eds ae oeatorreniobe Tot | aceon wl be Tue terse dtc above TO istnbevetochesmants amt oc ooo ast [ae es osm eo dereelg oti | occ ilntn bray berth eon feb [bear [astro irons coAekm tees os Cada mnebsonen: {ran aflonchart and reve apreodocodenlgithm that output torte ICO fr theditance and tyecf vice np. bb Testnayuralgorthnsworkty programming ard running the code nPython. 1s foput number te 6 ral clatr pogrom is capable of performing ony one arithmetic calculation line Moxy calculators allow theusero enter a sequence ofrumbers and operators, jsleygtecorustveresut ofthe arithmetic process the sequences entered. An gl othis process igen in Table 06, Using AND to Provide Range Criteria In hefoloningcade, the conditions metifthelnputrumber great than LObut ks than. Beware of geting the wrong operator, Ung inthe statement would evaluate to tuefor 605 any rumba. exe neocon operat seed Using the AND Operator to Replace a Nested IF Staternant ‘AnestedIFstaterent is oen used to check two contons Ey [Copter ion fe sored wih sa ranibe av and Opa eA Sos fresno prs feode to execu | \When the condions ae simple, the nested statementcanbe replaced by AND. The Taloning code represenste seme condtons 5: = > cone plication he coraabve auc tenenrarbernpa St" a oR Sere Se etudent_sser <= te 30 XD_mumber » 600 code to execute ing Logical onnecos sa aie re Meese epee eral icon endofaequns by sting allopsatr incest al ‘Task 10 - Cumulative Calculator (Optional) here Bess torch peice scar bt capt faking ioatite te thnombwsord gents eu thes opr eed tse sas thebitlale A subequen operators repressed they compete the pero pation, orig and cepayngthscamulstie valu, The equlsbuttonwllend the Sue, ply teal cumulative vate and reset any vals alow a ew Sequecetobeinat, 2 Testourlgrth works by programming and unin the cleo as thon ul ppicaion, Figure 6.08 Flowchart wth and without logical connecter Task 9 - CO, Calculator Extension youd not ary doo, eure the CD, emissons rogram om Task sig comected eter | Jae Iteration FOR WHILE and REPERT UNTL ope.

You might also like