Function in Python

Suppose we are creating an application and we need to write some fixed code regularly, instead of writing every time, we can create a function and call whenever required. in this tutorial, we will learn how to create, define, and call a function in Python.

What is a Function

  • A function is a block of code.
  • It can perform a specific task (computation).
  • The function can take information as a parameter.
  • A function can return information as a result.
  • A function makes an application more organized.

Types of Function

In Python, a function is divided into two parts.

  1. Built-in function – Function, that is predefined in Python is known as a built-in function. For example the len(), lower() and upper() in previous String in Python tutorial, are built-in function.
  2. User-define function – Like a built-in function, we can also create a function in Python using the def keyword, known as a user-defined function.

How to Create a Function in Python

In Python, we can create a function using the def keyword. Creating a function is also known as a user-defined function.

def fun():
    print("Hello")

In the above code def is a keyword to create a function and the name of the function is fun followed by a parenthesis.

Call a Function

A function does not call itself, we need to call or use a function in our program, in another function or even you can call a function in the prompt.

#creating a function
def fun():
    print("Hello")

#calling a function
fun()

or you can call it on prompt (Python Shell) also.

>>> fun()
Hello
>>> 

Function Arguments and Return Keyword

  • Arguments: Function arguments (parameter) means the information which is passed to the function as an input. In the previous string in Python chapter, the lower() function is an example of without parameter, and the replace() function is an example of a function with parameters. Arguments (parameters) are optional.
  • return: Sometimes we need the result of a function in another function or program, in that case, we will use the return keyword. Return keyword returns a result of computation for further use in the program.
#function without parameter and not returning a value.
def msg():
    print("Hello, Everyone")

#function with parameter and not returning a value.
def greet(name):
    print("Hello,",name)

#function with parameter and returning a value.
def sqr(n):
    return n*n

#calling first function
msg()

#calling Second function
name=input("Enter your Name")
greet(name)

#calling third function
r=float(input("Enter Radius Of Circle"))
area=3.14 * sqr(r)
print("Area of Circle :",area)

Different Types of Arguments.

Fixed Arguments

Fixed arguments meaning, if you have created a function with two arguments then you must pass two values as a parameter at the time of calling the function.

def hello(name,age):
    print("Hello",name,", You are",age,"years old")

hello("James",22)
#you must pass value of name and age

Default Arguments

In Python, we can assign a default value to an argument. Any number of arguments can have a default value but if we assign a default argument then all the arguments to its right must have a default value. When we call a function without an argument, the default is used as a parameter.

def hello(name,msg="Good Morning"):
    print("Hello",name,msg)

hello("James")  #default msg will used
hello("James","Good Evening")   #we can passs both argument

Keyword Arguments

In Python, generally, we follow the order of arguments. But when a function called using keyword (name of argument) arguments, an order can be changed.

def hello(name,age):
    print("Hello",name,"You are",age,"years old")

hello("James",22)   #follow order
hello(age=19,name="Andy")   #keyword arguments

Arbitrary Arguments

When we do not know the number of arguments in advance, then we can use arbitrary arguments. When we use an asterisk (*) before the argument’s name, it is known as arbitrary arguments and you can pass any number of parameters.

#creating a function with arbitrary argument
def fun(*num):
    s=0
    for i in num:
        s=s+i
    print(s)

#now you can pass any numbers of argument
fun(11,22,33)
fun(11,22,33,44)
fun(11,22,33,44,55)

List as an Argument

In Python, we can pass any data type (list, tuple, string, etc) as an argument. In the below example we are using a list as an argument.

#function to find largest value in a list
def fun(num):
    large=num[0]    #assign first value of list as largest
    for i in num:
        if i>large:     #compare and assign largest
            large=i

    return large    #return largest
        
#create a list
lst=[11, 33, 22, 66, 44]
print("Largest :",fun(lst))

Recursive Function

When a function call itself is known as a recursive function and call itself continuously.

#recursive function to calculate factorial
def fact(n):
    f=1
    if n==1:
        return 1
    else:
        f=n*fact(n-1)   #call function, recursively with value of n-1.
        return f

print(fact(3))
print(fact(5))