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.
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.
>> <class 'int'>
Functions that convert value from one type to another are called as type conversation functions.
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
- ‘def’ keyword marks start of function
- A function name to uniquely identify it.
- Argument through which we pass the value of a function.
- A colon to mark end of function header.
- Optional documentation string(docstring) to describe what function does.
- One or more valid statement that makes function body.
- Optional return statement to return value from the function.
- Function name can have letters, numbers and some special characters but first character can’t be a number.
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.
def fun(): x=10 print("value inside function:", x) fun()
>> value inside function 10