You are on page 1of 6

Functions 

Friday, July 22, 2022  5:59 PM 

A function is a group of statements that exists within a program for the purpose of performing a  

specific task. 

Advantages of functions: 
1. Easier program handling. 
2. Reduced line of codes. 
3. Easy updating. 
 
Types: 
1. Built-in Functions 
2. Modules 
3. User-defined Functions 
 
BUILT-IN FUNCTIONS 
 

Pre-defined functions that are already available in Python. 

> They are available in the standard library and do not require import. 
> Provide efficiency and structure. 
> Faster and more powerful programming. 

 
I. Type conversion functions: 

Allow conversion from one data type to the other. 

  i) int(): 

     Converts to integer type. 

     When no argument is passed, returns 0 

     Syntax: int(value) 

ii) str(): 

     Converts to string type. 

     Syntax: str(value) 

iii) float(): 

     Converts to floating point numbers. 

     When no argument is passed, returns 0.0 

     KeyPoint: Returns numbers as it is. 

                        Completes operations (in strings too). 

                                    >>>float(34+33/11) would give 37.0 

                        Accepts –ve values. 

     Syntax: float(value) 

 
II. input() function: 

Enable accepting input in desired form from the user without evaluating it's value. 

Default data type is str until a particular one is specified. 

Syntax: variable=input("Enter data: ") 

 
III. eval() function: 

Evaluates the value of a string. 

KeyPoint: Takes only string as argument. 

                                   >>>eval("1+2") would return 3 

                   Evaluates the str as a number and returns numeric result. 

                   Returns both int and float depending on the result. 

Syntax: eval("operation ") 

 
IV. max() and min() functions: 

Used to find maximum and minimum value respectively. 


They take two or more arguments and return the max/min value. 

Syntax: max(a1, a2, a3) 

              min(a1, a2, a3) 

 
V. abs() function: 

Returns absolute value of a single number. 

KeyPoint: Data type depends on argument. 

                  Gives both int and float point values. 

                  Always returns a +ve value. 

Syntax: abs(argument) 

 
VI. type() function: 

Determines the data type of variable (it's enclosed value). 

Syntax: type(variable) 

 
VII. len() function: 

Returns length of the specified/given object. 

Accepts both sequence and mapping data types. 

Syntax: len(object) 

 
VIII. round() function: 
Returns the number rounded up-to the specified decimal places. 

Default decimal place is 0. 


When 5 or >5, the integer or pth value is increased by 1. 

Takes two arguments- 

           n: the number 

           p: no. of digits up to which n is rounded up 

  i) when 'p' is not specified: 

      Rounds up to 0 decimal places. 

      Returns an integer. 

ii) when 'p' is zero: 

      Rounds up to 0 decimal places. 

      Returns a float point value. 

iii) when 'p' is +ve: 

      Rounds up to p by checking (p+1)th digit. 

      Returns a float point value. 

iv) when 'p' is –ve: 

      Rounds up to p by checking (p-1)th digit. 

      All trailing decimal places beyond the . are converted to zero. 

      Returns a float point value. 

Syntax: round(n,p) 

 
IX. range() function: 

Defines the series of nos. 

Is particularly useful in 'for' loops. 

Syntax: range(n) 

              range(start, end) 

              range(start, end, stop) 

 
 
 
 

MODULES 
 

A module is a python file that contains a collection of related functions. 

Important relevant terms: 


• Modularization: The approach of making a set of functions in a file (a module). 

                              Makes program easier to understand, test and maintain. 


• Libraries: The commonly-used modules in Python are known as libraries. 
 
Importing Modules 
 
1. Importing entire modules: 

For one- 

               Syntax: import <module_name> 


For multiple- 

               Syntax: import <module_name1>, <module_name2>, <module_name3>,  . . . 


2. Importing selective objects from a module: 

To access all objects- 

                Syntax: from <module_name> import* 

To access a particular fun()- 

                Syntax: from <module_name> import <object_name> 

To access multiple fun()- 

                Syntax: from <module_name> import <obj_1>, <obj_2>, <obj_3>, . . . 


 
When an import statement is executed, the following operations are performed: 

  i) Search for the file, <module_name>. 

ii) Create space where modules definition and variable are created. 

iii) Execution of statements in module. 


 

#import statement: 

  The import statement creates an access to the functions/modules in a program. This is done by 
  specifying the allotted name, separated by a dot (this dot is known as dot notation). 
 
1. Math module 

Syntax: 

        import math 

        x=10.0 

        math.ceil(x) 

