Functions In Python

A function is block of reusable statements, which performs an action every time when we call the method. With functions we can reuse the code, which is already existing.

Different Types of Functions in Python?

In Python there are two types of functions namely.

1.In-built Functions
2.User Defined Functions

  1. Python In-built Functions : In-built functions are those, were in Python has already designed the functions. We need not do it again, we need to just call those methods for our scripting needs.

Example of In-built Functions in Python :

  1. Python User Defined functions: User Defined functions are those were people will design the functions based on their need.

Python Example on User Defined Functions :

Adding of two numbers

OUTPUT:

Python_UserDefined_Functions_Example

How to Define a user Defined Method?
There are few basic guidelines on how to define Method names in Python.

1.User Defined method name should start with the keyword “def”, continued by function name and parenthesis(())
2.If we want to pass parameters to the function then, we need to pass the parameters within parenthesis.
3.The reusable code of the function should be placed after the colon(:)
4.If the function contains return statement, then a return statement should be displayed at the end of the line.

Global and Local Variables in Python:

Local variables : The scope of the local variable lies within the function. So, when we declare the variable the scope starts from within the method and ends before leaving out of the method.

Example on Local Variable :

OUTPUT:

Python_Local_Variable_Example

so, the output of above program will be 10 will be printed and the scope of the variable “a” is within the function.

If we try to access below way

Print(a)

Then compilation error will throw up, because there is no “a” value available after the method is ended

Global Variables : A Global variable can be used within the class level. When we declare the variable the scope starts from the class name and ends before leaving out the class.


OUTPUT:

Python_Global_Variable_Example

If we try to access the variable a, we will not get any error because a is declared as global variable.

Leave a Comment

Your email address will not be published.