Python Function

Click to rate this post!
[Total: 2 Average: 4]

There are some cases where a  certain piece of code needs to perform an action several times. But writing the code at all times where the action is necessary increased the code complexity. So we need an alternative to these problems. Python function provide good solutions to this. So let first have a look over

What is a python function?

The function is a block of code which provides the re-usability. These functions allow the proper modularity for the application in a single action. Python offers built-in functions like Print(). Besides, it allows the users to create the function of our own. These functions are knows as the  User-defined functions.

So my readers till now we have what is a function in learn to code python, So now let us have a look over how to define a function.

Rules for defining a function:
  • The function name should start with a def keyword followed by a function name and parenthesis.
  • All the arguments and input parameters should be placed within the parenthesis
  • The functional code within the function should start with the colon :
  • To exit the function, we use the return (this is also used to send object return to the caller)
Syntax :

def func_name():




I would like to explain this with an  addition example

def sum(x,y):


return z

Sum (20, 30)

 Output : 


So in learn python for beginners, we will discuss how to call (or) how to invoke a function.

Function calling (or) function invoking :

The definition of the function would offer the name and specify the values/ parameter that should be included in a function. Once the function has given the basic structures,  it can be executed by calling from the other functions. Besides this can also be called from the python prompt.As discussed above in Function calling, we can pass value by reference (or) pass by value.

Syn :

Def function_name():




Def first():

Print(‘this is the first function’)

Arguments :

These are the values passed in a function. The arguments are of 5 types.

Default arguments:

 These arguments provide a default value if nothing is provided in the function call. These have to be defined in the function definition.

Keyword arguments :

These arguments are related to the calls. With the help of parameter name caller identify the arguments

This allows skipping arguments.

Required arguments :

These are those arguments that are passed to the function in the correct order according to their positions.

Variable- length arguments :

In some cases, we need to write functions, that accept more parameter than they defined. These arguments are otherwise called as These arguments as a variable – length arguments.

also check  How can you check the quality of the python code

scope of the variable :

The variables declare this have different scopes. let us discuss the usage in detailed.

Local variable :

The variables that can be accessed in a function, where it is declared. It cannot be accessed outside the body. Let us discuss the code with an example.


def first():

a = 'im the lcoal variable'



Output :

Im the local variable

EX :2:

def first():

a  = 'im the lcoal variable’



print (a)

Output :

im the local variable

name ‘a’ is not defined
Reason :

 Since variable ‘a’  is defined in a function ,it cannot accessed outside the function.So we have experienced an error.

So to overcome this feature, we use Global variables

 Global Variable :

This is unlike the local variable. This can be accessed globally. The variables that are declared ones can be accessed many functions.


def f():

s= 'im the local function. I overrided the global function'

print (s)

a= 'im the local function, i cannot  access the outside the function f'

print (a)

# Global scope

b= "Since, I am the global function, print S is called before the function, and first  exected"



a= 'i love python'

print (a)

Output :

Since, I am the global function, print S is called before the function,and first  exected

im the local function. I overrided the global function

im the local function, I cannot  access the outside the function f

i love python


def f():

s= 'im the local function. I overrided the global function'

print (s)

# Global scope

b = "Since, I am the global function, print S is called before the function,and first  exected"



print (b)

Output :

Since, am the global function, print S is called before the function,and first  executed

im the local function. I overrided the global function

am the global function, print S is called before the function,and first  executed

 Note :

If you have observed the code, when the control comes outside the function, the value of the global variable will be stored.

Q: How do we access the local variable value outside the function?

So far, we have discussed the local variables as well as the global variables. But as shown above, if the control is a function outside, the memory/cache stores only the global variable

So to store the local variable value outside the memory we need to make use of Global function. let us consider the working of the global function with an example.


def f():

global b

s= 'im the local function. I overrided the global function'

print (b)

# Global scope

b = "Since, I am the global function, print S is called before the function, and first  exected"



print (b)

Output :

Iam the global function, since print S is called before the function, I was exected

im the local function. I override the global function

im the local function. I overrided the global function

So now let’s move to the next topic recursion.


So till now, we have seen how to call the function and also how to pass the variables to it. But we cannot say exactly the function may call the other functions. In some cases, function calls the same functions too. This phenomenon is nothing but recursion.

In simple words factorial is a good example of recursion.


def calc_factorial(x):

"""This is a recursive function

to find the factorial of an integer"""

if x == 1:

return 1


return (x * calc_factorial(x-1))

num = 10

print("The factorial of", num, "is", calc_factorial(num))

So far, we have discussed what is a function, how to define the function and the types of functions? Now its time to discuss some functions in python.


After the class creation __init__ called . It also known as constructor

Self :

Self represents the instance of the class. In python, using the self keyword, we can access the python class attributes and methods.

In the best way to learn to learn python, these keywords play a prominent role. So now let us have a look over the syntax and example


class SomeClass:

variable_1 = “ This is a class variable”

variable_2 = 50    #this is some other variable

def __init__(self, param1, param2):

self.instance_var1 = param1

#instance_var1 is a instance variable

self.instance_var2 = param2

#instance_var2 is a instance variable


class Rectangle:

def __init__(self, length, breadth, unit_cost=0):

self.length = length

self.breadth = breadth

self.unit_cost = unit_cost

def get_perimeter(self):

return 2 * (self.length + self.breadth)

def get_area(self):

return self.length * self.breadth

def calculate_cost(self):

area = self.get_area()

