Python Function

A function is a group of statements performing a specific task.

When a program gets bigger in size and its complexity grows, it gets difficult for a programmer to keep track of which piece of code is doing what!

A function can be reused by the programmer in a given program any number of times.

Using a ‘def‘ statement for defining a function is the corner store of a majority of programs in Python. To group a set of statements, programmers use functions, and they can be run more than once in a program. They act like a pack of instructions that is invoked by a name.

Example and Syntax of a function

The syntax of a function looks as follows:

def func1():

This function can be called any number of times, anywhere in the program.

Function call

Whenever we want to call a function, we put the name of the function followed by parenthesis as follows:

func1()          #This is called function call

Function definition

The part containing the exact set of instructions that are executed during the function call.

Quick Quiz: Write a program to greet a user with “Good day” using functions.

Types of functions in Python

There are two types of functions in Python:

  1. Built-in functions #Already present in Python
  2. User-defined functions #Defined by the user

Examples of built-in function includes len(), print(), range(), etc.

The func1() function we defined is an example of a user-defined function.

Functions with arguments

A function can accept some values it can work with. We can put these values in the parenthesis. A function can also return values as shown below:

def greet(name):
	gr = “Hello” + name
	return gr

a = greet(“Sandeep”) #“Sandeep” is passed to greet in name

# a will now contain “Hello Sandeep”

Default Parameter Value

We can have a value as the default argument in a function.

If we specify name = “stranger” in the line containing def, this value is used when no argument is passed.

For Example:

def greet(name=’stranger’):
	#function body

greet()                       #Name will be ‘stranger’ in function body(default)

greet(“Sandeep”)        #Name will be “Sandeep” in function body(passed)

Advantages Of Python Functions

  • Maximizing code reusability
  • Minimizing redundancy
  • Procedural decomposition
  • Make programs simpler to read and understand
Was this article helpful?

Leave a Comment

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