In Python, function is a block of code to perform a specific task. When a function is called
then the function definition is executing. We can pass data called as parameters into a
function. A function returns value which consider as result. It makes code reusable.
Function breaks a program into smaller and modular chunks. When program grows larger and larger, functions make it more organized and manageable.
In python, a function is defined by using def keyword.
print("Python means SILAN Technology")
We can pass parameter into a function. Parameters are specified after the function name, inside the parentheses. We can add parameters based on the problem requirements and separate them with a comma.
A function can return a value by using return statement. Let’s see an example:
A variable scope is the portion of a program where the variable is recognized. Variables defined inside a function is not visible from outside. Hence, they have a local scope.
Lifetime of a variable is the period throughout which the variable exits in the memory. The lifetime of variables inside a function is as long as the function executes.
They are destroyed once we return from the function.
Here is an example that I have presented the scope of a variable inside a function.
x = 100
print("Value inside function:",x)
x = 200
print("Value outside function:",x)
Value inside function: 100
Value outside function: 200
Here, we can see that the value of x is 200 initially. Even though the function show()changed the value of x to 100, it did not effect the value outside the function.
Here the variable x inside the function is different (local to the function) from the one outside. Although they have same names, they are two different variables with different scope.
On the other hand, variables outside of the function are visible from inside. They have a global scope.
We can read these values from inside the function but cannot change (write) them. If we want to modify the value of variables outside the function, they must be declared as global variables using the keyword global.
Basically, there are two types of functions like:
1. Built-in functions - Functions that are in-built to Python.
2. User-defined functions - Functions defined by the users.