
Domains
Agile Management
Master Agile methodologies for efficient and timely project delivery.
View All Agile Management Coursesicon-refresh-cwCertifications
Scrum Alliance
16 Hours
Best Seller
Certified ScrumMaster (CSM) CertificationScrum Alliance
16 Hours
Best Seller
Certified Scrum Product Owner (CSPO) CertificationScaled Agile
16 Hours
Trending
Leading SAFe 6.0 CertificationScrum.org
16 Hours
Professional Scrum Master (PSM) CertificationScaled Agile
16 Hours
SAFe 6.0 Scrum Master (SSM) CertificationAdvanced Certifications
Scaled Agile, Inc.
32 Hours
Recommended
Implementing SAFe 6.0 (SPC) CertificationScaled Agile, Inc.
24 Hours
SAFe 6.0 Release Train Engineer (RTE) CertificationScaled Agile, Inc.
16 Hours
Trending
SAFe® 6.0 Product Owner/Product Manager (POPM)IC Agile
24 Hours
ICP Agile Certified Coaching (ICP-ACC)Scrum.org
16 Hours
Professional Scrum Product Owner I (PSPO I) TrainingMasters
32 Hours
Trending
Agile Management Master's Program32 Hours
Agile Excellence Master's ProgramOn-Demand Courses
Agile and ScrumRoles
Scrum MasterTech Courses and Bootcamps
Full Stack Developer BootcampAccreditation Bodies
Scrum AllianceTop Resources
Scrum TutorialProject Management
Gain expert skills to lead projects to success and timely completion.
View All Project Management Coursesicon-standCertifications
PMI
36 Hours
Best Seller
Project Management Professional (PMP) CertificationAxelos
32 Hours
PRINCE2 Foundation & Practitioner CertificationAxelos
16 Hours
PRINCE2 Foundation CertificationAxelos
16 Hours
PRINCE2 Practitioner CertificationSkills
Change ManagementMasters
Job Oriented
45 Hours
Trending
Project Management Master's ProgramUniversity Programs
45 Hours
Trending
Project Management Master's ProgramOn-Demand Courses
PRINCE2 Practitioner CourseRoles
Project ManagerAccreditation Bodies
PMITop Resources
Theories of MotivationCloud Computing
Learn to harness the cloud to deliver computing resources efficiently.
View All Cloud Computing Coursesicon-cloud-snowingCertifications
AWS
32 Hours
Best Seller
AWS Certified Solutions Architect - AssociateAWS
32 Hours
AWS Cloud Practitioner CertificationAWS
24 Hours
AWS DevOps CertificationMicrosoft
16 Hours
Azure Fundamentals CertificationMicrosoft
24 Hours
Best Seller
Azure Administrator CertificationMicrosoft
45 Hours
Recommended
Azure Data Engineer CertificationMicrosoft
32 Hours
Azure Solution Architect CertificationMicrosoft
40 Hours
Azure DevOps CertificationAWS
24 Hours
Systems Operations on AWS Certification TrainingAWS
24 Hours
Developing on AWSMasters
Job Oriented
48 Hours
New
AWS Cloud Architect Masters ProgramBootcamps
Career Kickstarter
100 Hours
Trending
Cloud Engineer BootcampRoles
Cloud EngineerOn-Demand Courses
AWS Certified Developer Associate - Complete GuideAuthorized Partners of
AWSTop Resources
Scrum TutorialIT Service Management
Understand how to plan, design, and optimize IT services efficiently.
View All DevOps Coursesicon-git-commitCertifications
Axelos
16 Hours
Best Seller
ITIL 4 Foundation CertificationAxelos
16 Hours
ITIL Practitioner CertificationPeopleCert
16 Hours
ISO 14001 Foundation CertificationPeopleCert
16 Hours
ISO 20000 CertificationPeopleCert
24 Hours
ISO 27000 Foundation CertificationAxelos
24 Hours
ITIL 4 Specialist: Create, Deliver and Support TrainingAxelos
24 Hours
ITIL 4 Specialist: Drive Stakeholder Value TrainingAxelos
16 Hours
ITIL 4 Strategist Direct, Plan and Improve TrainingOn-Demand Courses
ITIL 4 Specialist: Create, Deliver and Support ExamTop Resources
ITIL Practice TestData Science
Unlock valuable insights from data with advanced analytics.
View All Data Science Coursesicon-dataBootcamps
Job Oriented
6 Months
Trending
Data Science BootcampJob Oriented
289 Hours
Data Engineer BootcampJob Oriented
6 Months
Data Analyst BootcampJob Oriented
288 Hours
New
AI Engineer BootcampSkills
Data Science with PythonRoles
Data ScientistOn-Demand Courses
Data Analysis Using ExcelTop Resources
Machine Learning TutorialDevOps
Automate and streamline the delivery of products and services.
View All DevOps Coursesicon-terminal-squareCertifications
DevOps Institute
16 Hours
Best Seller
DevOps Foundation CertificationCNCF
32 Hours
New
Certified Kubernetes AdministratorDevops Institute
16 Hours
Devops LeaderSkills
KubernetesRoles
DevOps EngineerOn-Demand Courses
CI/CD with Jenkins XGlobal Accreditations
DevOps InstituteTop Resources
Top DevOps ProjectsBI And Visualization
Understand how to transform data into actionable, measurable insights.
View All BI And Visualization Coursesicon-microscopeBI and Visualization Tools
Certification
24 Hours
Recommended
Tableau CertificationCertification
24 Hours
Data Visualization with Tableau CertificationMicrosoft
24 Hours
Best Seller
Microsoft Power BI CertificationTIBCO
36 Hours
TIBCO Spotfire TrainingCertification
30 Hours
Data Visualization with QlikView CertificationCertification
16 Hours
Sisense BI CertificationOn-Demand Courses
Data Visualization Using Tableau TrainingTop Resources
Python Data Viz LibsCyber Security
Understand how to protect data and systems from threats or disasters.
View All Cyber Security Coursesicon-refresh-cwCertifications
CompTIA
40 Hours
Best Seller
CompTIA Security+EC-Council
40 Hours
Certified Ethical Hacker (CEH v12) CertificationISACA
22 Hours
Certified Information Systems Auditor (CISA) CertificationISACA
40 Hours
Certified Information Security Manager (CISM) Certification(ISC)²
40 Hours
Certified Information Systems Security Professional (CISSP)(ISC)²
40 Hours
Certified Cloud Security Professional (CCSP) Certification16 Hours
Certified Information Privacy Professional - Europe (CIPP-E) CertificationISACA
16 Hours
COBIT5 Foundation16 Hours
Payment Card Industry Security Standards (PCI-DSS) CertificationOn-Demand Courses
CISSPTop Resources
Laptops for IT SecurityWeb Development
Learn to create user-friendly, fast, and dynamic web applications.
View All Web Development Coursesicon-codeBootcamps
Career Kickstarter
6 Months
Best Seller
Full-Stack Developer BootcampJob Oriented
3 Months
Best Seller
UI/UX Design BootcampEnterprise Recommended
6 Months
Java Full Stack Developer BootcampCareer Kickstarter
490+ Hours
Front-End Development BootcampCareer Accelerator
4 Months
Backend Development Bootcamp (Node JS)Skills
ReactOn-Demand Courses
Angular TrainingTop Resources
Top HTML ProjectsBlockchain
Understand how transactions and databases work in blockchain technology.
View All Blockchain Coursesicon-stop-squareBlockchain Certifications
40 Hours
Blockchain Professional Certification32 Hours
Blockchain Solutions Architect Certification32 Hours
Blockchain Security Engineer Certification24 Hours
Blockchain Quality Engineer Certification5+ Hours
Blockchain 101 CertificationOn-Demand Courses
NFT Essentials 101: A Beginner's GuideTop Resources
Blockchain Interview QsProgramming
Learn to code efficiently and design software that solves problems.
View All Programming Coursesicon-codeSkills
Python CertificationInterview Prep
Career Accelerator
3 Months
Software Engineer Interview PrepOn-Demand Courses
Data Structures and Algorithms with JavaScriptTop Resources
Python TutorialPython's standard distribution consists of a large number of functions. Some are always available for use as they are loaded every time when Python interpreter starts. Others may be loaded as and when required from the built-in modules bundled in the distribution itself. Each of these functions performs a predefined task and can be called upon in any program as per requirement.
However, the user (programmer) is free to define a new function if required. Such a function is known as a User Defined Function. Just as we can import a function from built-in module, a user-defined function in one script can be imported in another script. It is also possible to make such script available for system-wide use or even for other users by uploading to Python Package Index (PyPI). First we shall learn how to define and then use it in Python program.
As we learned earlier, a function is a reusable block of statements performing a single task. A new function is defined using 'def' keyword. You can give it any suitable name (the name should follow the rules of naming an identifier). The name of your function after def keyword should have parentheses. The block Python statements to perform required task is entered with increased indent. To start the block you have to type ':' symbol after the parentheses.
Many a times, some parameters need to be provided to the function to perform its task. In such cases, these parameters are mentioned inside parentheses. Otherwise parentheses may be empty.
Given below is a prototype definition of function
def function([p1],[p2],…):
"function docstring"
statement1
statement2
..
..
return [expression]
The keyword def is followed by a suitable identifier as name of function and parentheses. One or more parameters may be optionally mentioned inside parentheses. The : symbol after parentheses starts an indented block.
First statement in this block is an optional string literal which provides description about functionality. It is called docstring and is somewhat similar to comment. It is not executed, but is a part of function object attributes in the form of function.__doc__.
Subsequent statements that perform a certain task form body of the function. It may be a variable declaration, expressions, conditionals, loop or even another function declaration inside it.
Last statement in the function block has return keyword. It sends execution control back to the position in the program from where it was called. Following diagram will explain this behaviour.

