Decomposition & Abstraction
{ D e c o m p o s i t i o n : break problems into small pieces A b s t r a c t i o n : Black box \begin{cases}Decomposition: \textit{break problems into small pieces}\\Abstraction: \textit{Black box}\end{cases} {Decomposition:break problems into small piecesAbstraction:Black box
Function
-
Characteristic:
name
parameter
docstring
body
def is_even(i): # name and the parameter
'''
here is the docstring
'''
<body>
is_even(n) #call the function
The indentation indicated the body of the function.
Calling function and Scope
Return & Print
Return | |
---|---|
Only has meaning inside the function | Can be used outside the function |
Only one return executed inside a function | Can execute many print statement inside a function |
- Python returns the value None, if nothing return given.
Scope
- inside a function, can access a variable outside
- inside ac function, cannot modify a variable outside
Keyword Arguments
EXAMPLE
def printName(firstname, lastname, reverse):
if reverse:
print()
else:
print()
- Reverse the input order
printName(lastname = 'balaba', firstname='balaba',reverse = False)
- Given default value
def printName(firstname, lastname, reverse = False)
<scope>
printName(balaba,balaba) #THE REVERSE WILL BE DEFAULT VALUE
Specification
'''
input: i , a positive int
Returns True if i is even, False if i is odd
'''
Objects
Built-in Types - Python 3.10.2 documentation
capitalize | upper | isupper | swapcase | index | find | count | replace |
---|---|---|---|---|---|---|---|
index
raises ValueError when x is not found in s
find Return -1
if sub is not found.
Interaction vs. Recursion
RECURSION
Breaking down question into a smaller version of the question itself.
a × b = a + a + . . . + a ⏟ b = a + a + a + . . . + a ⏟ b − 1 a\times b = \underbrace{a+a+...+a}_{b}\\= a+\underbrace{a+a+...+a}_{b-1} a×b=b a+a+...+a=a+b−1 a+a+...+a
# Recursion
def mult(a,b)
if b == 1:
return a
else:
return a + mult(a, b-1)
INTERACTION
Looping constructs lead to interactive algorithms
# Interaction
def mult_inter(a,b)
result = 0
while b > 0:
result += a
b -= 1
return result
Files
module and files
a module is a .py doc
# the file circle.py contains:
pi = 3.14159
def area(radius):
return pi*(radius**2)
def circumference(radius):
return 2*pi*radius
- import and use the module
import circle
pi = 3
print(pi) # print out 3
print(circle.pi) # print out 3.14159
print(circle.area(3))
- Dont want to refer to functions and variable by module,
from cicle import *
Files
- save work for latter use
OPEN and CLOSE
#open a file called kids for writing use
nameHandle = open('kids','w')
name = input('type something:')
nameHandle.write(name+'\n')
nameHandle.close()
#open a file called kids for reading use
nameHandle = open('kids','r')
print(line)
nameHandle.close()