Python Functions

python tutorial
Python User defined Functions

1) What is Function?

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

2) Types of Functions in Python

Basically, we can divide functions into two types,

Built-in functions – Functions that are built into Python.
User-defined functions – Functions defined by the users themselves.

3) Advantages of User defined functions

  • Code Reusability
  • Easy Debugging and Maintenance
  • Increases program readability.

4) Writing and Calling Functions in Python

i) Function definition
ii) Function calling

Syntax of Function in Python

def function_name(arguments):
“””doc string”””

i) Keyword def marks the start of function header.

ii) A function name to uniquely identify it. Function naming follows the same rules of writing identifiers in Python.

iii) Arguments (Parameters) through which we pass values to a function and they are optional.

iv) A colon (:) to mark the end of function header.

v) Optional documentation string to describe what the function does.

vi) One or more valid python statements that make up the function body. Statements must have same indentation level.

v) An optional return statement to return a value from the function.

Example of a function

def greet(name):

"""This function greets to

the person passed in as


print("Hello, " + name + " Good morning!")

How to call a function in python?

greet(value for arg/parameter)

Hello, Paul. Good morning!

5) User defined function types in Python

i) Function without return any value
ii) Function return one or more value

Using “return” statement we can return values.

Function with return a value

def add(a, b):
return result

x= add(123, 234)

Function with return multiple values
def add_sub(a, b):
return (result1, result2)

x,y = add_sub (100, 50)

print (x)
print (y)

G C Reddy

G C Reddy, Working as a Software Testing Trainer in Hyderabad, India.

You may also like...