return area * self.unit_cost

# breadth = 50 cm, length = 70 cm, 1 cm^2 = Rs 1500

r = Rectangle(50, 70, 1500)

print("Area of Rectangle: %s cm^2" % (r.get_area()))

print("Cost of rectangular field: Rs. %s " % (r.calculate_cost()))

Here in the above example, all the values that were the length, breadth, and unit_cost were assigned to self.length, self.breadth, and self.unit_cost  respectively. And all the operations were done using the self.variable_name (variable _name may be length,breadth and unit_cost).

Hope you got a better idea regarding _init_ and self. 

Doc strings :

It provides a convenient way of associating documentation, with python modules, classes, functions, and methods. doc_ strings can be accessed by  __doc__ attribute. 

How to define a doc string?

Usually, the doc string line should start with a capital letter.

The first line should be a short description

And we should not write the object name.


def my_function():

"""Demonstrate docstrings and does nothing really."""

return None

print ("Using __doc__:")

print (my_function.__doc__)

Out Put :

Using __doc__:

Demonstrate docstrings and does nothing really.

I Suggest you to practice the one line Doc string, multi-line doc strings and Doc string in classes. If you fin difficulty clarify your doubts at best online python course.

Date and Time :

The other function that we need to discuss is Date and time. Let us discuss briefly it.

A date in python is a data type of its own. But we can import a module, named date time to work with dates as well as date objects.


import datetime

x =


Output :

2019-02-13 13:12:25.389359

It means it displays the result in a year, month, day, hour, minute, second and microsecond.

How to get the calendar?

Python allows you to print the calendar of the month. The following code allows you to print the calendar of the month.

Ex :

from datetime import datetime

import calendar

cal = calendar.month(2019, 2)

print ('Here is the calendar:')

print (cal)

Output :

How to display the year and weekday of the week
import datetime

x =



Output :



How to display the name of the month?
import datetime

x = datetime.datetime(2018, 6, 1)


Output :


Now let us have a look over some Date and time legal formats.

Directive Description Example
%a Weekday, short version Wed
%A Weekday, full version Wednesday
%w Weekday as a number(0-6). Weekday starts from Sunday 3


%d Day of the month (1-31) 13
%b Month name(short version) Feb
%B Month name(full version) February
%m Month as a number(1-12) 2
%y Year, short version 19
%Y Year, Full version 2019
%H Hour (00-23) 15
%I Hour(00-12) 3
%M Minute(00-59) 27
%S Second(0-59) 27
%f Microsecond(000000-999999) 270893
%z UTC offset +0100
%Z Timezone CST
%j Day number of the year 44
%U Week number of the year. Sunday as the first day of the week 22
%W Week number of the year. Monday as the first day of the year 52
%c The local version of date and time Wed Feb 13 15:10:54 2019
%x The local version of date 02/03/2019
%X The Local version of time 15:14:17

 In the previous topics, we have discussed the python list, python tuples, and python dictionaries. And these perform the Slicing operation. Basically, these tuples/dictionaries contain a group of elements. But in all the cases, we do not require to display the complete list of elements. (It is enough to display only some elements). In those cases, we use a concept of slicing.


A slice object specifies how to slice the sequence. Here, you can specify where to start and where to end the sequence. The slice function returns a slice object.


Slice (start , end ,step)

Parameter Description
start An integer specifying the position to start slicing. Its default value is zero. It is optional
End An integer specifying the end of the slicing
Step An integer specifying  the step of slicing. Its default value is one


temp= ("Online", "IT", "Guru", "Training", "Education", "and", "placement", "centre")

x = slice(3, 5)


Out put :

(‘D’, ‘E’)

to our newsletter

Drop Us A Query

Trending Courses
  • Microsoft Azure Architect Technologies(AZ-300) | ITGuru
    Microsoft Azure Architect Technologies(AZ-300)
  • Azure is a great Microsoft Cloud Computing platform in providing various cloud services through online. ITGuru Certified Azure Architect certification course gives you the practical knowledge on Azure Cloud platform through real-world use cases from live experts

  • ServiceNow Admin Training | ITGuru
    ServiceNow Admin Training
  • Getting knowledge of cloud platforms like ServiceNow is essential in today’s world for the smooth running of projects in cloud platform. Turn your dream to the reality of becoming the Certified ServiceNow Administrator through ServiceNow Administration online certification Course with practical examples by live industry experts through online at ITGuru with real-world use cases.

  • Workday Financials Training | ITGuru
    Workday Financials Training
  • knowing the basics on any platform like Workday is not enough to sustain the IT industry. Hence it is essential to go beyond on Workday basics like Workday Financials training which lets you know the application of Financials management in real -world use cases from ITGuru Live Experts in a practical way.

  • Workday Training
  • An organization is considered as the best one when it offers the best benefits to the employee. Moreover, the greater the employee benefits, the greater the contribution to the organization. ITGuru let you know the practical workday Human Resource Management(HRM) features with live examples by experts

  • Python Online Course | ITGuru
    Python Online Course
  • Turn your dream into reality by ITGuru live experts with real-world use cases through practical knowledge on python online course and become the certified associate in python programming and become a master in python programming

  • Python Programming | ITGuru
    Python Programming
  • Python is the trending programming language in the IT industry. Mastering in python programming gives you more value among the people in the IT industry. Hence start today to learn python programming online by live experts with real-time uses cases at ITGuru

100% Secure Payments. All major credit & debit cards accepted.

Call Now Button