Python Functions


Function ?

A function is a group of statements that together perform a task.

Functions are used to provide modularity to a program. Creating an application using function makes it easier to understand, edit, check errors etc.


Types of Functions :

1. Library Function: The Python standard library provides numerous built-in functions that your program can call.
Example: print()

2. User Define Function: If a set of statements are needed to execute more than one times then user can define their own function and call when needed.
Example: myfun()

Defining a Function :

Syntax :


def function_name(parameters/arguments):  #function header 
    """docstring"""
    statement(s)
    return [expression]
                
  1. Function definition starts with the keyword def.

  2. function_name must be unique and must follow the valid identifier rules.

  3. Parameters (arguments) are optional, through which we pass values to the function.

  4. Colon : to end of the function header.

  5. Document string (docstring) is optional and use to describe what function does.

  6. Python statements are use to make function body, and statements must be intended.

  7. Function can have optional return statement to return the value from function.

Example :

Function defined below take a string as parameter and print it as output.
# script.py
def myFun(name):
    """Funtion is used to
        print the name"""
    print("Hello ",name)
  

Calling a Function :

After defining a function, to execute it we need to call it.

# script.py
def myFun(name):
    """Funtion is used to
        print the name"""
    print("Hello ",name)

# Function calling
myFun("Amit")
myFun("ProwessApps")
  

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

Hello  Amit
Hello  ProwessApps                    
                

Docstring :

Inside the function, after function header very first string is called docstring or document string. It is used to explain what function does.

Although it is optional, but it is good practice to define docstring. It makes us to remember why we have defined this function.

We can get it by the __doc__ attribute of function.

# script.py
def myFun(name):
    """Funtion is used to
        print the name"""
    print("Hello ",name)

# Function calling
myFun("Daneyal")

# getting docstring
myFun(myFun.__doc__)
  

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

Hello  Daneyal
Funtion is used to
        print the name                    
                

The return statement :

The return statement is used to exit from function and return back to to place from where it was called.

The return statement can have expression which gets evaluated and value is returned.

If there is no expression to evaluate and no return statement is present then function will return the None object.

Example :

Let's create two function, one without return statement and another with return statement
# script.py
def firstFunc():
    print("Function without return")

def evenOdd(num):
    """This function returns 'even' or
'odd' after checking the number"""
    if num % 2 ==0:
        return 'even'
    else:
        return 'odd'

# Function calling
print(firstFunc())
print(evenOdd(10))
                

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

Function without return
None
even
                

Variable Scope :

Scope of a variable in a program is defined as where the variable is recognized and accessible.

There are two scopes are in program for variable :

1. Local variable scope
Local variables are local to the function blocks, we cannot access the local variable outside the function.

Example

Here is an example to illustrate the local scope of variable
# script.py
def myFunc():
    x = 10
    print("Inside function value of x =",x)


x = 20
myFunc()
print("Outside function value of x=",x)
                

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

Inside function value of x = 10
Outside function value of x= 20
                

2. Global variable scope
Global variable have wider scope than local and can be access any where in the program.
# script.py
def myFunc():
    print("Value of x =",x)


x = 20
myFunc()
                

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

Value of x = 20
                

In ambiguous situation, if the local and global variable have the same name, function always read the local data.


Pass arguments to functions :

  1. Arguments are passed by reference in Python.

  2. Any changes made to parameter passed by reference in the called function will reflect in the calling function based on whether data type of argument passed is mutable or immutable.

  3. If the data type is mutable then change will be reflect otherwise not.


In Python
  • Mutable data types are Lists, Sets, Dictionary etc

  • Immutable data types are Numbers, String, Tuple etc.


Pass immutable type argument to function :

# function definition
def myfun(roll_num):
    roll_num += 1
    print("Students roll number in function",roll_num)
    return

# function invocation with immutable data type

roll_num = 1001
print("Before function calling roll number ",roll_num)
myfun(roll_num)
print("After function calling roll number ",roll_num)
                
OUTPUT
Before function calling roll number  1001
Students roll number in function 1002
After function calling roll number  1001 
                

As you can see, in the above output roll_num remains unchanged even after function calling.


Pass mutable type argument to function :

# function definition
def myfun(stu_roll_list):
    # add a new roll_num to list
    stu_roll_list.append(1004)
    print("Students roll number in function",stu_roll_list)
    return

# function invocation with immutable data type

stu_roll_list = [1001, 1002, 1003]
print("Before function calling roll number ",stu_roll_list)
myfun(stu_roll_list)
print("After function calling roll number ",stu_roll_list)
                
OUTPUT
Before function calling roll number  [1001, 1002, 1003]
Students roll number in function [1001, 1002, 1003, 1004]
After function calling roll number  [1001, 1002, 1003, 1004] 
                

As you can see, in the above output stu_roll_list gets changed after function calling.

Next chapter is Python Functions Arguments






 





Training For College Campus

We offers college campus training for all streams like CS, IT, ECE, Mechanical, Civil etc. on different technologies like
C, C++, Data Structure, Core Java, Advance Java, Struts Framework, Hibernate, Python, Android, Big-Data, Ebedded & Robotics etc.

Please mail your requirement at info@prowessapps.in


Projects For Students

Students can contact us for their projects on different technologies Core Java, Advance Java, Android etc.

Students can mail requirement at info@prowessapps.in


CONTACT DETAILS

info@prowessapps.in
(8AM to 10PM):

+91-8527238801 , +91-9451396824

© 2017, prowessapps.in, All rights reserved