Selenium With Java and Python For Mobile Apps & Web Apps......!

Sunday, 16 October 2016

Function in Python.

Functions
A group of related statements to perform a specific task is known as a function. Python provides two type of functions
1) Built-in functions
2)User-defined functions
Function Definition
The following specifies simple rules for defining a function.
1.      function block or function header begins with a keyword def followed by the function name and parentheses(()).
2.      Any input parameters or arguments should be placed within these parameters. We can also define parameters inside these parentheses.
3.      The first string after function header is called the docstring and is short for documentation string. It is used t explain in brief, what a function does. Although optional, Documentation is good programming practice.
4.      The code block within every function starts with a colon(:) and is indented.
5.      the return statement [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.
Syntax
            def functionname(parameters):
          "function_docstring"
          function_suite
          return [expression]
Example program
            def sum(a,b):
          sum = a+b
          return sum
Function Calling
After defining a function, we can call the function from another function or directly from python prompt. The order of the parameters specified in the function definition should be preserved in
function also function call also.
Example program
            a = int(input("enter first number:"))
     b = int(input("enter second number:"))
     s = sum(a,b)
     print("sum of",a,"and",b,"is", s)
output
     enter first number: 4
     enter second number: 3
     sum of 4 and 3 is 7
            All the parameters in python are passed by reference . It means if we change a parameter which refers to within a function, the change also reflects back in the calling function. Parameters defined inside a function have local scope. The scope of a variable determines the portion of the program where we can access a particular identifier. They are destroyed once we return from the function. Hence, a function does not remember the value of a variable from its previous call.
Example program
            def value_change(a):
          a=10
          print("value inside function:",a)
          return
     a= int(input("enter a number:")
     value_change(a)
     print("value outside function:",a)
output
     enter a number: 2
            value inside function: 10
     value outside function: 2
Function Arguments
We can call function by any of the following 4 arguments
1) Required arguments
2) Keyword arguments
3) Default arguments
4) Variable-length arguments
Required Arguments
Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition. Consider the following example.
Example program
            def value_change(a):
          a=10
          print("value inside function:",a)
          return
     a= int(input("enter a number:")
     value_change()
     print("value outside function:",a)
output
            enter a number: 4
     Traceback (most recent call last):
       File "main.py", line 7, in <module>
         value_change()
     TypeError: value_change() take exactly 1 argument (0 given)
The above example contains a function which requires 1 parameter. In the main program code, the function is called without passing the parameter. Hence it resulted in an error.
Keyword Arguments
When we use keyword arguments in a function call, the caller identifies the argument by parameter name, This allows us to skip arguments or place them out of order because the python interpreter is able to use keywords provided to match the values with parameters
Example program
            def studentinfo(rollno,name,course):
          print("roll no: ",rollno)
          print("name: ",name)
          print("course: ",course)
          return
     studentinfo(course="UG",rollno=50,name="jack")
output
     roll no: 50
     name: Jack
     course: UG
Default Arguments
A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument. The following example shows how default arguments are invoked.
Example program
            def studentinfo(rollno,name,course="UG"):
          print("roll no: ",rollno)
          print("name: ",name)
          print("course: ",course)
          return
     studentinfo(course="UG",rollno=50,name="jack")
     studentinfo(rollno=51,name="Tom")
output
     roll no: 50
     name: Jack
     course: UG
     roll no: 51
     name: Tom
     course: UG
            In the above example the first function call to studentinfo passes the three parameters. In case of second function call to studentinfo, the parameter course is omitted. Hence it takes the default value "UG" given to course in the function.
Variable-Length Arguments
In some cases we may need to process a function for more arguments than specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments. An asterisk(*) is placed before the variable name that holds the value of all non-keyword variable arguments. the tuple remains empty if no additional arguments are specified during the function call. the following shows the syntax of a function with variable-length arguments.
syntax
            def functionname([formal_srguments,]):
          "function_docstring"
          function_suite
          return [expression]
Example program
            def variablelengthfunction(*drgument):
          print("result:",)
          for i in argument: print(i)
          return
     variablelengthfunction(10)
     variablelengthfunction(10,30,50,80)
output
     Result: 10
     Result: 10
     30
     20
     80
Anonymous Functions(Lambda Functions)
            In python, anonymous function is a function that is defined without a name. While normal functions are defined using the def keyword, in python anonymous functions are defined using lambda keyword. Hence, anonymous function are also called as lambda functions. The following are the characteristics of lambda functions.
1.      Lambda functions can also take any number of arguments but return only one value in the form of an expression.
2.      It cannot contain multiple expressions.
3.      It cannot have commands.
4.      A lambda function cannot be a direct call to print because lambda requires an expression.
5.      Lambda function have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace.
6.      lambda functions are not equivalent to inline functions in c or c++.
Syntax
            lambda [arg1 [arg2,.....argn]]:expression
  Example Program
     square = lambda x: x*x;
     n = int(input("enter a number: "))
     print("square of",n,"is",square(n))

output
     enter a number: 2
     square of 2 is 4
Uses of Lambda function
We use lambda function when we require a nameless function for a short period of time. In python we generally use it as an argument to a higher-order function (a function that takes in other functions as arguments). Lambda functions are used along with built-in functions like filter(), map(), etc.
Recursive Functions
Recursion is the process of defining something in terms of itself. A function can call other functions. It is possible for a function to call itself. This is known as recursion. the following example shows a recursive function to find the factorial of a number.
Example program
     def recursion_fact(x):
          if x==1: return 1
          else: return (x*recursion_fact(x-1))
     num = int(input("enter a number:")
     if num>=1:
     print("the factorial of ",num,"is",recursionfact(num))
output
     enter a number: 5
     the factorial of 5 is 120
Explanation
            recursion_fact(5)                 #1st call with 5
     5*recursion_fact(4)               #2nd call with 4
     5*4*recursion_fact(3)             #3rd call with 3
     5*4*3*recursion_fact(2)           #4th call with 2
     5*4*3*2*recursion_fact(1)         #5th call with 1
     5*4*3*2*1                         #return from 5th call
     number = 1
     5*4*3*2                           #return from 4th call
     5*4*6                             #return from 3rd call
     5*24                              #return from 2nd call
     120                               #return from 1st call
Functions with more than one return value
Python has a strong mechanism of returning more than one value at a time. This is a very flexible when the function needs to return more than one value. Instead of writing separate functions for returning individual values, we can return all values within same function. The following shows an example for function returning more than one value.
 Example program
            def calc(a,b):
          sum = a+b
          diff = a-b
     return sum,diff
     a = int(input("enter first number:"))
     b = int(input("enter second number:"))
     s,d=calc(a,b)
     print("sum=",s)
     print("Difference=",d)
output
     enter first number:  10
     enter second number: 5
            sum = 15
     Difference = 5
Practice Questions
1.      Write a python function to check whether a number is even or odd
2.      Writer a python function to test whether a number is within 100 or 1000 or 2000.
3.      Write a python program to calculate the sum of threegiven numbers, if the values are equal then return thrice of their sum.
4.      Write a python function to get a new string from a given string where "is" has been added to the front. If the given string already begins with "Is" then return the string unchanged.
5.      Write a python program to get a string which is n (non-negative integer) copies a given string.
6.      Write a python function that will return true if the two integer values are equal or their sum or difference is 5
7.      Write a python function that takes two lists and returns true if they have at least one common member.
8.      Write a python function to find GCD of 2 numbers.
9.      Write a python function to generate all the factors of a number.
10.  Write a python function to find the sum of digits of a number.
11.  Write a python function to concatenate two strings.
12.  Write a python function called compare which takes two strings s1 and s2 and an integer n as arguments. The function should return true if first character of both the strings are same else the function should return false.
13.  Write a python function to find whether a number is completely divisible by another number.
14.  Write a  python program to display fibonacci series using recursion
15.  Write a python program to find the sum of n natural numbers using recursion.
16.  Write a python program to convert decimal to binary using recursion.


0 comments:

Post a Comment

Translate

Popular Posts

Total Pageviews