0% found this document useful (0 votes)
18 views

Chapter 2 Cs Class 12

Computer science
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
18 views

Chapter 2 Cs Class 12

Computer science
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 12
‘ats, ‘ Functions 2.1 INTRODUCTION So far we have introduced variables, operators, input/output operations, data types and execution of a program in Python. The codes we have studied till now have been single, conditional and iterative sequence of instructions and were small in size. We can easily work with problems whose solutions can be written in the form of small Python programs. However, as a problem becomes complex, the program also increases in size and complexity, and it becomes difficult and cumbersome for a programmer to keep track of the data and control statements in the whole program, Thus, Python provides the feature to divide a large program into different smaller modules. These modules are known as functions which have the responsibility to work upon data for processing, It is difficult and time-consuming to interpret a large program every time there is a slight modification in the code. But if that program is divided into a number of small functions {also called sub-programs), then the whole task becomes easy and saves a lot of time and effort. If required and if it becomes necessary, the sub-programs (or sub-problems) can be further divided into still smaller programs, and the process of dividing a program into a set of programs of smaller size can be continued up to any appropriate level. ‘Therefore, functions provide a systematic way of problem-solving by dividing the given problem into several sub-problems, finding their individual solutions, and integrating the solutions of individual problems to solve the original problem. This approach to problem-solving is called stepwise refinement method or modular approach or divide and conquer approach as shown below (Fig. 2.1). This program is one long, complex __ In this program, the task has been divided Sequence of statements, into smaller tasks, each of which is performeq | bya saparste Neen 1 |def function1(): statement statements statements statements statement function statements atacehent statements ape def function2(): statements Seer statements function statement statements statements seen statements Meee es def function3(): statements statement naeien statements statement statements statement i statements ae . statements def functiond (): statements | statement , statements statement function statements statement statements a statements statements statements 2.2 FUNCTIONS IN PYTHON A function is a group of statements that exists within a program for the purpose of performing a specific task. Instead of writing a large program as one long sequence of instructions, it can be written as several small functions, each performing a specific part of the task. They constitute line of code(s) that are executed sequentially from top to bottom by Python interpreter. It is simply a group of statements under any name, i,, function name, and can be invoked (called) from another part of the program. Consider an example of School Management Software which constitutes various tasks like registering students, fee collection, issuing books from library, ‘TC (transfer certificate) generation, result declaration, etc. In such cases, we have to create different functions for each task to manage software development. This can be better explained using the example of a dishwasher from our day-to-day life. (Fig. 2.2), A dishwasher works like a function. You put dirty dishes in the dishwasher and when you press the start button, it performs several tasks like adding detergent and water, washing dishes, and even drying them out. OU Cao TUT eA Dirty Dishes Function: wash. dishes 1. Add water/detergent | 2. Wash dishes 3. Dry them Return Value (Output) Fig. 2.2: Working of a Dishwasher similar to a Python Function And, thus, you get clean dishes as a result (output), Functions are also similar as they take some data as input and, depending upon the instructions/ code given, perform the defined task and give some output in the end. In Python, we have worked with the script mode in the Python revision chapter, which provides the capability of retaining our work for future usage. For working in script mode, we need to write a function in Python and save it in the file having .py extension. A Python function is written once and is used/called as many times as required. Functions are the most important building blocks for any application in Python and work on the and conquer approach. > (Advantages of Functions: Functions offer the following advantages over sequential approach of programming: 1. Program handling becomes easier: Only a small part of the program is dealt with at a time. 2. Code reusability: A Python function can be defined once and used many times. So, it results in code reuse; you don’t need to write the same code more than once. 3. Compact code: While working with functions, a common set of code is written only ‘once and can be called from any part of the program which reduces lines of code and programming overheads. 4. Easy updation: In case a function is not used in a program, the same set of code which is required in multiple programs has to be written repeatedly. Hence, if we wish to make any change in a formula/expression, we have to make changes at every place, else it will result in erroneous or undesirable output. With function, however, it is required to make changes to only one locationXwhich is the function itself). Functions can be categorized into the following three types: (i) Built-in Functions (ii) Modules Built-in Library (iii) User-defined Functions Python provides built-in functions that convert values from one data type to another, which are termed as type conversion functions (Pig. 2.3(a)). (® intQ: The int() function takes any value and converts it into an integer (Statement 1), int() can convert oating-point values to integers but it doesn’t round off; it chops off the fraction part (Statements 3 and 4). However, if we give a string Value as ay argument to int(), it will generat an error (Statement 5) SOE a a ngument is Passed, inti) returns 0, If ni * str() function converts its argument into a string (Statement 2). 1 ee eSebtP80eNNaM, tae a0 2058, Salone) DES TOT Dae (Intel) ) on wansa Type “copyright, screditer or de> ane (rags) oe “License ()* for more information, “s converts the string argument to integer >>> strqaas) ‘Soveren' converts the numer vue to string tas" En t20t-88) =e, Meter converts the feet erpumentte nagar $96 6-94.2) —s statement4, Ane ("Hed20") —e statement gener Traceback (most x File "cpysneiis: ine ("Helio") Vatuetsrer: ‘chops off the floating pont number to integer Fig. 2.3(a): Type Conversion Functions in Python (iii) float(): float function converts inte ers and strings into floating- (Fig.2.3(b)). This function treats diffe point numbers rent types of parameters as expl lained below: Mar 28-2038, 16:07:46) MSE v.00 3a ype, onprsighe", coredica or ~licenee()* tor mare internation, >>> Heat ao, Soe oat ea1.70 >>> frowecane2s) >>> Coat a2e3/a) Fig. 2.3(b): floati) Type Conversion Function a > Ifthe argument is a number, floa = retu float(26) returns 26.0, and mata seh fitch He oe If the a Pate Por eae Weare the expression is evaluated and float() returns its > If the arguinent i" nee eturns $8.0 and float(12+3/4) returns 12.75. a string containin, iy correct format, loat() returns the Mes ss */~ sign and a floating point number in e float float('3.14159") returns 3.14159, loat value represented by this string. For example, > Ifthe string argument contains any character other than leading +/- sign and floating point number in the correct format, th n , then float() resul ; ia following statements will result in errors: 7 SOS TS a float('40.63+’), float(‘86.7~'), float(‘35+4/7') Gah) if no argument is passed, float() returns 0.0. B) input() function Itenables us to accept an input in the form of string from the user without evaluating its value. It provides the most common way to gather input from the keyboard. The function input() continues to read input text from the user until it encounters a new line. For example, name input ("Enter a name:') print (‘Welcome', name + 'Pleasure to meet you') & Prog2.py - C/python36/prog2.py 3.6.5) — © MES File Edit Shell Debug Options Window Help Python 3.6.5 (v3.6.5: f59c09S2b4, Mar 26 2018, 16:0 = (Invel)} on wansz | Type "copyright", "oredite™ or "License ()" for more informacion. 46) [MSC v.2900 82 Ba ~ RESTART: C:/python36/prog2-py “-=--====eenmmmmmee Enter your name: Rinke Welcome RinkuPleasure to meet you >> The input() function allows to insert a value into a program. input() function returns a string | value that can be converted into integer data type. For example, ; > To calculate the Selling price of an item [a -vester-< fe tae fort hor Opts Hatem te : Seatbrice > intlinput ("Enter cost Pricer) TitingpoaarocarrepenPpienticnireie Bi - OX Profit = int (input (Enter Profit: ')) ‘Selling Price = costPrice + Pro! print('Jelling Price: ', Selling Price) = — = tan cae ia WEF & ere tic Tae vce matamaost? sar mun 00 ana Rabe a nesrarr: <1 /cners/over2/apptata/ocal /Progeans/PYtRCA/ Ries cat iat @ eter frotits 30 Setting prise: "v0 Here, int() function is used to convert the inputted cost price and profit, which is of string ‘type, into integer data type. > input() method can also be used without arguments Consider the code snippet: Here, input() function has been used without displaying any message to >>> selapaeqy the user. As per the nature of input() method, it will extract whatever ||,,> fae input is being entered from the keyboard, like ‘hello’ has been entered "e140" and then displayed in the next line using print() function. eval() function This function is used to evaluate the value of a string. eval() function takes and evaluates as per the input fetched, enclosed within single quotes (can be referred to as a string) as an argument, evaluates this string as a number, and returns the numeric result (int or float as the case may be). If the given argument is not a string, or if it cannot be evaluated asa number, then eval() function results in an error. For example, -5 (v3.6.5:25900002bH, Mar 28 2018, 1610714 ~ ©) (usc v.1900 32 bit (Zneel)} cn wins? Type “copyrigne", “credits” or “License ()* for more 4 TrpeBsror: eal arg 1 mst be a string, Dycas or code cojece i TE) Insimple words, the eval() function evaluates the “String” like a python expression and returns the resultas an integer. For example, poanaec may ee fotiiusteating eval) using Tnpat Jere = eva input "Eater any nuaber of your ctoice")) [prise (eva) Prine (eype eva)) Dd) 5) As is evident from the output, eval() function returns the evaluated expression as 80 in the form of an integer with string as input. 50 + 30 is an expression that returns 80 as a result. max() and min() functions These are used to find maximum and minimum value respectively out of several values. The max() function takes two or more arguments and returns the largest one. For example, (v8. 6.818900 tse v. (invel)} on wins? Type "copyright", "credits" or "License()" for more information d>> maxi, 12, 6, 15) as >>> max(-2, -7, 98, -4) 2 5d> X= max(S9, 80, 95.6, 98.2) >>> print ("Maximum Value", x) Maximum Value 95.6 In case of String type argument, ASCII values of characters are compared for retrieving highest and lowest values using max() and min() functions. [>>> maxc*Deini”, tugjain® rat™, "Agartala") The min() function takes two or more arguments and returns the smallest item. For example, Mar 28 2018, 16078 900 32 bit (Incei)} on wins? Type "copyright", “credits” or “License()* for more information, >>> min(23, =108, 5, 2) “108 >>> min(7, 26, 0, 4) ° de> ys min(*hello', ‘now’, ‘are'y ‘you', 'Siz") 3o> print ("Minimum Value: *, ¥) Minsmum Value: Sir Explanatio The above lines of code shall print ‘Sir’ as the output because the ASCII value of 's’ is smallest, ie, 83, which is an uppercase letter and less than the rest of the words in lowercase— h Chelle’), a (‘are’) and y (‘you’) whose ASCII codes are 104, 97 and 121 respectively. ‘a’ and 0 (zero) is 65, 97 and 48 respectively. abs() function ‘The abs() function returns the absolute value of a single number. It takes an integer or float humber as argument and always returns a positive value. It returns a floating or integer number depending upon an argument. FA) )} on wans2 copyright", “credits” or "License()" for more information. >>> abs (-80) 50 >>> ans cas) 4s >>> abs(-20.6) 30.6 >> type() function If you wish to determine the data type of a variable, i.e, what type of value does it hold/point to, then type() function can be used. de> type. (8.2) Zclaes tele >>> eye 22/7) doo" eywe 22/7") 22 cue (teste Fr==0") THe Boolean argument given to type() do> type ese)» function should have T (capital lette) for eee ee? ; > | True and F (capital letter) for False; otherwise it will generate an error. Soo tape (8) Pychon 3.6.8 (v3 0 32 bir (Invel)} on wind? Type “copyrighe™, “oredite* or “License()" for more information. >>> xel0 >>> eype (x) “elas. *ant'> >>> x090.8 So> pine (0) 30.5 >>> cype (8) Zelass ‘£loee'> >>> x oH" >>> expe () oles '#tr'> >» G)_len() function 4) ‘The len() function returns the length be a sequence (string, tuple or list) 0 For example, (the number of items) of an object. The argument may a mapping (dictionary), 1018, 16107 tus. Type "copyright", “credite* or *License()" for more infornat: >>> str® ‘Hello World" PA eae >>> Len(see) a >>> xe 2,2,3,4) >>> ten (x) 4 >>> = (wince! >>> lenis) ‘ >>> ae(1itcs", 2:°1P*, 3 >>> Tenia) s + ‘Spring’, ‘sumer’, ‘fa12") physics") round() function The round() function rounds a given number to the specified number of decimal places and returns the result. By default, round() function rounds a number to zero decimal places. The round() function takes two arguments. Syntax: Here, n is the number/expression to be rounded and p is the number of digits up to which n is to be rounded. n is a mandatory argument and can be an integer or a floating-point value while p is an optional argument and must be an integer. ound (n, p) The situations given below exhibit the behaviour of round{) for different sets of values for n and p: (pis not specified: n is rounded up to 0 digits of decimal and the result is an integer. If the first digit after the decimal value is 5 or >5, then the integer number is increased by 1. Forexample, _ round(12.452) returns 12 Here, first digit after the decimal number is 4, so the number remains unchanged. round(12.534) returns 13 Here, first digit after the decimal number is 5, so the number is increased by one. (il) pis 0: n is rounded up to 0 digits of decimal and the result is a float value. For example, _round(12.452,0) returns 12.0 round(12.534,0) returns 13.0 (iii) pis positive integer: n is rounded up to p by checking (p+1)" digit; ifitis 5 or >5, then p" digit is increased by 1 and the result is a float, For example, _round(12.452,1) returns 12.5 round(12.534,2) returns 12.53 es, le eo ne aan 0 (iv) p isa negative integer: n is rounded up to p digits before the decimal by checking the p* digit; if itis § or >5, then the (p-1)" digit is increased by 1, all trailing p digits arg converted to zero and the result is a float. The trailing p digits are rounded off to 9 if case of negative value of p. For example, round(1234.56,-1) returns 1230.0 round(1258.4,-2) returns 1300.0 range() function The range() function is used to define a series of numbers and is particularly useful in ‘for loops. For example, >>> range (5) range (0, 5) The expression range(5) above generates a series of integers from zero and ends with 4 (5-1). © To show the list of numbers, we can use the command list(range(n)) >>> list (range (5)) POA 2," 3,4] © Wecan explicitly define the starting and ending number by specifying the two arguments for beginning and ending numbers: Syntax: range (begin, end) For example, >>> range (5, 9) range (5, 9) To show the list: >>> list (range(5, 9) [5, 6, 7, 8] ‘The above examples of range() demonstrated an increment of 1. We can change the way Python increments the number by introducing a third argument, the ‘step’ It can be a negative oF positive number, but never zero. Syntax: range(begin, end, stop) For example, >>> range (10, 71, 5) range(10, 71, 5) Invoking the list, we'll see this sequence of numbers: >>> list (range (10, 71, 5)) (10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70) {asthe programs become more lengthy into smaller segments called modutes, Amodule is a ~ enone functions and variables defined in Separate files. A module is simply file that contains Python code or a series of instructions and is saved with .py extension. nother ental ak en Stored in a file is called MODULE and this approach is known as modularization, which makes a program easier to understand, test and maintain. wee on - Ee ae Saar each module should contain functions that perform rela . some commonly-used modules predefined tasks and they are called libraries, Tae ee oes Modules: also make it easier to reuse the same code in more than one program. If we have written a set of functions that is needed in several different Programs, we can place those functions in a module. Then, ‘we can import the module in each Program that needs to call one of the functions. Once we import a module, we can refer to any of its functions or variables In our program, and complex, there arises a need for the tasks to be split Importing Modules in a Python Program Python provides import keyword to import modules in a program. There are two methods to import modules: (i) Importing entire Module(s): An entire module can be imported in the current program using import statement. The syntax to import the entire module is: import< ule name> For example, import math It gives access to all the functions of math module. = Toimport multiple modules in a program, the syntax is: import_ import* For example, from math import* Itgives access to all the functions of math module. * To import a particular function of the module, the syntax is: from import For example, from math import sqrt This will import only sqrt() function from the math module. * To import multiple functions, the syntax is: Le name> import sqr + pow, pi This will import multiple functions, ie, sqrt, pow and pi functions of m ath module ing Program. As Is evident from the screenshot, it is not required to use math module Prefixed with the function name as it has already been imported using from statement. To import all methods from a module, the syntax is: mmodulename import* (Import everything from the file) This statement is used to import all the functions and const. For example, ‘ants from a module. For example, import math (2) Search for the file, “math.py” (b) Create space where modules definition a1 ind variable will be created, (€) Execute the statements in the module. import math result = math. sqrt (64) print (result)

You might also like