Functions in Python

Previous
Next

What is Function?

  • Block of programming statements is called a function which designed to perform a certain task.
  • Reusing the same code is required many times within a same program can be defined as functions.
  • We write the things we have to do repeatedly in a function then call it where ever required.
  • We will see the built in functions like len() in coming concepts.
  • To define a function, Python provides the def keyword.
  • Python gives you many built-in functions like print(), etc.

Syntax: “def” is a keyword which is used to define functions in Python.

def  identity(arguments) :
	……
	Logic
	……

Example snippet:

def  add(a, b):
	c=a+b
	return c

Calling or Invoking the Function: Every function consists

  1. Function definition:
    • Function definition is a block.
    • Definition contains logic to perform the task.
    • Function definition will not execute automatically in the program.
  2. Function call:
    • It is a single statement.
    • It used to access the function definition.

Definition syntax :

def  add(a, b):
	c=a+b
	return c

Call syntax :

res = add(10,20)
  • General example to understand the concept of function calling.
  • Television program contains lot of functionality but executes only when we control the Television from another program called Controller.
  • A simple function is defined here with one line of logic.
  • Return statement is optional in this code.
  • Return statement represents the end of function to programmers.
def fun():
    print("First function")
    return

fun() #calling
Previous
Next

Add Comment

Courses Enquiry Form