Download as pdf
Download as pdf
You are on page 1of 69
2.01 UNIT - I DECISION MAKING, CONTROL STRUCTURES AND FUNCTIONS Introduction Python programs are executed statement by statement in a sequential order. In many situations it is necessary to alter this order. This is achieved using control structures. These structures are used to control the program execution order. Figure given below gives the classification of control structures Control structure Unconditional Decision making] Looping continue] pass | it] [if else] [if . [Nested if for] [while Indentation Indent is defined as a space that is left when a block of text is spaced inwards compared with other texts Surrounding it. In programming languages like C, C++, Java etc { } (curly) brackets are used to indent (mark) the block of Codes used in control structures, functions, classes etc. But q es depends on the Quality of the 2.02 this alignment of cod the programmer: nis a compulsory rule of Python ; to write uniform, regular » readable code. So it is compulsory while writing a structures, functions, classes etc or functions or classes. line up the related the block or suit of codes according to : logical structure. visualization of But indentatio forces the programmers mpt mode or in IDLE editor, the cursor automatically moves to fifth place leaving four spaces and blinks in the fifth place while using control structures This gives the start of the related block. After completing a block of statements, use backspace or tab key to move the prompt to the correct place. dows show the Python interactive dow and the IDLE editor window respectively. In interactive pro The following win prompt win' | Indentation Rules The following are the important rules to be followed while using different structures. (i) (ii) (ii) (vi) Same header continuation must be indented in the same level Block or suit of codes related to a particular header must be indented at the same distance to the right of the header. There is no standard rule in Python for the number of spaces to be followed in indentation. But it should be same for all statements in a given block under a header. Four spaces per indentation level is generally followed. Nested block statements the right of the header. Don't mix tab and spaces. must be indented further to - 2.04 Figure given below shows the process of Ndentay gy Header 1 Header 1 Block Header 2 4 space 4 space = Header 2 Block Header 1 Continuation 4 space Header 2 Block Continuation Regular statements Note: Inthe remaining sections IDLE editor is Used to write example programs. Conditional Structure There are two types of conditional structures. * — Decision making structures * — Looping structures 2.1. Decision Making Structures Decision making structures are used to skip or to execute a group of Statements or a Single statement based on the result of a test Condition. The condition may be a relational or logical expression Giving either True or False value. The decision making Structures are: (i) if Statement (li) if... else Statement (ill) if. Clif .... else Statement 2.05 (i) if Statement if statement is used to alter the sequential flow of execution according to the Output of a test condition in the header. If the output of the test Condition is True, one or a group of statements called suit or block is executed followed by the next statement sequentially. If the test condition value is False, if statement will not work and the control is transferred to the next statement skipping the suit of statements. Therefore if condition is defined as a statement used to execute or skip one or More statements called suite or block, for a True value of the Condition. The general form is: if test condition: Header | statement | statement 2 | wee eee True suit or block | statement n | next statement where: if - keyword test condition - header. Relational or logical expression - colon. Used as an indentation operator __ Figure given below shows the flow and indent diagram Of if statement, statements if condition : else : 4 Space| False suit or Bi, next statement EES new statement Example (i) To add mark according to the grade mark=70 grade=‘A’ if grade==‘A: # Header matk=mark+10 —#suit of statement print (mark) # suit of statement print (‘Program over’) The outputis: ( 80 program over To check whether the given number: is even or odd a=int (input (‘Enter the number eG to check:”)) print (“The given number j . 2 ‘ i print (‘Program over’) ee Tuesv When the pi ‘ram is executed, the input as: the computer waits fol 2.07 Enter the number to check : 10 When an even number 10 is given as the input, the if statement checks the remainder for zero by dividing the number by 2. Since the condition is True the True block is executed followed by the statement outside the if statement as: The given number is even Program over When a odd number 7 is given as the input, the if statement checks the remainder for zero by dividing the number by 2. Since the condition is False the if statement is not executed and the control comes out of the if statement without executing the if. So the output will be: Program over We do not get the expected output if the condition is false. (ii) if... else statement if... else statement is used to alter the sequential flow of execution according to the output of a test condition called header. If the output of the test condition is True, one Or a group of statements called True suit or block is executed followed by the next statement in sequential order. If the test condition is False, one or a group of statements called False suit or block in the else part is executed followed by Next statement in sequential order. Therefore if... else Condition is defined as a statement used to execute one block of Statements if the test condition is True else other group if the test Condition is False. The general form is: 2.08 Header if test condition: statement | statement 2 statement n else statement | statement 2 statement n next statement True Suit or block True suit or block where: if, else - keyword test condition - header. Relational or logics expression - colon. Used as an indentatio, Operator. Use the same indent fo if and else Figure given below shows the flow andi : indent diagram of if ..... else statement. if test conditi i statement suit] 4g si or block —wace Next statement next statement 2.09 Example (i) To, find the maximum of two numbers a=10;b=20 ifa>b: print(‘A is maximum’) # True suit else: print(‘B is maximum’) # False suit print(*Program Executed Successfully’) The output is: Bismaximum Program Executed Successfully (ii) To check whether a number is divisible by 3 and 27 a=177 ifa% 3 and a% 27: print (‘Number is divisible by3 and 27’) #True suit else: print (‘Number is not divisible by3 and 27’) # False suit (iti) Usage of logical operator not in the above example _ ifnot (a% 3) and not (a% 27): print (“Number is divisible by 3 and 27’) else print (‘Number not divisible by 3 and 27’) | y) Py rogram to check whether a student is allowed to sit Sor the examination depending on his attendance Presentage, If attendance > = 70 the student is eligible 10 write examination else the student is not eligible. os th=int(input(‘Enter the total workin how ha = int(input(‘Enter the hours attendeg by te I LY, —— =(ha/th)*100 print(‘Attendance secured is:”, attendance ) ifattendance >= 70: print(‘Eligible to sit for the exam ”) 2.10 else: : print(‘Sorry, you are not allowed to sit fory ie examination’) The outputis: Enter the total working hours: 420 Enter the hours attended by the student: 309 Attendance secured is: 71.42857] 42857143 Eligibleto sit for the exam (v) Program to check whether the given character jy alphabet or not using ASCII value. Logic - The given character is converted to its ASC value using ord() function, The ASCII vale of A, Z, a and z are 65, 90, 97 and 1: Tespectively, ch=input(‘Enter any character: « ) c=ord(ch) #9 Convert ch oe . aracter t value print( The given characteris ch) catia if(ch>—"A and ch<="7> o, ch>="9’ and ch<="z’): Print(‘The gi i bet’) 7 BiVen character ig an alphabet’) riNt(“The gi Print(‘The given character jg not an alphabet 2.14 The output is: Enter any character: 8 The given characteris 8 The given character is not an alphabet Enter any character: The given characteris }] The given character is an alphabet (vi) Program to check whether the given character is q vowel or not cl=input(‘Enter a character: ‘) ifel='a’ orcl=¢ orel='’ or cl=="o’ or cl="worcl==’A’ orc [== =F’ orcl=="P or cl=0’ orcl=U’: print(‘The given character is a vowel’) else: print(‘The given character is nota vowel’) The output is: Enter a character; A The given character is a vowel Enter a character; 9 The given character is not a vowel (vii) Program to check whether the given year is a leap year or not Logic - A leap year is a year which is divisible by 4 and 400 but not by 100. year=int(input(‘Enter a year: ‘)) if (year%4==0 and year% 100!=0) or year%400—=0): print(*The given year else: print(*The given year {$j The outputis: Enter 4 2.12 1 Sep Format, ay ty ISNotleay’, ormat i, ayear: 2015 The given year 2015 is not leap Enter ayear: 2020 The given year 2020 is leap (viii) Program to check whethe Perfect square number Logic - r the given number yj, (i) Take the Square root of the number (li) Floorthe Square root value (iii) Compare Value (iv) Ifthey are ¢qual. Then the given numbe isa perfect Square number, import math n intinput(‘Enter the m*math.sqr(n) no math.floorm) ifm=no: PrINU(“The given numbers } is a perfect Square number’ -format(n )) else: Print(‘The the square root Value and flog humber to check: ‘ )) ziven . i fec gr “Number { i Isnota perfec! Square number format(n)) 2.13 The output is: Enter the number to check: 6400 The given number 6400 is a perfect square number Enter the number to check: 4248 The given number 4248 is nota perfect square number (iii) if... elif... else Statement if... elif... else statement is used to check multiple test conditions. This statement is formed by joining any number of elif... partin the if part of the if. .. else statement, The general form is: ee iftest condition 1: statement block 1 elif test condition 2: statement block 2 elif test condition 3: statement block 3 elif test condition n: statement block n else: statement block next statement where: if, elif, else - keyword test conditions - header, relational or logical expression 2.14 _ colon, used as an Indentat operator. Use the same indents" if... elif... else ‘| else is used to alter the sequential 4 of operation to any one of the multiple branch depen ding g | the test condition in the if part. If the output of the te condition1 is True, statement block 1 is executed followeg by the next statement in sequential order. if testcondition1 is False, the flow of control jg transferred to the elif part and checks the test conditions, | any one test condition is True the statement block associateq with that elif is executed followed by the next statement. | all test conditions are False in the elif, the statement block in the else part is executed followed by the nextstatement, Figure given below shows the flow and indent diagram if... elif. - if condition 45 : | ai Space [True suit or Bloc elif condition : at Spee [rue suit ar Block elif condition ; Space | False suit or Blodl Next statement 2.15 Example (i) To find whether the given number is positive, negative or zero. | a=-27 | ifa>0: | print(‘Number is positive’) | elifa=0: | print(‘Number is zero’) elifa<0: print(‘Number is negative’) else: print(‘Give a valid number’) The output is: Number is negative (ii) Program to name the shape from its number of sides. sides=int(input(‘Enter the number of sides: ‘) ifsides= 3: print(‘The name of the shape is Triangle’) elifsides=4: print(‘The name of the shape is Quedrilateral’) elifsides =5: print(‘The name of the shape is Pentagon’) else: print(‘Give a value for side between 3 and 5’) The outputs: Enter the number of sides: 4 The name of the shape is Quadrilateral Enter the number of sides: 7 Give a value for side between 3 and 5 (iti) 2.16 Program to name the triangle from the lengu, S i sides. s1=float(input <2=float(input( F <3=float(input(“Enter ifs]==s2 and s2==s3: name=’Equilateral Triangle’ elifs1==s2 or s2==s3 or s3==s1: name='Isosceles Triangle’ else: name=’ Scalene Triangle’ print(name) (‘Enter the length of side : *)) Enter the length of side2 : *)) the length of side3 : ‘)) e output is: (iv) Enter the length of sidel : 4.5 Enter the length of side2 : 8 Enter the length of side3 : 90 Scalene Triangle Enter the length of sidel : 8 Enter the length of side2 : Enter the length of side3 : 9 Isosceles Triangle ; Program to find the biggest of given three number’ n]=int(input(‘Enter the first number : ‘)) n2=int(input(‘Enter the second number : *)) n3=int( input(‘Enter the third number : ‘)) ifnl>n2 and nI>n3: big=nl elifn2>n1 and n2>n3: big=n2 \o 217 else: big=n3 print(‘The biggest number is: * big) The outputis: Enter the first number : 89 Enter the second number : 45 Enter the third number : 98 The biggest number is: 98 (v) Program to check whether the given character is an uppercase letter or lowercase letter or whitespace or a digit. c=input(‘Enter a character: *) ifc>=’A’ and c<=’Z’: print(‘The given character is an uppercase letter’,c) elifc>="a’ and c<="2": print(‘The:given character isa lowercase letter’,c) elif c>=’0'and c<=9': print(‘The given character is a digit’,c) elifc>="\n’ and c<="\v’: print(‘The given character is a whitespace’,c) else: print(‘The given character isa special character’,c) The output is: Enter a character: \n The given character is a special character \n Enter a character: $ The given character is a special character $ Enter a character: G The given character is an uppercase letter G 2.18 (vi) Program to find the roots of a quadratic €quation ~b+Vb>—4ac 2a If \b’— 4ac > 0 there are two roots, Formula = namely —b+Vb?-4ac -b- Vb] =, r, = —___* | 2a 2 2a If ¥b?—4ac=0 there is one root namely r —b_ r= 2a If Vb" =4ac<0 the Toots are complex namely X,=-b/2*a x, =i Vb?—4ac/2*g Tx +x] 2X) — Xj from math import sqrt a=float(input(‘Enter the Value ofa: « b=float(input(‘Enter the value of p : ‘) c=float(input(‘Enter the value d=b**2-4*a*¢ ifd>0: rl =(-b+sqrt(d))/(2*a) 12=(-b-sqrt(d))/(2*a) print(‘There are two roots: Ba lifd—0: oo r1=-b/2*a print(‘There is one root:’,rl) ofc: ‘)) a 2.19 else: xl=-b/. 2*a x2=sqrt(-d)/2*a rl=complex(x1,x2) r2=complex(x!,-x2) print( ‘The roots are complex’ rl y’and’,12) The output is: Enter the value ofa: 5 Enter the value of : 8 Enter the value ofc : 3 There are two roots: -0.6 and -1.0 Enter the value ofa: 1 Enter the value of b : -4 Enter the value ofc: 13 The roots are complex (2+3}) and (2-3)) Control statement Looping structures or iterative structures are used to execute a group of statements (Block of statements) repeatedly for a known number of time. These structures need two entities namely, loop variable and loop terminator. Loop variable is used to control the repetition of the loop and loop terminator determines the number of times the loop has ‘obe repeated. The different looping structure are: (i) while loop (ii) for loop (i) while Loop : ; i by while loop is used to execute a block of codes called = or body of the loop repeatedly until the given condition "ue. The general form is: —_ ON 2.20 while test condition: Header statement-| statement-2 Body or block of the | 0, statement-n next statement where: while - keyword - colon. Indent operator test condition - header, relational or logical expression The body of the loop must be properly indented, Working The following operations take place during the execution of while loop (i) The loop variable in the test condition is checked with the loop terminator. If its value is True, the body of the loop is executed. _ (ii) The loop variable is increased or decreased. } (ili) Then the control is transferred to the while statement (iv) Again the loop variable is checked with the loop terminator. If its value is True, the body of the loop is executed. (v) The steps (ii) to (iv) are repeated until the test condition is False. (vi) When the test condition becomes False, the control comes out of the while loop and executes the nex! statement in sequential order, 2.21 Figure given below shows the flow diagram of the while loop. Body of the Block Next statement Example i=l # i loop variable while (i<=5): #5 loop terminator body of print (‘God Loves you’) the loop i=i+1 #loop variable increased print (‘Program Ended’) Initially the loop variable i in the test condition is checked with the loop terminatori<=5. If it is False, the program ends without executing the body of the loop. If it is True the body of the loop will be executed and the loop variable i is incremented and this process is repeated five times. After executing the body five times the test condition becomes False. So the loop terminates and the control is transferred to the statement following the while statement and the output will be as shown below. God Loves you God Loves you God Loves you aD God Loves you God Loves you program Ende while LOOP i sed within another while If one while 10oP is en sted while loops. Each Joop then such loop’ called ne its ind tation. There is no limit on the loop must follow ts inden number of while loops that can be nested. Nested Example while condition: while condition: << we foe inner loop wep fo cesses Rules nested structure must have its (i) Every loop in the follow indentation. control variable and must while i< 10: whilej>x: Body of the inner loop (ii) Cont rol ca i n only transfer fi i ediate outer rom inner loop to i! {iii) Loo Ps shoul id not overlap or each | joop must follow its own indentation 2.23 Example — Printing 1, 2, and 3 tables i=l jl whilei<=3: # outer loop while j<=5: #inner loop print(i,”*” j=") Ft print() iit] jl The output is: Ix1l=1 2x1=2 3x1=3 1x2=2 2x2=4 3x2=6 1x3=3 2x3=6 3x3=9 1x4=4 2x4=8 3x4=12 1x5=5 2x5=10 3x5=15 Example Programs (i) Program to print n natural numbers. Natural numbers are 1, 2,3,4,...n i=l n=int(input(‘Enter the value of n: *)) print(‘The natural numbers are’end=’ *) while i<=n: ; print(i,end=" ‘) it=1 The output is: Enterthe value of: | 0 The natural numbers are 123456789 Ig (i) Program to find the sum of the following Series . =04+24+4t 64..." sum=0;i=2 n=int(input(*Enter the value ofn: ‘)) whilei<=n: sumt+=i it=2 print(‘The sum of numbers is’,sum) The output is: Enter the value of n: 50 The sum of numbers is 650 (iii) Program to find all the perfect squares up ton Logic - A perfect square number is a number made by squaring a whole number. i=l n=int(input(‘Enter the value of n: ‘)) Print(‘The perfect squares below { } are:’.format (n)) while ti » next statement yb 2.35 (i) To print the first 7 numbers in the range of 10 number using break in for loop for i inrange (10): ifi==7: break print (‘The number in Tange is :’, i) print (‘The loop breaks when i=7”) The output is: The number in range is : 0 The number in rangeis : | The number in range is : 2 The number in range is : 3 The number in range is : 4 The number in range is : 5 The number in range is : 6 The loop breaks when i=7 (ii) To print the first 7 numbers in the range of 10 numbers using break in while loop r=range (10) i=0 whileiinr: ifi==7: break print (‘The number in range is :’, i) i=i+l. print (‘The loop breaks when i =7’) The output is: The number in range is : 0 The number in range is : | 2.36 5 Th nuit 4 nge IS: - op in range is: a from 0 10 9- ‘se when i becomes 7. So the program: continue Statement h / Loop / test NE alse m om / vor ndilon on of loop body Eeee) | — | | J | _ | : | ~<—( condition | I b tinue / t= Body ol the loop | | | | | | 4 Exit loop 2.37 continue statement is used to skip a part in the bo of the loop when the test condition is True and the cont ey transferred to the beginning of the loop. Loop operat on not terminate but continues with the next iteration _ Normally this statement is used inside the body of or sae i” the loop within a conditional statement. Figure given above shows the flow diagram of continue statement. general form is: Example () while condition : eer re control next statement (i) forcondition : next statement (ii) s= ‘Nagercoil’ foriins: ifi==‘e’ ori== Tl’: continue print (i, end = *") _ wy The output is: Nagrcol This program is intended to print Nagercoil, By pecause of continue inside the if oe the conta transferred to the for statement, without executing the a statement in the for loop. oo the letters & and | in the; condition. So these letters will not be printed. Theref,,, the output will be Nagrcoi. pass Statement The general form of pass statement is: This statement acts as a place holder or an empty area and this can be used for writing codes in future. Normally in loops, if statements, functions and classes empty body or block is not allowed. But, by using pass, the body or a block can be left blank and can be filled in future. D uring execution the interpreter reads the pass statement (empty area) and does nothing. Example if(a>b): pass else: print (‘ais big’) Example programs (i) Program 10 find the n=int(i Factorial of a given number "- 'nput(‘Enter the fy] erthe number to find the factorial: *)) 2.39 for iin range(1,n-+1): ffi print(“The factorial of ’,n, is:’,f) The output is: Enter the number to find the factorial: | The factorial of 1 is: | Enter the number to find the factorial: 5 The factorial of 5 is: 120 (ii) Program to display all the perfect numbers up to 1000. Definition - A perfect number is a positive number that is equal to the sum of all divisors including 1 and excluding the number itself. Example - 6 is a perfect number. This is because, the sum of the divisiors 1, 2, and 3 is equal to 6. print(‘The perfect numbers up to 1000 are: *) for i in range(6, 1000): s=0 for j in range(1,int(i/2)+1): r=1%j if ==0: st=j if s=i: print(i) _—_ a 2.40 1 t is: he outpul perfect numbers up to 1000 are: The 6 28 496 (iii) Program to construct the following pattern, * * * ek * x oe Rk OF * * * * OF x * * * * * OK * * * n=int(input(‘Enter the number of rows: ‘)) fori in range(n): for j in range(i): print (“* ‘, end=””) print(*”) for iin range(n,0,-1); forj in range(i): anni e end=””) Print(‘’) 2.41 he outputs: Enter the number of rows: 3 * x * xee ae * iv) Program to generate all three and four digit Armstrong number Definition | - Armstrong number is a number that is equal to the sum of the nth power of its digits. Where n.is the number of digits. (a) 153 isanArsmstrong number. Because [+ 53+3? = 153 (b) 1634isanArmstrong number. Because 14+ 69 +344 44 = 1634 import math print(*The three and four digit Armstrong numbers are:’) for iin range(100,10000): if i<=999: a=i%10 # First digit b=int((i%100)/10) # Second digit c=int(i/100) # Third digit t-math pow(a.3)+math,pow(.3)+mathpow(3) if i==t: print(i) Peat 2.42 else: a=1%10 b=int((i%100)/10) c=int((i%1000)/100) d=int(i/1000) t=math.pow(a,4) + math.pow(b,4 )+ my, pow(c,4) + math.powe, if ist: Power(dy print(i) The output is: The three and four digit Armstrong number are: 153 370 371 407 1634 8208 9474 (v) Program to find the value of sin (x) for n terms x3 x x’ i =x-—— +— -— .... sin (x) =x 3) + 3) 77 : Logic First term =x Secondterm = — (x) * (x * x) /(2*3) #3] = —(previous term) * (x * x)/@2 x3 Thirdterm = = (- —| * (x *x)/(4*5) #5 (Previous term) * (x * x) iG i» yr 2.43 “ x (-=] *(x*x)/(6*7) — (Previous term) * (x * x)/(6* joer = _(i— I term * (we * x) /(2* i) * (2 *i +1) ’ =~ (Previous term) * (x *x)/(2*i)*(2*i+1) Fourth term generalised formula is: sin(x) =X* [- (previous term) * (x *x)/((2* i) * (2*i+1)] ert the given angle x to radian using the formula The Conv jan =x * 0/ 180 n=int(input(‘Enter the value of n: ‘)) g=float(input(“Enter the angle: ‘)) x=a*3.141592/180 t=s=x fori in range(! wn): ta(-t*x* (281) 4274) rad st=t print(‘The value of sin ({ })= {} radian’.format (a,s)) The output is: Enter the value ofn: 20 Enter the angle: 78 The value of sin( 78.0 = 0,.9781475418485508 radians ng harmonic (i) Program to find the sum of the fol low! series for the given value of " 7 t— ft+—a tore 3 n . 4 2.44 n=int(input(‘Enter the value of p: ‘)) s=0 for iin range(1,n+1): st=l/i print(‘The sum of the series for’.n, terms is The output is: Enter the value of n: 10 The sum of the series for 10 terms is: 2.9289682539682538 (vii) Program to print number 1 one time, 2 two times three times and so on up to 10 ten times, for iin range(1,11,1): forjin range(i,i*2,1): print(i,end=”) print() The outputis: 1 22 333 4444 55555 666666 Ty 88888888 999999999 '101010101010101019 (viii pee Whether the given number 1" 245 Definition - A prime number is a number divisible by 1 and by itself. These two divisors are called improper divisors. All the other divisors are proper divisors Therefore to check a number n for prime or not its proper divisors are checked. If there is no proper divisor, the number is prime else not prime . n=int(input(‘Enter the value of n: *)) ifn>2: for i in range(2,int(n/2)+1): rn%i if r==0: break ifr!=0: ai print(‘The given number’ ,n,’is prime’) else: uae print(‘The given number’ { } is not prime’. format (n)) else: FE print(‘The given number’ ,n,’is prime’) The output is: Enter the value of n: 71 The given number 71 is prime Enter the value of n: 9% The given number 94 is not prime 0) Program to print the prime numbers between | fon Nint(input(‘Pnterthe value ol) for iin range(2,n4 1) ifie2 2.46 forj in range 1=i%j if r==0: break if r!=0: . print(ijend=" *) else: i print(iend=" *) The output is: f fn: 100 ee 19 23 29 31 37 41 43 47 53 59 6 67 1 73 79 83 89 97 _ (x) Program to find the sum of s = 47 + 8? + 12 + oo s=0 fori in range(4,24,4): st=i*] print(“The sum of the series=”,s) The output is: The sum of the series= 880 2.2, Functions Built-in functions Built-in funct written by the Progr language as module. it depending on thei ! ‘Ons are functions which are not to > ammer. S. The p ' need. in the But these are available in " s fogrammer can import and U 2.47 mathematical functions Mathematical functions are pre-defined (built-in) functions in the Python language for performing mathematical operations. The various mathematical functions are listed below. (a) Number functions (b) Power and logarithmic functions (c) Trigonometric, angular conversion and hyperbolic functions (d) Special functions (e) Mathematical constants The above mathematical functions are stored in a module called math. To use this module in our program the user has to import using the import statement in the beginning of the program. The general form to call the mathematicals function is: math.functionname (parameter) where: math - module name function name - name of the pre-defined function parameter —- integer or float value Number Functions Table given below lists the different number functions in Python. Function ceil (x) os” Functionality Return the rounded up inte or equal to the floating po x is integer same number j BET Value Int umber S Fetumeg XY math.ceil (8.78) =9 floor (x) copysign (x, y) T Retin the rounded down integer val a floating point number x smaller than numbe:. Ifx is integer same numb te returned. math. floor (8.78) = 8 er jg Return the value of x with sign of y, 7h, returned value is float type. math.copysign(-8,9) = 8.0 fabs (x) Return the absolute value of x. math. fabs(-5)=5.0 factorial (x) ; fmod(x,y) | Return the factorial value c nath.factorial(4)=24 “Retum the remainder when x is divided by| y. math.fmod(8,3)=2.0 f | i } | | | | Return the mantissa and exponent of pair (m,¢). The value of m is float ande's integer. Usingmande, x can be calculated as x=m*2**e, math.frexp(9)=(U.5625,4) X= 0.5625*2**4=9,0 | ee et —_— isin) isnan( x) In Python there isa facility to represent not 2.49 Return the greatest common divisor of x and y. math. ged(9,4) =! math.ged(1701,3768)=3 in Python there is a facility to represent positive infinity and negative infinity. Positive infinity is denoted by float (‘inf”) and negative infinity is denoted by float (*- inf). Return True if x is positive or negative infinity, else False ifx is positive or negative number or nan (Not a number) math.isinf(9)=False math isinf{float(‘inf”))= True math.isinf{float(‘-inf”))=True cr, el is infinity or a nan (nota number) math.isfinite()=1 math isfinite(float(‘inf)= False math isfinite(float(‘nan’))=False 1. Not a number is a data type value that is This is a numbe' used to represent any undefined and unpresentable. denoted by nan and its datatype is nume! ic datatype and is represented as X ~ float (‘nan’) 2.50 Example jsanan modf(x) trunc(x) Idexp(.¥) @ % (Se re root ofan imaginary numbe,j ey do not have vali, Retum True ifx isanan else False math.i ignan(float(‘nan’))- True math. ‘jgnan(9)=False Return x* a**y). This is just the reverse of frexp0- math.Idexp the fractional and in th fraction (0.5624, 4-8. 9984 teger part ofx Return al and integer Ifx is signed, bo part has sign math.modf(-9.87)> math.modf(9)=(0-0, Return the integer pal point number. math. trune(9.873)=9 math.trunc(9)=9 =(-0. 87000, -9.0) 9.0) rtofx ifx is floating Pp. ower and Logarithmic Functions Table giv . e below lists . logarithmic functions lists the different powel *” 251 math.exp(5)=148.41315910 math.expm1(5)}=147.41315910 With one argument, retum natural logarithm of x to base e. With two argument, retum the log of x to the given base calculated as logix) logt base) math. log(23,8)}=1.507853 math log(23)=3.135494 Retum natural log of 1+x to base ¢ math log |p(23)= 3.178083 Retum natural log of x to base 2 math log2(23)=4.5235619 + dog! O(x) Retum the log of x to base 10 math log !0(23)= 13617278 | pow(x,y) Retum x raised toy math pow(23,4)=279841.0 Retum the square root of math sqri8 17 )=9.038 22 SB Trigonometric and Angular Conversion and Hype, Tho) Ic Functions Table given below lists the different trigonom ar conversion and hyperbolic functions. Strig angul Functions Functionality acos(X) Retum the are cosine of x in radians. The valy, | | of x must be between- land 1. © | math.acos(—0. 1 )}=1.670963 | | asin(x) Retum the arc sine of x inradians. The value of | x must be between -1 and 1 | math.asin (0.1)=—0.10016742 | atan(x) Retum the arc tangent of x in radians. The value | ofx must be between—1 and 1. | math.atan(-0.1)=-0.099668 | cos(x) Return the cosine of x in radians | sintx) Retum the sine of x in radians | math.sin(34) = 0.529082 tan(x) | Retum the tangent of x in radians | math.tan(34) = -0.623498 | Retum the length of the vector from orgin to | point (x. y). | | math hypot(10,5)=11.180333 degreestx)) Retum the angle x inradians to degrees | math.degrees(.6981 317007977318) | | | hypot(x.y) T radiansix) | R | radians(x) | Retum the angle x in degrees to radians math radians(40)=.6981317007977318 : 2.53 Return the hyperbolic cosine of x math.cosh(34)=29 1730871 263727.44 n(x) cos! Return the hyperbolic sine of x math.sinh(34)=29 173087 12637227.44 Return the hyperbolic tangent of x math.cosh(34)=1.0 sinh) tanh(X) Return the inverse hyperbolic sine of x math.asinh(291730871263727.44) = 34 Return the inverse hyperbolic cos of x math.acosh(291 73087126372744) = 34 asinh(x) acosh(x) Special Functions Table given below lists the various special functions. Functions Functionality erfix) Error function. This occurs while working with probability, statics and partial differentiation. x accepts values between —x to x and returns between —1 to 1. Return the error function of x. math.erf(40)=1.0 math.erf(-40) =-1.0 erfe(x) Complementary error function, This is 1 —erf(x) | Return the complementary error function ofx math.erfc(40)=0.0 | Samma(x) Return the gamma function. x canbe any number. Ifx is negative integer it returns value Error. The gamma value is equal to factorial of x — 1, math.gamma(39)=5.230226 1e44 math.gamma (-20.7)=~] -90405025e-19 ee 2.54 atural logarithm of the absolute LY, Return the n of the gamma function x math.lgamma(30) = 5.333674377¢46 alue Igamma(x) nts Mathematical Consta Table given below lists the mathematical Constants Functionality Return the mathematical constant x= 3.14. math.pi=3.141592653589793 Return the mathematical constant t = 6.28... math.tau = 6.283 185307179586 Return the floating point positive infinity. Equivalent to float (‘inf’) math.inf=inf—math.inf=— oating point nota number. This is inf (negative infinity). Return the fl equivalent to float (‘nan’) math.nan=nan ath contains predefined The module named cm ers. Note : mathematical functions for complex numb dir () functior dir () function is used to fini attributes such as constants, variables, functions, cla present in the module. The general form is: dir (object name) d the list of names of al sses et° y 2.55 where: dir - function name objectname =—- valid module name Example fn) import math print (dir (math)) The output is: [_doc_’, *_loader_’, *__name_’, ‘package’, «spec ‘acos’, ‘acosh’, ‘asin’, ‘asinh’, ‘atan’, ‘atand’, ‘atanh’, ‘ceil’, ‘copysign’, ‘cos’, ‘cosh’, ‘degrees’, ‘e’, ‘erf”, ‘erfe’, exp’, “expm1 ’, ‘fabs’, ‘factorial’, ‘floor’, ‘fmod’, ‘frexp’, ‘sum’, ‘gamma’, ‘ged’, ‘hypot’, “inf”, ‘isclose’, ‘isfinite’, ‘isinf”, “snan’, ‘Idexp’, ‘Igammia’, ‘log’, ‘log10”, ‘loglp’, ‘log2’, ‘modf”, ‘nan’, ‘pi’, ‘pow’, ‘radians’, ‘remainder’, ‘sin’, ‘sinh’, ‘sqrt’, ‘tan’, ‘tanh’, ‘tau’, ‘trunc’] (ii) import datetime print (dir (datetime)) The output is: [‘MAXYEAR’, ‘MINYEAR’, ‘__builtins__’,*__cached__’, (doc 2 «file. | loader name ‘package’, ‘__spec__’, ‘date’, ‘datetime’, ‘datetime_CAPI’, ‘sys’, ‘time’, ‘timedelta’, ‘timezone’, “tzinfo’] help () This function is used to get the python help documentation for modules, functions, classes, keywords ect. The documentation will be printed on the screen. The general form is: 2.56 where: object - Optional. The name of the documentations is needeg Whos, It no grummet is given, the help system start the user can give the object name at the Prompt to 4 any et th, hlep. Example (a) To get the documentation for math >>> help('math’) Help on built-in module math: NAME math DESCRIPTION Objec 6 This module is always available. It provides access to the mathematical functions defined by the C standard. FUNCTIONS cturn the inverse hyperbolic cosine of x. asin(x, /) Return the arc sine (measured in radians) of x asinh(x, /) Return the inverse hyperbolic sine of x. atan!x, /) Return the arc tangent (measured in radians) of x. - More -- 2.57 o) To get the documentation for print >? helpO) welcome to Python 3.7's help utility! if this is your first time using Python, you should finitely check out def the tutor jal on the Internet at https:// docs.python.org/3.7/tutorial/. Enter the name of any module, keyword, or topic to get help on writing python programs and using Python modules. To quit this help utility and return to the interpreter, just type "quit". To get a list of available modules, keywords, symbols, or topics, type "modules", "keywords", "symbols", or "topics". Each } t module also comes with a one-line summary of what it does; to list the modules whose name or summary contain a given string such as "spam", type "modules spam". help> print Help on built-in function print in module builtins: print(...) print(value, ..., sep=' ', end=" ie file=sys.stdout, flush=False) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: : . ea file-like object (stream); defaults to th sys.stdout. ie current ~ oo” sep: string inserted between values, default 2.58 4 Space. end: string appended after the last value, default a Newline, flush: whether to forcibly flush the stream, help> User defined function A user - defined function is a group of reusable code written by the user to perform a speci defined task or job. 'elatey fic wel. Function definition def key word is used to define a function. The general form is: Header def function name (list of parameters): “function_docstring” statement - | statement - 2 Ae es Function Body’ statement -n return (expression) where: def - keyword function name - user-defined name list of parameters - Parameters separated by commas and used to receive values during calling. > ON 2.59 - Indentation Operator. The function body must follow Proper indentation. ction_docstring” - Optional statement. Used to give brief explanation about what the function does. “fun Function body -This contains the executable Statements for doing the operations intended by the function. return - keyword to return the value of the function to the calling function. This can be omitted. In Python, functions are treated as ordinary executable def statements and the first line of the function is called header. Rules (i) The key word def marks the function header. (ii) List of arguments are optional. If the function has no list of arguments an empty parentheses is a must. (iii) The function body consists of valid statements and must follow proper indentation. (iv) The return statement is used to return a value from the function and is optional when there is no value to return. Parameters and arguments Parameters are variables present in the function definition, These variables receive value only at the time of ‘unction calling. These parameters are also called as dummy | Parameters, “~ 2.65 — 80 20] y . 1303052432 1803053399 Therefore the parameters a and b receive the : 2 and 80. With these values the statement ¢ “a The return statement transfers the pa e calculated value ¢ = 100 to the calling a 400 is stored in the variable z on the : n calling statement. control and thi The returned value hand side of the functior inction using more than one return value defadd (a, b): return a +b, a * b, a/ b #More than one retum (ii) Fu # Main program x,y,z=add (10, 5) # Function calling print (‘The sum ofa and bis:’.x) print (“The product ofa and b is:’,y) print (“The divisor of a and bis :”, z) The output is: The sum ofa and bis: 15 The product ofa and bis : 50 The divisor of a and b is : 2 Scope and Lifetime of Variables Scope of known among the ae means how widely a variable is variable mean: lunctions in program: i is hi s. Life time of ow long a variable retains a given value during the execution four soopes, Of the program. In Python there ale (ii) Global scope Local scope (iv) Built-in scope (iil) Enclosing scope geal SOP o : The variables defined inside a function are called variables: These variables are local to this function and 1008 ible to the function where they are defined. fe fe scope of these variables are, it is known within : function. Lifetime is, it is active until the function is in execution” example, def ‘example (): a=10 b= 20 print (a+b) example () The variables 4 and b are called local variables. These cessed witnin the function and cannot be utside the function example (). The ‘an be used outside the function variable names inside jo not clash with each variables can be a accessed from 0! able names @ and b c r other objects. The side the function d vari example ( ) to refe' the function and ou! other. Global Scope The variables defined outside all the functions in a file is called global variables. These variables are common to all the functions in the file and can be accessed from any function. These variables are visible to all the functions In the file. The value of the global variables cannot be modified inside the functions. — 2.66 of these variables are, it is known The scope?” « active until the program j "hou out the file. itetime is it 'S FAM is acy Is, Example bl x= “Good Evening defexample (): : y= ‘To YouAll pexty #y,zlocal variables print (2) #Global variable example () The output is: Good EveningTo YouAll In the above example, the function example ( ) uses three variable x, Y, 2. Out of this x is defined outside’ the is common to all the functions in the file ang function and it i can be used directly without defining inside the function. Function composition Function composition is defined as a process of combining two or more functions in such a way that the output of one function becomes the input of second function and so on. The figure given below shows the composition of two function f and g with one arsgument x. Jy 7 f(x) ->[g }- > eff) Example - Function to square 4 and divide the result by 2 using function composition. def square(x): retum(x*x) def divide(x): retum(x/2) out=divide( square(4)) Drint(“The output is:”.out) Fr 2.67 uit is: The oe he outputis: 8.0 ive Function is a technique used to solve the problem In this, the given problem is defined as a pecs” si Recursion using computer ; and this contains a statement to call itself repe whe problem is solved. In general, a function is said to be recursive, f it calls itself. well defined recursive function or procedure must satisfy the following: e a recursive formula. There must b t be a base value for which the function (i) (ii) There mus! does not call to itself (iii) Each call of the function must move value. closer to the base Example (i) To. find the factorial of a number The factorial value ofa positive int =1*2*3*....- *n The value of n! The base value for factorial function is 0! n*(n-1)! eger is denoted as n! =1 The recursive formula isn!= The mathematical representation of! nl=1ifn=0 n!=n*(n- 1)! ifn>0 n! is: where nis a positive integer. Program def factorial (n) : ifn retum | else fact =n * factorial (n retum fact intanput Enter n tact ~ factonal (n) print ( The factonal of |) 815 The output ts Givea positive number § The tactonal of Sis 120 tact- n* factonal(n- 1) call fact. = $ * factorial (4) i" | call2 24 p> 4" tectonal (3) 6 | call 3 L_ 3* factorial (2) call 4 > r® 2" factorial (1) | call § Back : |! * factorial (0) substitution | + a positive number {}. format (n, fact)) 2.69 / the fibonacet sequence ) Pros | : sequence o type 0, 1, 1, 2,3, 5, 8 13 . i sci sequence In this, the first two numbery 9 these two numbers the thira, Nace e pase values. Using 0,1,0+1=1 Using the second and as hh number Is calculated as 0,1,1,1+1 yam (0 fine and ie calculated be! ma ymbet the fourt g s0 07 in general the succeeding number is got by adding in ig numbers oF Foy Fn be the fibonacei precedin Lot Fo: Fr . ne 2 the wo eF,=0.F,=1 ecursive formula Foo F yt Fa VP 1 sequence The The & base values ar Program def fib(n): ifn==! return 0 elifn==2 return | else: return( #Main program Dn int(input(*Enter the value of n: *)) ifn<—0: print(*Enter a positive integer’) print(*The Fibonacci sequence for {} 1s: fib(n-1)+fib(n-2)) * format(n)) for iin range( 1 ,n+ 1): print(fib(i),end =) eT 2.70 The output is: e value of n: 5 Enter th nce for 5 is: The Fi bonacci seque! 01123 Figure given belo above function. 7 fib (5) =3 oni + = Tn fib(1) + fib (2) fib(2) + fib@)=1 /\ fib (1) + fib (2) oo The series is n=1=0,n=2=1,n=3=1,n=4=2,n=5=3 (iiiy Program to find the GCD of numbers a and b The base value for GCD of numbers a, b is: gcd (a, b) =a, ifb==0 The recursive formula is: ged (a, b) = gcd (b, a %b), ifa>Oandb>0 Program def ged(a,b): ifb==0: return a else: v=ged(b,a%b) w shows the recursive call o¢ h The put is: Enter tl Enter th the GCD of Ei Enter the v value 0} The GCD of 10. .45 is 5 Anonymous Func of functio function. The general form is: 271 return ¥ on Ct (‘Enter the value ofa ist Enter the Vv alue of.” bei rns .b) -int(” The GCD° fu is {}’ format(a,b,value)) he value of a :89 e value of b :289 89,289 is 1 nter the value ofa :10 fb 45 tion - Lambda Function Lambda or anonymous function is an expression form n that generates a function object as ordinary xpression using arg lambda - keyword arg1, arg2. . .- arguments same as arguments used in ordinary function - indent operator During execution, the expression is evaluated using the passed actual values to the formal arguments arg, arg2, -. The calculated value will be returned to the calling point. 272 Characteristics xpression can be there in g lim i) Only asingle © pr ; ee after indent operator (:) (ii) Lambda functi put retums only 0! execution the lambda function retumng This object can be assigneg He left hand side of the definition ag. (iii) After j function object. variable on the (iv) Using the variable var on the left hand side, 7 function can be called as: var (actual arguments) where: ~ game as used in lambda functio, definition values to be substituted fo, arguments in lambda var actual arguments - (v) The lambda function can use only local variables, it cannot use global variables. (vi) The lambda function can be used inside def and can use the local variables in def. That is it can use enclosing scope variables. Example (i) sum =lambdaa,b,c:a+b+c #a=10,b=20,c=20 s=sum (10, 20, 30) #function calling print (“The value sent by lambda is :’, s) The output is: The Value sent by lambda is : 60 ee . a 2.73 _Jambda a= 5, b 6,c=4:atb+e +) gum i. o u oe) g=sum iC) # functions print (8) 1 =sum (10, 20, 30). # function calling print (sl) he owl’ is: 15 60 yuustrative programs () Program tof find the roots of a quadratic equatioy i def: root(a,b,c,d): ifd>0: rl=(-b+sqrt(d)y/2*a b-sqrt(d))/2*a print(“There are two roots {} and 3” format(rl 12) 12> one root ont) 12=complex(x1,-x2) print(“The roots are complex {} and {}” format(rl 2) #Main program

You might also like