The return statement is optional. Even if it is not used, flow of program goes back. However, if it is required that it should carry with it certain expression while returning, an value of expression put in front of it is returned.
Given below is definition of greetings() function.
>>> def greetings():
"First line in function is DocString"
print("Hello EveryOne")
return
When this function is called, it will print a greeting message.
>>> greetings()
Hello EveryOne
If the function contains a string literal as its first line, it is treated as docstring and serves as value of __doc__ attribute of function object.
>>> greetings.__doc__
'First line in function is DocString'
As mentioned above, process defined inside a function may depend upon one or more parameters. Hence it should be designed that way to receive one or more parameters (also called arguments) mentioned inside parentheses after its name. These parameters/arguments may be given suitable formal names.
In the greetings() function we now define a string parameter called name.
>>> def greetings(name):
"First line in function is DocString"
print("Hello {}".format(name))
return
When calling the function required parameter is now passed to it.
>>> greetings("World")
Hello World
>>> greetings("Bengaluru")
Hello Bengaluru
Arguments in definition of function are called formal arguments/parameters. Data items passed to the function become actual arguments/parameters.
Instead of defining and calling function in Python console, one can put it in a Python script and run it from command prompt or from inside an IDE like IDLE.
In following example, add() function is defined with two parameters. It calculates their total. The function is called by providing same number of parameters.
def add(x, y):
ttl=x+y
print ("addition = {}".format(ttl))
return
num1=int(input("Enter first number: "))
num2=int(input("Enter second number: "))
add(num1,num2)
Save above script as add.py
Output of above code with two different set of inputs is shown below:
Enter first number: 10
Enter second number: 20
addition = 30
Enter first number: 100
Enter second number: 200
addition = 300
One or more parameters in a function may be defined to have a default value. If while calling such function, required parameter is not passed, the default value will be processed.
In the greetings() function defined earlier, the 'name' parameter is now set to a default value 'World'. If any value is explicitly passed, the default will be overridden. If no value is passed, the default is used.
>>> def greetings(name="World"):
"First line in function is DocString"
print("Hello {}".format(name))
return
>>> greetings("Mumbai")
Hello Mumbai
>>> greetings()
Hello World
Number and type of parameter must match with the values passed to the function. If not, error may be encountered. In add.py script used earlier, add() function needs two parameters of numeric type. However, if only one parameter is passed, error is generated as shown
def add(x, y):
ttl=x+y
print ("addition = {}".format(ttl))
return
add(10,20)
add(10)
Output:
addition = 30
Traceback (most recent call last):
File "C:\python36\add.py", line 7, in <module>
add(10)
TypeError: add() missing 1 required positional argument: 'y'
First call to the function is ok as two required parameters are passed. In second call, there is one parameter less.
Even if number of values passed is same as that of arguments but if their respective types don't match, TypError message is still displayed.
For instance passing number and a string to add() function is not accepted as shown below:
def add(x, y):
ttl=x+y
print ("addition = {}".format(ttl))
return
add(10, "Hello")
Output:
Traceback (most recent call last):
File "C:\python36\add.py", line 6, in <module>
add(10, "Hello")
File "C:\python36\tmp.py", line 2, in add
ttl=x+y
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Let us define a divide() function with two numeric objects as arguments.
def divide(n, d):
div=n/d
print ("division = {}".format(div))
return
For divide() function, n and d are the positional arguments. Hence, first value passed to it will become n and second becomes d.
Python provides a useful mechanism of using argument in definition as keyword in function call. The function will process the arguments even if they are not in order of definition.
Second call to div() function is uses keyword arguments.
def divide(n, d):
div=n/d
print ("division = {}".format(div))
return
#positional arguments
divide(10, 5)
#keyword arguments
divide(d=10, n=100)
Output:
division = 2.0
division = 10.0
Any function is one component of the entire program which may have many such functions. Most of the times, we need the output of one function to be processed in other. Hence when a function returns, it should also return a value.
Most of the built-in functions return some value. The len() function returns length of sequence.
>>>string='Hello World'
>>> chars=len(string)
>>>chars
11
In order to make a function return certain value, put an expression front of return statement. Value of this expression may be assigned to some variable for subsequent processing.

