Module 06. Making Your Code Organized
Lecture Date 1: September 27, 2021 - Monday Slides-1
Lecture Date 2: September 29, 2021 - Wednesday Slides-2
DataCamp Chapter: Introduction to Python
-> Functions and Packages
In the last lecture, we learned lists
, an objects that can hold multiple values in it. We also, learned about iterating through lists using loops. In this lecture, we will first cover functions
which allow us to create code snippets that can be called with a name and parameter(s). Functions help us organize our code better and re-usable. Remember abs()
or print()
? These are built-in Python functions. In this class, we will learn how to create our own functions. Also, you will see slides above regarding the concept of class
. Although we won’t cover it in this lecture, you will see that it’s part of your DataCamp Assessment.
Table of contents:
1. Functions
1.1. Function definition
square_root(4)
def square_root(num):
s = num ** 0.5
print(s)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-1-9aed0e0008a1> in <module>
----> 1 square_root(4)
2 def square_root(num):
3 s = num ** 0.5
4 print(s)
NameError: name 'square_root' is not defined
def square_root(num):
s = num ** 0.5
print(s)
square_root(4)
2.0
1.1.1. Return
return single object
def square_root_r(num):
s = num ** 0.5
return s
return multiple objects
def square_root_r2(num):
s = num ** 0.5
return -s,s
a = square_root_r2(4)
a
(-2.0, 2.0)
square_root(16)
4.0
root = square_root_r(16)
print(root)
4.0
root2 = square_root_r2(16)
print(root2)
(-4.0, 4.0)
1.1.2. Arguments (parameters)
all required arguments
def sum_4(a,b,c,d):
s = a + b + c + d
return s
sum_4(1,2,3,4)
10
passing arguments by name
sum_4(d=4, c=3, b=2, a=1)
10
optional arguments
def convert_distance(distance, conversion="mile to km"):
if conversion == "mile to km":
return distance * 1.60934
elif conversion == "km to mile":
return distance * 0.621371
else:
print("Unsupported conversion is requested. Supported types are:")
print("mile to km")
print("km to mile")
convert_distance(100)
160.934
convert_distance(100, conversion="km to mile")
62.137100000000004
convert_distance(100, conversion="mile to meter")
Unsupported conversion is requested. Supported types are:
mile to km
km to mile
1.2. Variable scope
s = "This is a global variable"
def sum_4(a,b,c,d):
g = "This is a local variable"
# if we want to access the gloval s variable,
# we meed to use global keyword
def sum_2(e,f):
g = e + f
# if we want to access enclosing g variable,
# we need to use nonlocal keyword
return g
s = sum_2(a,b) + sum_2(c,d)
return s
sum_4(1,2,3,4)
10
1.3. Recursive functions
def factorial(n):
if n == 1:
return 1
return n * factorial(n-1)
factorial(5)
120
1.4. Examples
Example 1
def sum_all(elements):
total = 0
for elem in elements:
total = total + elem
return total
values = [4,10,11,56]
sum_all(values)
81
Example 2
def sum_all2(elements):
if isinstance(elements, (list,tuple)) == False:
print("You can only use list or tuple as argument")
return
total = 0
for elem in elements:
total = total + elem
return total
values = [4,10,11,56]
sum_all2(values)
81
values = "Hello"
sum_all2(values)
You can only use list or tuple as argument
values = {}
values["six"]=6
values["one"]=1
sum_all2(values)
You can only use list or tuple as argument
values = [4,10,11,"56"]
sum_all2(values)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-21-d40293a64176> in <module>
1 values = [4,10,11,"56"]
----> 2 sum_all2(values)
<ipython-input-20-83599399706d> in sum_all2(elements)
6 total = 0
7 for elem in elements:
----> 8 total = total + elem
9 return total
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Example 3
def sum_all3(elements):
if isinstance(elements, (list,tuple)) == False:
print("You can only use list or tuple as argument")
return
total = 0
for elem in elements:
if isinstance(elem, (int,float)) == True:
total = total + elem
return total
values = (4,10,11,56)
sum_all3(values)
81
values = (4,10,11,"Hello")
sum_all3(values)
25
values = []
sum_all3(values)
0
Example 4
def sq_product(elements):
if isinstance(elements, (list,tuple)) == False:
print("You can only use list or tuple as argument")
return
total = 1
for elem in elements:
if isinstance(elem, (int,float)) == True:
total = total * elem ** 2
return total
values = (4,10,11,56)
sq_product(values)
607129600
Fibonacci Example - Iterative Version
def fibo(n):
sequence = [0,1]
for i in range(n-2):
sequence.append(sequence[-1]+sequence[-2])
return sequence
fibo(16)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
Fibonacci Example - Recursive Version
def fib_recursive(n):
def fibo2(n):
if n > 1:
return fibo2(n-1) + fibo2(n-2)
else:
return n
result = [fibo2(i) for i in range(n)]
return result
fib_recursive(16)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
2. Classes
2.1. Object Oriented Programming
class FallingObject():
def set_start_position(self, y):
self.start_position = y
triangle_object = FallingObject()
triangle_object.set_start_position(20)
print(triangle_object.start_position)
20
triangle_object = FallingObject()
triangle_object.set_start_position(20)
pentagon_object = FallingObject()
pentagon_object.set_start_position(30)
hexagon_object = FallingObject()
hexagon_object.set_start_position(40)
falling_objects = [triangle_object, pentagon_object, hexagon_object]
for o in falling_objects:
print(o.start_position)
20
30
40
class FallingObject():
start_position = 0
def set_start_position(self, y):
self.start_position = y
local_variable = "hello"
class FallingObject():
start_position = 0
def __init__(self, y):
self.start_position = y
triangle_object = FallingObject(20)
print(triangle_object.start_position)
20
class FallingObject():
start_position = 0
def __init__(self, y):
self.start_position = y
def simulate(self, t, vy=0):
g = -9.8
# we use y2 = y1 + vy*t + 0.5*g*t^2
new_pos = self.start_position + vy*t + 0.5*g*t**2
if new_pos < 0:
new_pos=0
return new_pos
triangle_object = FallingObject(20)
triangle_object.simulate(1.1)
14.070999999999998