Tuesday, 4 April 2017

python functions: user defined functions

User Defined Functions in python:


Syntax:

def <function_name>(param1,param2, ...  ,param_n):

            """ doc string """

            statement1

            statement2

            statement3

            [return <value>]

Above shown is a function definition which consists of following components:

  • Keyword def marks the start of function header.
  • A function name to uniquely identify it. Function naming follows the same rules of writing identifiers in Python.
  • Parameters (arguments) through which we pass values to a function. They are optional.
  • A colon (:) to mark the end of function header.
  • Optional documentation string (docstring) to describe what the function does.
  • One or more valid python statements that make up the function body. Statements must have same indentation level (usually 4 spaces).
  • An optional return statement to return a value from the function.


def f1():      #function definition

    print("HI Siva")

f1()           #function calling


HI Siva


Advantages of user-defined functions:

  • User-defined functions help to decompose a large program into small segments which makes program easy to understand, maintain and debug.
  • If repeated code occurs in a program. Function can be used to include those codes and execute when needed by calling that function.
  • Programmers working on large project can divide the workload by making different functions.

def f1(x,y):           #function definition

    print(x,y)

f1("HI","Siva krishna")  #function calling


HI Siva krishna


  • The variables which are declared within the function header are known as parameters.
  • We can define any number of parameters to a function, At the time of calling the function we have to pass the values to the parameters. 
  • The values which are passed to the parameters of  a function at the time of calling the function are known as arguments.


return statement:-


  • return statement is used to return the execution of the function is over. 
  • If we don't assign function call to a variable the return value of a  function will become as garbage collected. 
  • If the programmer doesn't define the return statement explicitly in the function then by default  the function returns none. 
  • While executing the function if control reached to the return statement of a function then remaining part of the function will not be  executed.

def add(a,b):

    c=a+b

    return c

x=add(10,20)

print(x)

print(add(5,6))

print(add(8,9))

30

11

17


def absolute_value(num):

   """This function returns the absolute
      value of the entered number"""

   if num >= 0:

       return num

   else:

       return -num


print(absolute_value(2))

print(absolute_value(-4))


2

4


def absolute_value(num):

   """This function returns the absolute
      value of the entered number"""

   if num >= 0:

       print(num)

   else:

       print(-num)


print(absolute_value(2))

print(absolute_value(-4))


2

None

4

None


def my_addition(x,y):

   """This function adds two
   numbers and return the result"""

   sum = x + y

   return sum

num1 = float(input("Enter a number: "))

num2 = float(input("Enter another number: "))

print("The sum is", my_addition(num1,num2))


Enter a number: 4

Enter another number: 6

The sum is 10.0


def my_addition(x,y):

   """This function adds two
   numbers and return the result"""

   sum = x + y
   
num1 = float(input("Enter a number: "))

num2 = float(input("Enter another number: "))

print("The sum is", my_addition(num1,num2))


Enter a number: 7

Enter another number: 6

The sum is None


Types of parameters:-

We can define two types of parameters to a function

  • Non-default parameters
  • Default parameters

Non-default parameters:-

Defining the parameters without assigning the values explicitly are known as Non-default parameters.

def f1(name,msg): 

    print("hi",name," ",msg)

f1("siva","good mrng")


hi siva   good mrng

Default parameters:-

Defining the parameters by assigning values explicitly are known as default parameters.

We need not pass arguments to the default parameters of a function.

def f1(name="siva",msg="good mrng"): 

    print("hi",name," ",msg)

f1()


hi siva   good mrng


both Default and non default parameters

def f2(name,msg="Hw r u"):

    print("hello",name,msg)

f2("siva krishna")

hello siva krishna Hw r u


def f2(name="siva",msg):   

    print("hello",name,msg)

f2("siva","Good Evening")


display the error message

After defining the default parameters we are not allowed to define non-default parameters. It give syntax error .


Types of arguments:-

We can pass the two types of arguments to the functions.
  • Non-keyword arguments
  • Keyword arguments

Non-keyword arguments:-

Passing the arguments directly without assigning the arguments to the parameters is known as Non-Keyword arguments.

Non-keyword arguments will work based on the positions.

def f1(name,msg):

    print("hai",name,"",msg)

f1("siva","good mrng")


hai siva  good mrng


def f1(name,msg):

    print("hai",name,"",msg)

f1("good mrng","siva")


hai good mrng  siva

Keyword arguments:-

Passing the arguments to the function by assigning the arguments to the parameter names are known as keyword arguments.

def f1(name,msg):

    print("hai",name,"",msg)

f1(name="siva",msg="good mrng")


hai siva  good mrng


def f1(name,msg):

    print("hai",name,"",msg)

f1(msg="good evng",name="siva")


hai siva  good evng


Both keyword and non keyword arguments:

def f1(name,msg):

    print("hai",name,"",msg)

f1("siva",msg="good mrng")


hai siva  good mrng


def f1(name,msg):

    print("hai",name,"",msg)

f1(name="siva","good mrng")


shows the error

After keyword arguments we are not allowing to use non-keyword arguments.

Arbitrary arguments :

If we define the arbitrary parameters to a function we can pass 0 or more arguments to that function.

Arbitrary argument type will be taken as a tuple.

def f1(*x):
    print(type(x))
    print(x)
    print(len(x))
f1()
f1(10,20)
f1(10,20,30)
f1("hyd","Ban","Delhi")

<class 'tuple'>
()
0

<class 'tuple'>
(10, 20)
2

<class 'tuple'>
(10, 20, 30)
3

<class 'tuple'>
('hyd', 'Ban', 'Delhi')
3

Both normal arguments and arbitrary arguments:

def f2(x,y,*z):
    print(x,type(x))
    print(y,type(y))
    print(z,type(z))
f2(10)

Traceback (most recent call last):
  File "E:/python_practice/examples/arbitrary arguments.py", line 14, in <module>
    f2(10)
TypeError: f2() missing 1 required positional argument: 'y'


def f2(x,y,*z):
    print(x,type(x))
    print(y,type(y))
    print(z,type(z))
f2(10,20)

10 <class 'int'>
20 <class 'int'>
() <class 'tuple'>


def f2(x,y,*z):
    print(x,type(x))
    print(y,type(y))
    print(z,type(z))
f2(10,20,30)

10 <class 'int'>
20 <class 'int'>
(30,) <class 'tuple'>

def f2(x,y,*z):
    print(x,type(x))
    print(y,type(y))
    print(z,type(z))
f2(10,20,30,40,50)

10 <class 'int'>
20 <class 'int'>
(30, 40, 50) <class 'tuple'>

def f3(*x,y,z):
    print(x,type(x))
    print(y,type(y))
    print(z,type(z))
f3(10,y=20,z=30)

(10,) <class 'tuple'>
20 <class 'int'>
30 <class 'int'>

def f4(*x,y,z):
    print(x,type(x))
    print(y,type(y))
    print(z,type(z))
f4(10,20,30)

Traceback (most recent call last):
  File "E:/python_practice/examples/arbitrary arguments.py", line 28, in <module>
    f4(10,20,30)
TypeError: f4() missing 2 required keyword-only arguments: 'y' and 'z'

No comments:

Post a Comment