Function is a named sequence of statements that performs a computation. function is a device that groups a set of statements so they can be run more than once in a program. Functions also can compute a result value and let us specify parameters that serve as function inputs, which may differ each time the code is run. Coding an operation as a function makes it a generally useful tool, which we can use in a variety of contexts.

When you define a function, you specify the name and the sequence of statements. Functions are useful for breaking up a large program to make it easier to read and maintain. They are also useful if you find yourself writing the same code at several different points in your program. You can put that code in a function and call the function whenever you want to execute that code. 
for example :-

type(32)                                                          
<class 'int'>      

The name of the function is type. The expression in parentheses is called the argument of the function. The argument is a value or variable that we are passing into the function as input to the function. The result, for the type function, is the type of the argument.

It is common to say that a function “takes” an argument and “returns” a result. The result is called the return value

As you already know, Python gives you many built-in functions like print(), etc.

Built-in functions

Python provides a number of important built-in functions that we can use without needing to provide the function definition. The creators of Python wrote a set of functions to solve common problems and included them in Python for us to use.
The max and min functions give us the largest and smallest values in a list, respectively:


>>> max('Hello world')                                            'w'              
>>> min('Hello world')
' '      

The max function tells us the “largest character” in the string (which turns out to
be the letter “w”) and the min function shows us the smallest character (which turns out to be a space).
Another very common built-in function is the len function which tells us how many items are in its argument. If the argument to len is a string, it returns the number of characters in the string.


>>> len('Hello world')   
11             
>>>      

These functions are not limited to looking at strings. They can operate on any set of values, as we will see in later chapters. You should treat the names of built-in functions as reserved words (i.e., avoid using “max” as a variable name).


Basics

def Statements, The def statement creates a function object and assigns it to a name. Its general format is as follows:



def 
<name>(arg1, arg2,...argN):
    <statements>                                                          
      


As with all compound Python statements, def consists of a header line followed by a block of statements, usually indented (or a simple statement after the colon). The statement block becomes the function’s body—that is, the code Python executes each time the function is called.

The def header line specifies a function name that is assigned the function object, along with a list of zero or more arguments (sometimes called parameters) in parentheses. The argument names in the header are assigned to the objects passed in parentheses at the point of call.

Function bodies often contain a return statement:



def 
<name>(arg1, arg2,...argN):
    <statements>
    <statements>
    <statements>                                                      ...          
    return < 
value >



The Python return statement can show up anywhere in a function body; it ends the function call and sends a result back to the caller. The return statement consists of an object expression that gives the function’s result. The return statement is optional; if it’s not present, the function exits when the control flow falls off the end of the function body. Technically, a function without a return statement returns the None object automatically, but this return value is usually ignored.

for example--

As we have discussed earlier, Functions are defined with the def statement. The statement ends with a colon, and the code that is part of the function is indented below the def statement. Here we create a simple function that contains prints statement to print Hello Universe.

#create and assign functions

def 
hello:  
        
    #Body executed when called
    
    print
('hello Universe
)                                       
   
   


The first two lines define the function.One use for functions is if you are using the same code over and over again in various parts of your program, you can make your program shorter and easier to understand by putting the code in a function. For instance, suppose for some reason you need to print a box of stars like the one below at several points in your program.

def is a keyword that indicates that this is a function definition. The name of the function is hello. The rules for function names are the same as for variable names: letters, numbers and some punctuation marks are legal, but the first character can’t be a number. You can’t use a keyword as the name of a function, and you should avoid having a variable and a function with the same name.

The empty parentheses after the name indicate that this function doesn’t take any arguments. Later we will build functions that take arguments as their inputs. The first line of the function definition is called the header; the rest is called the body. 

The header has to end with a colon and the body has to be indented. By convention, the indentation is always four spaces. The body can contain any number of statements.


Calling Function

Defining a function gives it a name, specifies the parameters that are to be included in the function and structures the blocks of code.

Our function is now fully defined, but if we run the program at this point, nothing will happen since we didn’t call the function. So, outside of our defined function block, let’s call the function with hello()

You should receive the following output:

Output : Hello Universe

Functions can be more complicated than the hello() function we defined above. For example, we can use for loops, conditional statements, and more within our function block.

