FUNCTIONS

 Syntax for defining a function:

def func_name(formal arguments/parameters):
    #statements

calling a function:

func_name(actual argments)

LEGB Rule for checking scope of variable: Local, Enclosing, Global, Built-in 

For passing arguments in a function in any indefinite order :

Func1(arg2=value, arg1=val, arg3=val...) - This method is called keyword arguments

A function can return multiple value which be later picked up by a variable as tuple

if a function doesn't return anything and it is called inside a print statement then the output will be 'None'

Common built-in functions:

  • Round(Number, no. of decimal to be rounded off) 
  • Round(12.5)==12
  • Round(13.5)==14
     if the second argument is in negative then it will start round off the tens, hundreds position and so on. 
  • abs(number) - Returns absolute value as int ot float as per input 
  • help(function/module) eg. print(help(math.cos)) 
  • max, min - If two same values then they would return the one which has lowest positive index
  • type conversions : int,float,str,list ...
  • input()
  • type()
  • range()
  • eval('15+10')==25 # convert string to int or float accordingly

Types of arguments:

1.) Positional - Actual parameter need to be defined in the same order as in defining

2.)Default- If  Actual parameter is not given then the function will use default value as provide while defining

NOTE: While defining a function with default arguments then they need to start from right to left ie it can't happen that a formal argument has a predefined value but one on its right doesn;t.

3.)Keyword Arguments

4.) Variable length - args,kwargs :

def func_name(*n):

here n is iterable object that allow variable number of actual argments

NOTE: While calling a function we can use positional and keywords arguments simultaneously but we need to specify positional arguments before keywords arguments.

NOTE:If we pass an immutable object to a function then it doesn't affects it value but if an mutable object like list is passed to a function then any changes are made in the original object.

Specifying the keywords local or global before a keyword within a function a block changes it scope.

A classical practice in other programming languages is to write all the statements in a 'main' function the then execute the program to do same:

def main():

    #code

if __name__==__main__"":

    main()

Comments

Popular posts from this blog

Dictionary and Sets in Python

Insertion Sort in python

Grid Printing Code for Python