Functions in python

FUNCTIONS

statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.


Image result for function in python


A function is reusable code that can be called anywhere in your program. Functions improve readability of your code: it’s easier for someone to understand code using functions instead of long lists of instructions.

functions can also be re-used and modified so it also increases its testability.



we use this syntax to define a function:
                                        def function(parameters):
                                        instructions or code here
                                        return the value

The def keyword tells Python we have a piece of reusable code (A function). A program can have many functions.



You can define functions to provide the required functionality. Here are simple rules to define a function in Python.
  • Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).
  • Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.
  • The first statement of a function can be an optional statement - the documentation string of the function or docstring.
  • The code block within every function starts with a colon (:) and is indented.
  • The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.

EXAMPLE PRACTICALLY:

We can call the function using function(parameters).


                                        def a(b):
                                        return (b+b)
                                         print(a(5))

output will be :
                                   OUTPUT=10

HOW THIS HAPPENED???

 we defined a function with def and gived him name a and passed a parameter  called b in brackets then we said return b+b which means add a number which a user will give with that same number then we gived him the value in the third line of the code in print function where we said print(a(5))
where we gived the value of unknown b in the code we gived him 5 and then python returned us 5+5 or b+b which is equal to 10 hope it seems to be pretty easy and you understood it !

PARAMETERS:

we can also pass multiple variables in parameters like this code :


                       def a(b,c):
                       print('You called a(b,c) with the value b = ' + str(b) + ' and c= ' + str(c))
                       print('b * c = ' + str(b*c))

                            a(3,2)


Output:

You called a(b,c) with the value b = 3 and c = 2
b * c = 6



HOW IT  WORKS ???


we created a function and passed 2 parameters now then we said print "you called a(b,c) with this value of b='+str(b)' " str(b)" means we are converting the integer or number into a string if u will not create it in a string python will give error nd then we did same thing with b also ! and then we simply passed the numbers of both parameter 3 and 2 and then the code multiplied  both 3multiply by 2 which is equal to 6 that simple !


Calling a Function

Defining a function only gives it a name, specifies the parameters that are to be included in the function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it from another function or directly from the Python prompt. Following is the example to call printme() function −

# Function definition is here
def printme( str ):
   "This prints a passed string into this function"
   print str
   return;

# Now you can call printme function
  printme("I'm first call to user defined function!")
  printme("Again second call to the same function")

When the above code is executed, it produces the following result −

I'm first call to user defined function!
Again second call to the same function



Function Arguments

You can call a function by using the following types of formal arguments:
  • Required arguments
  • Keyword arguments
  • Default arguments
  • 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.
To call the function printme(), you definitely need to pass one argument, otherwise it gives a syntax error as follows −


# Function definition is here
def printme( str ):
   "This prints a passed string into this function"
   print str
   return;

# Now you can call printme function
printme()

When the above code is  executed, it produces the following result:

Traceback (most recent call last):
  File "test.py", line 11, in <module>
    printme();

TypeError: printme() takes exactly 1 argument (0 given)

Keyword arguments

Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters. You can also make keyword calls to the printme() function in the following ways −


# Function definition is here
def printme( str ):
   "This prints a passed string into this function"
   print str
   return;

# Now you can call printme function
printme( str = "My string")

When the above code is  executed, it produces the following result −

My string

The following example gives more clear picture. Note that the order of parameters does not matter.


# Function definition is here
def printinfo( name, age ):
   "This prints a passed info into this function"
   print "Name: ", name
   print "Age ", age
   return;

# Now you can call printinfo function
printinfo( age=50, name="miki" )


When the above code is  executed, it produces the following result −


Name:  miki
Age  50


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 gives an idea on default arguments, it prints default age if it is not passed −


# Function definition is here
def printinfo( name, age = 35 ):
   "This prints a passed info into this function"
   print "Name: ", name
   print "Age ", age
   return;

# Now you can call printinfo function
printinfo( age=50, name="miki" )
printinfo( name="miki" )


When the above code is  executed, it produces the following result −

Name:  miki
Age  50
Name:  miki
Age  35

Variable-length arguments

You may need to process a function for more arguments than you 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.
Syntax for a function with non-keyword variable arguments is this −

def functionname([formal_args,]*var_args_tuple ):
   "function_docstring"
   function_suite
   return [expression]

An asterisk (*) is placed before the variable name that holds the values of all nonkeyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call. Following is a simple example −


# Function definition is here
def printinfo( arg1, *vartuple ):
   "This prints a variable passed arguments"
   print "Output is: "
   print arg1
   for var in vartuple:
      print var
   return;

# Now you can call printinfo function
printinfo( 10 )
printinfo( 70, 60, 50 )

When the above code is  executed, it produces the following result −

Output is:
10
Output is:
70
60
50


thanks for reading !
anonymous

Comments

Popular posts from this blog

wifi attack with kali linux

how to clone a simcard ???