For example, the function defined below utilizes a conditional statement to check if the input for the name variable contains hypython, then prints Hey leaner.


#Define function names

def 
names():     
    
    
#Set up variable name with input 
    name = ('Enter your name') 
    if
 name = ('heypython'):
        print('Hey learner')
    else:
        print('Hey learner')

#Now call the function

names()
    
   

Working with Parameters

So far we have looked at functions with empty parentheses that do not take arguments, but we can define parameters in function definitions within their parentheses.

A parameter is a named entity in a function definition, specifying an argument that the function can accept.

Let’s create a small program that takes in parameters x, y, and z. We’ll create a function that adds the parameters together in different configurations. The sums of these will be printed by the function. Then we’ll call the function and pass numbers the function.



def 
add_numbers(x,y):  
    a = x+y    
    b x+z
    c = y+z
    print
(a,b,c
)                                       
    
   


We passed the number 1 in for the x parameter, 2 in for the y parameter, and 3 in for the z parameter. These values correspond with each parameter in the order they are given. The program is essentially doing the following math based on the values we passed to the parameters:

a = 1 + 2
b = 1 + 3
c = 2 + 3

The function also prints a, b, and c, and based on the math above we would expect a to be equal to 3, b to be 4, and c to be 5. Let’s run the program:

python add_numbers.py

Output : 3  4  5

When we pass 1, 2, and 3 as parameters to the add_numbers() function, we receive the expected output.

Parameters are arguments that are typically defined as variables within function definitions. They can be assigned values when you run the method, passing the arguments into the 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 here

def 
printme(str):  
   
    #This prints a passed
    str into this function
    print(str)
   
    return

#Now call the 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() missing 1 required positional argument: 'str'

       

Keyword Arguments

In addition to calling parameters in order, you can use keyword arguments in a function call, in which the caller identifies the arguments by the parameter name.

When you use keyword arguments, you can use parameters out of order because the Python interpreter will use the keywords provided to match the values to the parameters.

def fancy_print(text, color):

Every time you call this function, you have to remember the correct order of the arguments. Fortunately, Python allows you to name the arguments when calling the function, as shown below:

fancy_print(text='Hi', color='yellow')

As we can see, the order of the arguments does not matter when you use keyword arguments.When defining the function, it would be a good idea to give defaults. For instance, most of the time, the caller would want left justification, a white background, etc. Using these values as defaults means the caller does not have to specify every single argument every time they call the function.

Here is a example:


def key_args(str, num, bool):
    #Function goes here
    print(num)
    print(str)
    print(bool)

key_args(str='hypy', num=10, bool=True)

    
   

default argument


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.



def printinfo(name, age = 30):
    
    #Function goes here
    #this prints a passed
    #info into this function

   
    print(name)

    print(age)

#Now call the function

printinfo(name = "hypy", age = 20)
printinfo(name = "hypython")
       


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

hypy
20
hypython
30

return Statement

A function can produce a value with the return statement, which will exit a function and optionally pass an expression back to the caller. If you use a return statement with no arguments, the function will return
None.

So far, we have used the print() statement instead of the return statement in our functions


#function definition is here
def sum(arg1, arg2):

    
    #Function goes here
    #Addition of two number

    total arg1 + arg2
    print("inside the function : ",  total)
    return 
total

#Now call the function

total = sum(10, 20)
print("outside the function the : ", 
total)       


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

inside the function : 30
outside the function : 30

Anonymous Functions

These functions are called anonymous because they are not declared in the standard manner by using the def keyword. You can use the lambda keyword to create small anonymous functions.

Lambda forms can take any number of arguments but return just one value in the 
form of an expression. They cannot contain commands or multiple expressions.

An anonymous function cannot be a direct call to print because lambda requires an expression.

Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace.

Syntax

The syntax of lambda function contains only a single statement, which is as follows-


#Syntax is here

lambda(arg1, arg2,....argN : expression)


Following is an example to show how lambda form of function works-

#Function definition is here

sum
= lambda arg1,arg2 : arg1+arg2

#Now call the function

print("value of total :", sum(10, 20))

print("value of total :", sum(110, 220))


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

Value of total : 30
Value of total : 330