Python Devlopment






Functions



Python Functions

A function is a block of code which only runs when it is called.You can pass data, known as parameters, into a function. A function can return data as a result.

Creating a Function

In Python a function is defined using the def keyword:

my_function():
    print("Government College of Engineering, Jalgaon")

Calling a Function

To call a function, use the function name followed by parenthesis:

def my_function( ):    # Function Definition
    print("Government College of Engineering, Jalgaon")

my_function( )    # Calling Statement

Output:    
    Government College of Engineering, Jalgaon

Parameters

Information can be passed to functions as parameter. Parameters are specified after the function name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma.

def my_function(name):
    print(fname + " Gadade")

my_function("Harish")
my_function("Vihaan")
my_function("Priyanka")

Output:    
Harish Gadade    
Vihaan Gadade    
Priyanka Gadade

Return Values

To let a function return a value, use the return statement:

def my_function(x):
    return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))

Output:    
15    
25    
45

Exercise:

1. Write a python program to find even or odd number using functions.

#Function Definition 
def oddeven(num): 
    if num%2==0: 
        print"Even Number" 
    else: 
        print"Odd Number"

#Calling Statement 
oddeven(num)

2. Write a python program to swap two integer numbers using functions.

def swap(num1,num2):
    temp=num1
    num1=num2
    num2=temp
    print"After Swaping",num1,num1

#Calling statement
swap(num1,num2)