>>> 10 
ceil(x)  floor(x)  pow(x,y)  fabs()  sqrt(x) 
Smallest integer that is Largest integer that is less Value of xy in float Absolute positive Square root of x.  

greater than or equal to x.  than or equal to x.  point value.  value in float point.  Condition: x>0 

log10(x)  cos(x)  sin(x)  tan(x)  help() 


Base-10 logarithm of x.  Cosine of x in radians.  Sine of x in radians.  Tangent of x in Purpose of a
radians.  function and how
to use it. 

 
 
 
 
 
 
2. String module 

i) random module 
randrange()  random()  randint() 
Generates an integer b/w it's lower and Generates a random number between 0 Generates a number in the inclusive
upper argument. 
and 1, i.e., it's range is (0.1, 1.0).  range (a,b) such that a<=N<=b 
Default lower: 0 

Default upper: -1 


random.randrange()  random.random()  random.randint(a,b) 
random.randrange(start,stop,step) 

uniform()  choice()  shuffle() 


Returns a random float-point number Makes a random selection from a Shuffles/swaps contents of a list. 
between two numbers.  sequence (list, tuple, string, etc.) 
random.uniform(a,b)  random.choice(sequence)  random.shuffle(list) 

 
USER-DEFINED FUNCTIONS 
 

Python allows user to write their own function(s) which can be combined into module. 
Syntax: 

             def function_name(comma_separated_parameters):             function def 

                    Statement(s) 
 
1. Keyword 'def' marks the start of function header. 
2. A function name to uniquely identify it.  
3. Parameters (arguments) through which we pass values to a function. They are optional.  
4. A ':' (colon) to mark the end of function header. 
5. Valid Python statements of the same indentation level make up the function body. 
6. An optional return statement to return a value from the function. 
7. Function must be called/invoked to execute its code. 
 
Void Function:  
• A function that doesn't contain a return statement. 
• e.g.: def display(): 
                print("This is an example of a void function.") 
 

Importance of Indentation: 
Python functions don't have any explicit beginning or end (like curly brackets) to indicate the start
or end for function, they have to rely on indentation for the same. 
• They indicate the beginning and end of a user-defined function. 
• Returns "expected an indented block" error. 
• The indentation should remain the same for the entire body of the function. 
 
return command: 
Syntax: 

             def function_name(arguments): 

                    return<value> 
• It is used to end the execution of a function.                                termed as 
• Specifies the to be returned value to the calling function.         "fruitful function" 
 
 
 
 
 
Returning multiples: 

       i) as variables: 

▪  
 
 
 
 

             ii) as a tuple:   

 
 
 
 
• Returning without variable:   

 
PARAMETERS 
 

Parameters are the value(s) provided in the parenthesis when we write function header.  
1. These are the values required by function to work.  
2. For more than one values are listed in parameter list separated by comma.  
3. Example:  

            def calc(a,b): 


The values used in function call are actual parameter. 

The values used in function header are formal parameter. 


 
ARGUMENTS 
 
Arguments are the value(s) provided in function call/invoke statement.  
1. List of arguments should be supplied in same way as parameters are listed.  
2. Parameters to arguments bounding should be 1:1. 
3. No. of parameters = No. of arguments 
4. Example:  

            Arguments in function call  

            >>> calc(10,5) 


5. The values used in function call are actual argument. 
6. The values used in function header are formal argument. 
7. Types of arguments:  

 
 
 
 
 
 
 
 
PASSING OBJECTS AS ARGUMENTS 
 
  ARRAYS/LISTS  STRINGS  TUPLE  DICTIONARY 
1.  Are mutable and can be Are immutable and used as Are immutable and used as Are mutable and can be
passed as variables.  pass by value.  pass by value.  passed as variables. 
2.  Can be edited and viewed.  Can only be viewed.  Can only be viewed.  Can be edited and viewed. 
Extra  Lists are implemented as To modify a new string is To modify convert to list, - 
arrays.  created and concatenated.  modification is valid inside
Lists>>Arrays  
only. 
(as lists are homogenous.) 

• Outside the function, any modifications and calculations get deleted automatically. 
 
SCOPE OF VARIABLES 
 
Scope of variables is that part of the program which holds the current set of parameters and their values. 

There are two types of scope of variables: 


  GLOBAL SCOPE  LOCAL SCOPE 
Keyword  Module  Function 
Definition  Name assigned at top of function.  Name(s) assigned within the function. 
Condition  Can be accessed inside/outside of function.  Can not be accessed outside of the function. 

You might also like