13.1 Functions in Python
Functions are block of codes that allowing us to order our code, make it more reuseable, readable, and easy to debug. A function is defined with def keyword, example
def add(a, b):
c = a + b
print('{} + {} = {}' .format(a, b, c))
def substract(a, b):
c = a - b
print('{} - {} = {}' .format(a, b, c))
Example how to call the function.
def add(a, b):
c = a + b
print('{} + {} = {}' .format(a, b, c))
def substract(a, b):
c = a - b
print('{} - {} = {}' .format(a, b, c))
# this is the way you use the function
add(4, 5)
substract(8, 5)
13.2 Parameters and Arguments
Parameters are the names used when you define a function usually called as formal parameters, while arguments are the values which are passed to any function parameters or usually called actual parameters, example
# here a and b are formal parameters
def add(a, b):
c = a + b
print('{} + {} = {}' .format(a, b, c))
# here 4 and 5 are actual parameters
add(4, 5)
13.3 Return Values
In our previous examples we have created functions without return value or we usually call it as procedures. We can also create functions with return value, example
def add(a, b):
return a + b
def substract(a, b):
return a - b
print(add(4, 5)) # 9
print(add(add(4, 5), add(8, 9))) # 26
print(substract(9, 7)) # 2
print(substract(substract(9, 1), 2)) # 6
13.4 Default Parameters
When writing functions, Python allows you to not passing values for those arguments when calling the function. If you do not pass the values, then those parameters will have the default values given when the function called, example
def add(a=5, b=9):
return a + b
def substract(a=8, b=6):
return a - b
# this will print default value
print(add()) # 14
print(substract()) # 2
# the default values will be overrided
print(add(1, 3)) # 4
print(substract(4, 2)) # 2
13.5 Lambda Functions
One of Python's features that allowing us to write functions with another style that's lambda function. In Python lambda functions is usually known as anonymous functions which means it is defined without name but still they are just like regular functions and even behave like them, example
add = lambda a, b: a + b
substract = lambda a, b: a - b
print(add(3, 4)) # 7
print(substract(4, 3)) # 1
This lambda functions is used for short period of time and usually used with built-in functions like map(), filter(), and etc, example
nums = [1, 2, 3, 4, 5, 6, 7, 8]
new_nums = list(filter(lambda x: x < 5, nums))
print(new_nums) # [1, 2, 3, 4]
new_nums = list(map(lambda x: x ** 3, nums))
print(new_nums) # [1, 8, 27, 64, 125, 216, 343, 512]
Alright now that we understand how to write functions with Python to deal with our needs, If you guys have any questions please leave comments below and don't forget to share with others if think this is worth.
0 Response to "13. Python Functions"
Post a Comment