Skip to content

Instantly share code, notes, and snippets.

@sahilbadyal
Created June 5, 2019 18:23
Show Gist options
  • Save sahilbadyal/4fcedd282437dad587a2230690cded89 to your computer and use it in GitHub Desktop.
Save sahilbadyal/4fcedd282437dad587a2230690cded89 to your computer and use it in GitHub Desktop.
In Python, function is a group of related statements that perform a specific task.
Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable.
Furthermore, it avoids repetition and makes code reusable.
Syntax of Function
def function_name(parameters):
"""docstring"""
statement(s)
Above shown is a function definition which consists of following components.
Keyword def marks the start of function header.
A function name to uniquely identify it. Function naming follows the same rules of writing identifiers in Python.
Parameters (arguments) through which we pass values to a function. They are optional.
A colon (:) to mark the end of function header.
Optional documentation string (docstring) to describe what the function does.
One or more valid python statements that make up the function body. Statements must have same indentation level (usually 4 spaces).
An optional return statement to return a value from the function.
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
def add(a,b):
return a+b
result=add(3,6)
Lambda
lambda operator or lambda function is used for creating small, one-time and anonymous function objects in Python.
add=lambda a,b : a+b
result=add(2,3)
if we check type of add, it is a function.
Mostly lambda functions are passed as parameters to a function which expects a function objects as parameter like map, reduce, filter functions
map
Basic syntax
map(function_object, iterable1, iterable2,...)
map functions expects a function object and any number of iterables like list, dictionary, etc. It executes the function_object for each element in the sequence and returns a list of the elements modified by the function object.
def mul1(a):
for i in a:
i= i*2
return a
mul1([1,2,3,4])
def multiply2(x):
return x * 2
map(multiply2, [1, 2, 3, 4]) # Output [2, 4, 6, 8]
map(lambda x : x*2, [1, 2, 3, 4])
multiple iterable:
ist_a = [1, 2, 3]
list_b = [10, 20, 30]
map(lambda x, y: x + y, list_a, list_b)
filter
Basic syntax
filter(function_object, iterable)
filter function expects two arguments, function_object and an iterable. function_object returns a boolean value. function_object is called for each element of the iterable and filter returns only those element for which the function_object returns true.
Like map function, filter function also returns a list of element. Unlike map function filter function can only have one iterable as input.
Example:
Even number using filter function
a = [1, 2, 3, 4, 5, 6]
filter(lambda x : x % 2 == 0, a)
ict_a = [{'name': 'python', 'points': 10}, {'name': 'java', 'points': 8}]
filter(lambda x : x['name'] == 'python', dict_a) # Output: [{'name': 'python', 'points': 10}]
view raw
Scope and Lifetime of variables
Scope of a variable is the portion of a program where the variable is recognized. Parameters and 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. Hence, a function does not remember the value of a variable from its previous calls.
def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:",x)
def my_func():
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:",x)
def my_func():
global x
x=10
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:",x)
def my_func():
x = 10
print("Value inside function:",x)
my_func()
print("Value outside function:",x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment