In this module we will be going through the below given content:
- Python Functions
- Scope of variable
- Anonymous function
Function is a block of code which provides the re-usability of code. There are two types of functions –
Built – in function (Already created i.e. predefined)
User defined function (Created by users according to the requirements)
Defining a Function
A function contains following format –
- def keyword is used to start the Function Definition
- def is followed by function-name which is followed by parenthesis which contains the arguments passed by the user and use the colon at the end
- Statement specify the body of function.
- Return sends a result object back to the caller
z = x + y
Scope of variable
Scope of a variable means the portion of the program where you can access a particular identifier. There are two types of scope of variable –
- Local Variable
- Global Variable
The variables which can only be accessed in that function where it is declared. Outside the function body, it cannot be accessed.
z=x + y
print(z) # print 8
print(z) # shows errorOutput
NameError Traceback (most recent call last)
—-> 6 print(z) # shows errorNameError: name ‘z’ is not defined
Variable which is declared outside the function is known as global variable. It can be accessed anywhere throughout the program.
z=x + y
print(z) # print 30
print (x) # print 20output:
Functions which have no name is known as anonymous function which is created by using lambda. is created without using the def keyword.
print “Sum is”,sum(20)
Sum is 40
Now that we are familiar with the functions of python.
We can go ahead a bit deeper and discuss how to deal with the files and perform different operations on them from our Python tutorial.
Getting problem with Python learning? Take our Python certification course with a free guide to crack interview questions.