def add(x, y):
ttl=x+y
return ttl
a=10
b=20
c=add(a,b)
print ("addition of {} and {} is {}".format(a,b,c))
Output:
addition of 10 and 20 is 30
A variable defined inside function is not accessible outside it. Such variable is called a local variable. Formal arguments also behave as local variable inside the function. Attempt to access a local variable outside its scope will result in NameError
def add(x, y):
ttl=x+y
add(10,20)
print ("total=",ttl)
Here, ttl is local variable for add() function and is not accessible to print statement outside it. Output of above code on Python console is like this:
Traceback (most recent call last):
File "C:\python36\add.py", line 5, in <module>
print ("total=",ttl)
NameError: name 'ttl' is not defined
If a variable is defined outside any function block its value is accessible from inside any function. It is called as a global variable. In following code snippet, ttl is defined before function. Hence it is a global variable.
ttl=50
def add(x, y):
print ("ttl is a global variable")
print ("total=",ttl)
add(10,20)
Output of above code is:
ttl is a global variable
Total : 50
However, if we initialize variable of same name inside the function, a new local variable is created. This assignment will not alter value of global variable.
ttl=50
def add(x, y):
ttl=x+y
print ("ttl is local variable")
print ("total=",ttl)
add(10,20)
print ("ttl is global variable")
print ("total=",ttl)
Output shows that globally declared ttl will continue to have earlier value.
ttl is local variable
total= 30
ttl is global variable
total= 50
To modify value of global variable from within a function, it has to be accessed by using 'global' keyword.
ttl=50
def add(x, y):
global ttl
ttl=x+y
print ("modifying global variable in function")
print ("total=",ttl)
add(10,20)
print ("ttl is global variable")
print ("total=",ttl)
Here’s the output
modifying global variable in function
total= 30
ttl is global variable
total= 30
Python's built-in function global() returns a dictionary object of all global variables keys and their respective values. In following code same name is used as global and local variable.
ttl=50
def add(x, y):
ttl=x+y
globals()['ttl']=ttl
print ("modifying global variable in function")
print ("total (local variable) =",ttl)
add(10,20)
print ("ttl is global variable")
print ("total=",ttl)
Here 'ttl' is used as key and globals()['ttl'] retrieves value of globally declared ttl variable.
modifying global variable in function
total (local variable) = 30
ttl is global variable
total= 30
As explained earlier, variable in Python is a reference to the object in memory. H, both formal and actual arguments refer to same object. Following snippet will confirm this:
def function(x):
print ("value {} id {} of argument".format(x,id(x)))
a=10
print ("value {} id {} of passed value".format(a,id(a)))
function(a)
The id() function returns a unique integer corresponding to identity of an object. In above code, id() of object before and after passing is same, which means objects are always passed by reference to a function in Python.
value 10 id 1897295152 of passed value
value 10 id 1897295152 of argument
It also means that if argument object is modified inside the function, the changes should be reflected outside the function as well. In following program a list object is passed to append() function. Changes made to the list by the function are reflected in the list object.
def append(list):
list.append(60)
print ("changed list inside function: ", list)
return
numbers=[10,20,30,40,50]
print ("list before passing: ", numbers)
append(numbers)
print ("list after returning from function: ", numbers)
pass by reference feature of Python function is confirmed by following output:
list before passing: [10, 20, 30, 40, 50]
changed list inside function: [10, 20, 30, 40, 50, 60]
list after returning from function: [10, 20, 30, 40, 50, 60]