Python function

What is Python function?

Python function is a group of statements that perform a specific task. It helps the program to break into smaller and smaller parts and make it more organized and manageable.

Function call

Once we define a function we can call it from another function, program or even from python prompt. To call a function we type the name of the function with parenthesis and other optional parameters.

Type Conversion Functions

Name of the function is type. The expression in parenthesis is an argument. The function takes an argument and returns a result. The returns is called a return value.

Example:

type(52)

Output:

>> <class 'int'>

Functions that convert value from one type to another are called as type conversation functions.

Example:

int(32.52)
float(31)

Output:

>>32
>>31.0

User defined functions

Function definition specifies the name of a new function and sequence of statements that execute when the function is called.

Function consists of

  1. ‘def’ keyword marks start of function
  2. A function name to uniquely identify it.
  3. Argument through which we pass the value of a function.
  4. A colon to mark end of function header.
  5. Optional documentation string(docstring) to describe what function does.
  6. One or more valid statement that makes function body.
  7. Optional return statement to return value from the function.
  8. Function name can have letters, numbers and some special characters but first character can’t be a number.

Example:

def greet(name):
   "This function greets a person passed as a parameter"
   print("hello ", name,", Good Morning)

greet(sandeep)       #Function call

Scope and lifetime of variable

There are two type of variables in python

  • Local variable
  • Global variable

In this tutorial we will discuss about python Local variables. The variable which is used only inside the function having a local scope is known as local variable. We cannot access local variables outside the function.

Example:

def fun():
   x=10
   print("value inside function:", x)
fun() 

Output:

>> value inside function 10

Was this article helpful?
YesNo

Leave a Comment