VII L 6 More On Python

You might also like

Download as pdf
Download as pdf
You are on page 1of 16
CHAPTER 6 | LEARNING IN THIS CHAPTER } | ® Types of Operators in Python ™® Assignment Operator | w Relational Operators | ® Logical/Boolean Operators Inthe previous class, you have learnt how to declare. and initial MORE ON PYTHON Operator precedence © Types of Cont) Sin Algorithm ™ Conditional Silene Flowchart © if if.else, andit, a : hy Conditional Statements in Python to perform arithmeticand logical operationsin programming. Operators are symbols that performarithmeticand logical operations on operands and provide a meaning, ‘An operator needs one or more operands to perform any operations. The valid combination of both op: operators makes an expression which returns a computed result. rome Crea) ® TYPES OF OPERATORS IN PYTHON Operators canbe of different types based on thekind of operation they perform: 1, ARITHMETIC OPERATORS The arithmetic operators are used to perform basic mathematical calculations, '€" Subtraction (-), Multiplication (*), Division (), etc. The Arithmetic operators can be further classifiedas: Unary Operator: These operators operate on only one operand, eg.,a= +100 the value ass" b=-100(the value assigned to‘b’ is-100). Program 1: Learning Computers S099551i2e, JuL @ TOI, 19:28:22) HEC Y=1 ‘Tereditet or *aicense()* for more intomat! lise variables. Now, you willlear how tou, adi 8 peony ie einapsrmaaaal tor: These Operators operate on tyyo erator eens esa cte ee “isa bi f . eae lere "isa binary erator working on ta si sinary Per a sn + Toobtain the sumof Mofthe values Value of 13+35is165 i To subtract tt ~ subtraction oe Value of 45 -35is10 er ac * _Tofindthe productotthe data Valueofe26is372 1 To divide the n ~ pivision lumbers and give an it Output in the « decimal form Value of 5/2is2.5 * Value of -5/2is-25 * Value of 100/3is3.333 I To divide the numbers and give an output in the » Value of5//2is2 integer form + Value of -5//2is-3 % —— Tofind the remainder when onevalueisdivided bythe + Valueof3iais1 pores other. + Value of 10%6is4 ie + Value of 6%10is6 ntial eS focal rof numbers Exponential calculate the power of n + Value of 2"3is8 rogram 2: ize, gal 8 2055 Pees (ena ema mL syiaeaide) tiv isie rb. Gneey ‘ape Moke oepanen re 7, asb) os nore Intcreation. ‘ Pe se RESTART: C: /Users/abhay/AppData/Local /Prograns, cette on Python37-32/CT_pages2.py sion is!t,a/b) : ult of floor division of the numbers is:", a//b) lintor the tirst valuoras the first number is:", a*#3) lsntor the second vals line Quotient er the division ist'2.25 fhe cube of the first nunber ia: 91 Sil : Output Figure 6.2: Binary Operator TRING OPERATORS hi operatic em. Python allows only two srform some operations on them. We working with the string values, we may have to pe! some oper 7 lata types. We can either join two strings or replicate a string multiple times. For these ons on string di in two strings icate a string multip| er ig We can either ts spectively. '#' operator is termed as the concatenation \catenat ‘i Mt ss respectivel in € use '+" and '*’ operators on string: i more strings. ‘orjoin two ormoré Twhenweuseit with strings. Itis used to concatenate or} , Oram 3: aa Peter cee + for nore informatio ees ee b> bettow ere your? erie Figure 6.3: Concatenation Operator ig Lani wn KiPS > 4] fied tit 5. It is also Known as Replicats, '™ operators used to replicate a given string specified times. Itis also epi <3tion Oper, Program 4: Python 3.7.4 (Eags/v3.7-4:009358112e, Jul OES oe ‘ype *help", "copyrignt™, "cred! i BS prints 335] © 2019, 19:28:22) twee #3) Figure 6.4; String Replication Here, the'*' operator is used to print the string, 'Welcome' three times as you can see in, Output above, PRACTICE TIME print(52*7) print("52*7 =", 52*7) i Solved Programs: Program 5: Writea programto find theareaand circumference ofa circle whose radiusis enteredbytheue ee See =m ane | |ExpaGat Gnput (enter the radius of the circlemy)| [ote Se bow crew jaa python 3.7.4 (tags/v3.7.4 adda 2019, 19:25:22) [use v. 191 "The circumference of the circle is:*, «) | |n win32 [peincivane aces oe enernsceiMg, circle, eae gy fccrrysiont:, “credit: f 200" for nore intorsation | | >> RESTART: C:/Users/abha' }/Appbata/ Lots | jns/ython/PyEnon37=32/er- pase. 71 inter the radius of the iscle:dt the cixcunterence of the circle is the area of the circle is: 1384.74 Figure 6.5: Program to find the Area and Circumference of a ch ircle ‘Output Program 6: Writea program to print the string entered by the user five times. van =, Sood. (Eaga/v3.7.Aro055551 22) [Msc v.i916 32 Di n, neredits" Type “heip", "copyright", 80)" for more information. a too :/Usexs/abhay/ApPDat4 ny ms/Python/Python37-32/CT pages Enter tho Stringreython | | Eyeroneytaoneytnontytacne ss Figure 6.6: Printing a String Kips <> Output a Learning Computers with jo MENT OPERATOR ‘a ssi ment operator (=) [5 used to assign a value to a var asse™ Fa ntheleftofit. We have used this operator previoy wi progr lable. It assigns the v; ri alue on its right si slyinthe programs, ight side to the variable 209359112e, guy 9: 916 92 bit (Intel) } on winge apr ey ype “heIP". "copyright", *crediter or m on. OF "License ()" for more S55 aslo # assigning the SS a alte 10 to the variabl >>> b=a*lo # assigning the g the product. of Figure 6.7: Assignment Operator intheabove example, we have assigned the value 10to the variable a’ and then the tothevariable'b’. RELATIONAL OPERATORS Product of 'a'and 10is assigned Relational Operators are used to show the relationship between operands. These operators compare the values of \atablesand determine the resultina Boolean expression, whichis either‘True' or ‘False’. Python provides sixtypes ofrelational operators as shown in the table given below: eee rc Format cen Less than. 6 False “Greater than orequalto > Le “\sunderstand these operators with the help of aprogramin Python. ram 8: ees {use of eas than operator Fuse of tess than or equal to oD 4 vse of equal to operator {ose of greater than ope! nop equal to operator use of greater than oF 6m f bse of not equal £0 9 Figure 6.8: Relational Operator LOGICAL / BOOLEAN OPERATORS The Logical or Boolean operators evaluate to one of the two states, either True or False, We u Se these, python to make comparisons. There aremainly three types of Boolean operators, .e., AND, oR, andwoy Or aC eu) as eras Per )} and and b>=10 (a==5)-> True So the result of the (b>=10)-> True expression is True (a<5)>F (b!=10) -> Fal So the result of the expression is False not not (a!=5) (al=5) > False So the result of the expression is True ® OPERATOR PRECEDENCE ‘An expression in Python may have more than one operator involved in it. When more than one operators evaluated in an expression, the Python interpreter decides at run time which operator should be evaluatedtn.3 decision is based on the precedence and associativity of the operators as explained below. Precedence: Precedence is the priority order of an operator. according to which it is evaluated. Each operato’® Precedence associated with it. This precedence is used to determine the order of evaluation of an exp involving more than one operator. There are different levels of toahigherevelis evaluated first. Precedence from high to low. An operatorbelor Associativity: If two operators have the same precedence (priority), Right” or from “Right to Left” based on theirlevel. tis termed asassoci of operators (“Left to Right” or “Right to Left”) when operatorsinan e then they are either evaluated from “te” lativity, which tells the direction of exes? pression have the same precedence. cee Let's Know More The precedence of ‘operator tells the con the order in which ‘operators should b® ‘evaluated Operator Precedence erators. When erators ae operated before the lower precedence oP a Bs @N expression contai® o then whichever operatorcomesfirstis evainatecuer dence (like *and/), ted first. the same prece operators, whichhave ic > Higher precedence oP the following expressions: uate fa Solution Solution Bee 9/2 =15*4-6/2 3. =60-6/2 ooNDITIONAL STATEMENTS IN PYTHON sa nepreous chapter, Youhave learnt about the basic eleme in nts of Python. In 2 a geconceptof Conditional Branching and the various contro his chapter, you willbe introduced | statements availablein Python, ur day-to-day life, we come across various situations w ino here we have to take decisions and take actions sxcording. Inthis case, first you will check: ? ltheweatherisclear Then youwill go out and call your friends to play. Example Ifitis raining You will sit at home and enjoy watching television or probably read a story book. Let us take another example. You need to have a valid driving license for driving any vehicle. To apply fora driving license, your age should be greater than or equalto 18, (ao)NTo bite) ero sioly i ly foradrivinglicense. Example _'fyourageis greater than or equalto 18 Thenyouare eligibleto apply’ Ifyourageisless than 18 Thenyouarenot eligible to apply fora drivinglicense. ‘ady studied about algori flowchart, le s analyse the above example with the help of an Eine igorithm and flowchart, let “orthmanda flowchart, rth Ly "apply foradrivinglicense: 2g urge. a helicenses 3 Fag nt yourageisgreaterthan 1 thenyoucanaPPi for 3 ivi nse. “than 18, thenyouarenot eligible to apply fora driving ie Computer wih a“ a flowchart for this example Letusdraw: ! HART ; sak fthe flow of stepstosolveaproblem. ; i i ition of Itisapictorial representatis Se eis oceo in apply hart to check whether you cal Flowcha le : 0 Input your Age . 2 3 Be ‘age>=18? 5 NO | / YES 5 | You are eligi sply for | cat You are not eligible to apply| | You are eligible to apply for for a driving license. adrivinglicense. | ws ee , | The > Gio < a Figure 6.9: Flowchart For Ina computer program, statements are generally executed ina sequential manner. However, attimes,thess: Syn need to change this order of execution by repeating or skipping the execution of a few statements sulix: if given condition. Insucha situation, the flow of executionis altered by the use of Control Statements. Before proceeding further, we must understand the different types of constructs/statements in progr governthe flow of the control ofa program. R ® TYPES OF CONTROL STRUCTURES Er ‘SEQUENTIAL STATEMENTS Letu In Sequential construct, the statements in tee Prog @ Program are executed in a sequential manner, where one followedby the other, withno possibilty o f branching offto another action, Program 9: To calculate the area ofa rectangle, itsareaand print theresult, first, enter the length and breadth of the rectangle say eT fare 2oxs, 19:29:20) Tse fe (anter))‘on wins? scroll fEype "help", "copy Fisheye "icense()*’ for more 30 : p> outs RESTART: :/Users/ CONDITIONAL STATEMENTS ents to be repeated till the co Ndition is true. As soonas the P andthe repetition stops gefore youstart writing programs based on conditions, itis important to understand how conditional Programmin, ois Inconditional programming, the mostimportant elementis the condition on which the decision is ae a cantonal statements check the condition and execute the statements accordingly. The conditional statements canberepresented in many forms: #STATEMENT Theifstatementis used when we have to evaluate only one condition. It Performs a course of action if the condition erauatesto true, otherwise it skips the statements if the condition evalu: ates to false, Forexample, your parents allow you to go out for playing only f you complete your homework syntax: if: Statement 1 Statement 2 ‘emember, that after the if condition there is colon and the condition body starts with an indentation of tab space. "smandatoryin Python to indent the statementsin the condition body else twill display an error \etusunderstand this: througha Python program: Program 10: Et amat fam Opts Wadow Hep "int (input ("Enter a numbe: \Jul 8 2019, 19:29:22) [MSc v.1916 Leet ane Jit (Inteny] on wing2 00: = help", "copyright", “credits' j Print ("The number is less than 200") Eipeecuse eaaianreiniarnna >>> | PRderann: c: /osers/abhay/appoata/ta Progeans/2ython/eythons?- 32/0. pag \ 28 lpeipyis Ue | ee | enter @ numbers150 | [ine’numer is less than 200 b> | es cored | a8 Output Floure 6.11: py Condition At: Displaying the use of If Cor - Sin bove, a - berisless than 200°, it output"Thenumbe Bw Deveexample,ifwe enter anumberless than 200,itshows us the outp entera number greater than 200? No output will be displayed because have not given = is, ill be displ use We : - greater than 200? No out i “erinstruction tobe followedif the given condition false. sein ay KIDS E> This is demonstratedin the following example: Program 11: 2G pin Cetngiepoendccimopemtinaimten. DX in32 Hee ‘Type PE "copyrights eit fora Ron Optom Wedow | Teer oe nicer EI, og a=int (input ("Enter a number:")) | poraseten? for to a<200: >>> print("The number is less than 200") RESTART: 'aY/Apey, Figure 6.12; Program Displaying the Use of If Condition Here, nothingis displayed when you enter anumber greater than 200, if..else STATEMENT : !t contains two blocks of statements. In case the conditional expres evaluates to true, the statements in the 'f! block are executed, and if the result is false, then the statements ‘else’ blockget executed. For example, youcan go outto play fit doesn'train else youhavetoplay indoor games. Syntax: Statements Set? else: Statements Set2 Program 1: aint Cinput. ‘a<200 print ("the number is less than 200m) | Print ("me nunber is greater than 209%) | = (U0 fa j= Figure 6.13: Program Displaying the Use of it-lse Statement Output his example, when you enter a numberless than 200, the fist part, ie, the ip In this ex 7 art is executed and you get tN* itput mberis less than 200" output, lays the output, “The numbers ee 2 aa ‘atement following the ou ente! Z ys the outpt isg yan 200° q Bris, KIDS > pai ‘else! partis executed an? | nt (input (" if num<0: arpa (Cags/¥3: 7.4: 0093581i20, 9 2 PU ciese nie tintanh Saat a) le asis, inanay 22 ccopyrignt®, "exedits™ or "1 icons is, 1925038 Acenbet) wing e "help", eared ynrearuseerrnene anformat ion. Pezsmant: ct/Users/abhay/AppData/Loca Peeve ting 7 ==10 is ive number > f ————_} Output —= ares Output .ed on this input, the program should display the number 1, (teatea program to input name of the month. Bas ofadaysinamonth, i.e, January -31 Days, February-28 Days, etc. a2: : 2. Greate a program to input the runs scored by a batsman in a mate! .smanhas scoreda century ornot. _ batsman, the program should display amessage whether bat: Se h. Based on the scored runs by the ‘sel. else STATEMENT ot serve the Sametim #5, we need to work with multiple condition Purpose, Theit..elif... else statements provide a compa goto the counter if-else construct does n ion. I. fyouwant to s, In this case, only usin ct way to perform mut according to the se bout the cheque Itiple tests ona consi vice you want to avai 2, if you have to ‘ream, iple, when you visit a bank, you you go to counter oa it cas ; eee ce aoe ee want to enquire a fora Sag aNMESPan, yougoto counter 3,andsoon- *: oo sett y “Condition 2s: state ee te / “Btementsets wet go KiPS &> Ave canalsohavethe following: syntax: syntax: if: statement set 1 elif : statement set2 elif : statement set3 elif : statement set4 else: statement set S Program 14:Writeapro; |v aearecerantnatapeemmnetnnnata =O | input ("Taput a munber to print the nane Of hig print ("™onday") pint ("Tuesday") ("wednesday") (omursday) | print ("Friday") print ("Saturday") nt ("Sunday") | print ("invalid opt: Figure 6.15: Program Displa ing the Use of if-olif-else Statement Hence, from the above example, constructs. peintrsluor) nit? couens'g Print (lesan) jit coaeeye? print ("Oran Jeni code! print ("Red Print ("invalid colour codet)] Figure 6.16: Displaying Colour Name gramto display the nameof the day according to the number given by theuser, ie at St Donne ep python 3.7.4 (tags/v3.7.4:e09350il2, i eee |rype "help", "copyright", "credits* ora |tor more information. >> RESTART: C:/Users/abhay/Appbata/lec hon/Python37-32/CT_page101.py input a number to print the nane Friday >> Output iG a itis clear that we can add multiple conditions in a program using oot ‘Python 3.7.4 (tags/v3- 019, 19:29:22) [MSC vy. 1916 win32 Type "help", "copyright": 20" for more information >> pat? counter, the operatoris sy is offering discounts On purchase of various elec tro} MPs conan ee item code to get the details of thelscounta 7 : bee toinpls nlc Goods. At the payment the purchaseditems, ¥ 10% smart TV 101 eee 15% een 102 z 5% tof 104 Laptop a een programyihich wllcisplaythetotal discount availed bya ser basedonitem purchased fPRECAP. > operatorsare symbols that perform arithmetic and logical operations on operands and provideameaningf | result > Aithmetic operators are used to perform mathematical operations. > Stringoperators work on the strings. ¥ Tie concatenation operator Is used to join two strings and is represented Dy 2 “4! sign, while replication ‘neratorisused to repeat the printing of astring speicified number of timesandisrepresentedby the’*'sign. ; | > Assignment operator (=)is used to assign the value of an expression to avariable. | > Felationaloperatorsare used to compare the values or expressions: | > : Logtaloperators workon the statements to set the relation between them. at} > a, 4 _> Trordrinwhich the operatorsare evaluatedis calledprecedenc® of operators > iy Ue aA ram. ||» oo isawell-defined step-by-step procedure to solve aprogt roblem. . esas i ic sf steps to solveapt : isa pictorial representation of the flow of steP ae > program control t Inc log, Ing languages, conditional statements cause the ati i sion. on depencingon the outcome of the conditional expresso" Ht sta i dition. tementis used when we have to evaluate only one con performed yf the two different actions are to be *'se control structure is used when either 0 din ; 'SuPON the result of the conditional expression dition. if, i Je tests onacon multi performmultiP eli, ~else statements providea compact Way t0| ~ T - SECTION -A A. Fillin the blanks. 4. Theorderin which the operators are evaluatedis called of operators. 2. The valid combination of both operands and operators makes an a computed result. ‘ 3. operator is used to concatenate or join two or more strings. 4. in Python, the flow of ‘execution is altered by the use of statements. 5. The control structure is used when either of the two different actionsis tober depending upon the result of the conditional expression. 6. In Python, the conditional statement is terminated with a symbol. COGS) ~~ =~ ttolse ©» Precedence » Colon ae se B. State Trueor False. 1 now ewe Anoperator doesnot need any operand to perform any operations. Unary operators can be used on more than three operands. : Exponential operator is used to calculate the power of numbers. a blll Sk before the lower precedence operators. | a oe we have to evaluate only one condition. statements: execution of a setof statements to repeattll the conditions" | ‘ ‘Sumit is converting a decimal remains number to a binat calculate Which ry number, He needs the operator do you suggest him to use for this task? ” 2 oo” is same as / (division), i \ b. False SX que Gl a IN some seaneonsact te tALEMENES na Program ae 9, 1 cases, yes oes f fi ; cut ne oft ; seater wi no possibilty of branching off to another s “Sequential manne fo a t : ction, lowed by one aft woe b. Sequential Gilt 4 Iterative pienstaterent TONS the following enables the execut d.None ofthese i On ofastatementtorepeattil mf! i b.Sei i ms | cantonal quential coe the conditionis true, __inaconditional expression, the condition evaluates to false, then which bi Be © pyecuted first? ich block of statements will be b.if else ¢.bothaandb mi icin d.None ofthese . Namethe folloy S- syotypesof arithmetic operators sreetypes oflogical operators 3, Twooperators used in strings | Thestatement whichis used to evaluate only one condition ] $ Theprocedureto write the steps ofa program ina well defined way F Answerthe following questions briefly. \natdo yournean by the term operator? ee) & oe. Whatisthe: use of #1 aN in fements. 1. Write the output for the following code of stat print(a> 10and b<40) b, a=10 b=20 print(a+b) print(a+b’) c. a=100 ifa>99 print(a,'isa three digitnumber’) else: print(a, isa two digit number’) d.a=4 ifa%2==0: print(a,is even number’) else: print(a,'is odd number’) 2. Rewrite the programs after correcting the errors in the given box. a. n=6 IfN%2=0: Print n,is divisible by 2” b. a=10,b=20 Sum=a+b Print(Sum of numbersis +sum)) c. num1=50 Num2=60 IfNum1

You might also like