Example HTML page

Functions

Functions

A function is a block of organized, reusable code that is used to perform a single, related action.

We can also define function as a block of code that runs only when it is called. One can pass parameters into a function and that function will return data as an output.

Syntax

def functionname( parameters ):
     "function_docstring"        #optional
      function_suite
      return [expression]

Creating a function

We can create a function by using def keyword. It is shown in below example.

def func( ):
     print("A Function")

If you execute the above lines of code it prints nothing because we are just creating simply a function.

Calling a function

After creating a function we need to call that function. To call a function, we use the function name which is followed by parenthesis.

Ex

def func( ):
     print("A Function")
func( )

If you execute the above you will get the following output.

A Function

Passing parameters to a function

Parameters are passed after the function name, inside the parenthesis (( )). We can pass parameters into a function as per our need by separating them with comma. The following is simple example to pass parameter to a function.

def Fparam(fname):
    print(fname)
Fparam("Sudhakar")

Here the execution starts from function definition. The initial line will execute first and creates an object internally and then the execution transfers directly to the statements which are outside the function definition. Then the function is called and the value inside this function is allocated to the parameters in function definition. Then the internal statements of function definition get executed.

For the above example when Fparam function is called then the value “Sudhakar” is passed to the parameter of function def i.e fname  and later the statements inside the function definition executes and prints the following output.

Sudhakar

Function with two or more parameters

The below example depicts the function with two or more parameters.

def Fparam(fname,age,dept):
    print(fname,age,dept)
Fparam("Sudhakar",27,"CSE")

Output

Sudhakar 27 CSE

Ex 1: Below is another example for the function with one parameter passing multiple values to it.

def myfun(me):
    print(" Hi " + me)
myfun("Sudhakar")
myfun("Dhoni")
myfun("Pinky")

Output

 Hi Sudhakar

Hi Dhoni

Hi Pinky

Ex 2 An example for the function with two parameters passing multiple values to it.

def myfun(me,str):
    print(" Hi " + me, "How are you")
myfun("Sudhakar", str)
myfun("Dhoni", str)
myfun("Pinky", str)

Output

 Hi Sudhakar How are you

Hi Dhoni How are you

Hi Pinky How are you

The return statement

In order to return a value from the function we use return statement.

Ex

def function(x):
    return 3+x
print(function(4))
print(function(7))
print(function(2.3))
print(function(7/5))

Output

7

10

5.3

4.4

As we discussed earlier the function definition is executed first then the statements outside the function definition are executed. In the above example after execution of function definition then it directly moves control to print(function(4)) statement. Here the value 4 is assigned to x and then the return statement executes and produces 7 as its output. Similarly all the remaining statements are getting executed.

Function arguments

Function can be called through the following kinds of arguments.

  1. Required arguments
  2. Keyword arguments
  3. Default arguments
  4. Variable-length arguments

1.Required arguments

 Required arguments are the arguments which are required during function call. The number of arguments should match with the arguments available in the function definition. The example program on required arguments to a function is as follows:

def req_args(name,age,gender):
    print(name)
    print(age)
    print(gender)
req_args("Sudhakar",27,"Male")

Output

Sudhakar

27

Male

Here we are passing three arguments in function definition. So at the time of function call there required three arguments to pass.

def req_args(name,age,gender):
    print(name)
    print(age)
    print(gender)
req_args(27,"Male")

If you pass only two arguments for the same above program, then it produces the following error.

Traceback (most recent call last):

File “C:/python/funcvms.py”, line 31, in <module>

req_args(27,”Male”)

TypeError: req_args() missing 1 required positional argument: ‘gender’

2.Keyword arguments

During the time of function call these keyword arguments are used. The values must match with the parameters in the function definition no matter what the order is. The example program on keyword arguments is shown in below:

def kw_args(x,y,z):
    print(x)
    print(y)
    print(z)
kw_args(z=6,x=7,y=2)

The output for the above code is as follows:

7

2

6

If you observe code the values which we have given are not in sequence but the output is displayed with order.

3.Default arguments

This is one of the kinds of function arguments. When the value is not provided in function call, at that time it assumes default value to print. The following is a simple example on default arguments.

def my_own(wishlist = "Reading"):
  print("I like " +  wishlist)
my_own("Coding")
my_own("Swimming")
my_own( )
my_own("Browsing")

Output

I like Coding

I like Swimming

I like Reading

I like Browsing

There is no value provided in third statement in function call, hence it considers default value to print here.

4.Variable-length arguments

These are not specified in function definition unlike the required and default arguments.

Syntax for a function with non-keyword variable arguments is given below:

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 non-keyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call. Following is a simple example.

def add(*n):
    sum = 0
    for a in n:
        sum = sum + a
    print("Sum:",sum)
add(3,5)
add(9,8,7,6)

In the above code we have used *n as a parameter. This allows us to pass variable-length argument list to add( ) function. It displays the following output.

Output

Sum: 8

Sum: 30

Example programs:

1.An example program on default argument.

def defArgFunc( empname, emprole = "Manager" ):   
   print ("Emp Name: ", empname)
   print ("Emp Role ", emprole)
   return;
print("Using default value")
defArgFunc(empname="Nick")
print("Overwriting default value")
defArgFunc(empname="Tom",emprole = "CEO")

Output

Using default value

Emp Name:  Nick

Emp Role  Manager

Overwriting default value

Emp Name:  Tom

Emp Role  CEO

2.A sample program on variable-length arguments.

def var_len(*vartuple,a):
     print("output is:")
     print("Argument is",a)
     for x in vartuple:
          print(x)
     return
var_len(2,3,4,5,a=100)

Output

output is:

Argument is 100

2

3

4

5

3. A sample Python program to create and print a list where the values are square of numbers of particular range using function.

def squares():
	x = list()
	for i in range(1,55,3):
		x.append(i**2)
	print(x)		
squares()

Output

[1, 16, 49, 100, 169, 256, 361, 484, 625, 784, 961, 1156, 1369, 1600, 1849, 2116, 2401, 2704]

4.A  python program of a simple calculator using function.

def divide(x,y):
    return x/y

print("enter choice of operation:")
print("1.Addition")
print("2.Substraction")
print("3.Multiplication")
print("4.Division")

choice=int(input("enter the choice (1/2/3/4):"))
num1=int(input("enter first number:"))
num2=int(input("enter second number:"))

if choice==1:
         print(num1,"+",num2,"=",add(num1,num2))

elif choice==2:
         print(num1,"-",num2,"=",sub(num1+num2))

elif choice==3:
         print(num1,"*",num2,"=",mul(num1,num2))

elif choice==4:
         print(num1,"//",num2,"=",div(num1,num2))

else:
         print("enter the valid choice")

Output

enter choice of operation:

1.Addition

2.Substraction

3.Multiplication

4.Division

enter the choice (1/2/3/4): 3

enter first number: 12

enter second number: 8

12 * 8 = 96

5.A Python Program to find Sum of Digits of a Number using Recursion.

def sum(digit):
    Sum = 0
    while(digit > 0):
        Reminder = digit % 10
        Sum = Sum + Reminder
        digit = digit //10
    return Sum
digit = int(input("Give any Number: "))
Sum = sum(digit)
print("Sum of the" , digit ,"is", Sum)


Output

Give any Number: 5261613210

Sum of the 5261613210 is 27

 

Example HTML page

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest