A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
A function can return data as a result.
Calling a Function
def printmsg():##def keyword use for defining function in python
print("my name is khan")
printmsg()
#output ::- my name is khan
############function with arguments################
Parameters
print("my name is "+ n1)
name("rohan")
#output::- my name is rohan
#################################################################################
Default Parameter Value
def live(country = "India"):print("I am from" + country)
live("Sweden")
live("Dubai")
live()
live("Brazil")
live("Sweden")
live("Dubai")
live()
live("Brazil")
########### Output ##############
I am from Sweden
I am from Dubai
I am from India
I am from Brazil
I am from Dubai
I am from India
I am from Brazil
################################################################################
Return Values
#To let a function return a value, use the
return
statement:
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
########### Output ##############
15
25
45
################################################################################
Lambda Functions
In python, the keyword lambda is used to create what is known as anonymous functions. These are essentially functions with no pre-defined name. They are good for constructing adaptable functions, and thus good for event handling.
def myfunc(n):
return lambda i: i*n
doubler = myfunc(2)
tripler = myfunc(3)
val = 11
print("Doubled: " + str(doubler(val)) + ". Tripled: " + str(tripler(val)))
########### Output ##############
Doubled: 22. Tripled: 33
Comments
Post a Comment