0% found this document useful (0 votes)
3 views33 pages

Python Lesson4

The document discusses programming concepts such as decomposition, abstraction, and functions, emphasizing the importance of structuring code for better organization and reusability. It explains how functions serve as reusable code blocks that can simplify complex problems by hiding unnecessary details. Additionally, it covers variable scope, the difference between return and print statements, and how functions can be passed as arguments.

Uploaded by

ilovegot72305
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views33 pages

Python Lesson4

The document discusses programming concepts such as decomposition, abstraction, and functions, emphasizing the importance of structuring code for better organization and reusability. It explains how functions serve as reusable code blocks that can simplify complex problems by hiding unnecessary details. Additionally, it covers variable scope, the difference between return and print statements, and how functions can be passed as arguments.

Uploaded by

ilovegot72305
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PHY10016

DECOMPOSITION, ABSTRACTION,
FUNCTIONS

McS. Nguyen, Vuong Thuy Ngan


Previous
01 string manipulation

02 guess and check algorithms

03 approximate solutions

04 bisection method
TODAY
01 structuring programs and hiding details

02 functions

03 specifications

04 keywords: return vs print

05 scope
HOW DO WE WRITE CODE?
so far....
covered language mechanisms
know how to write different files for each computation
each file is some piece of code
each code is a sequence of instructions
HOW DO WE WRITE CODE?
problems with this approach

easy for small-scale problems


messy for larger problems
hard to keep track of details
how do you know the right info is supplied to the right
part of code
GOOD
PROGRAMMING
more code not necessarily a good thing
measure good programmers by the amount
of functionality
introduce functions
mechanism to achieve decomposition and
abstraction
EXAMPLE –LED
An LED is a black box:
You don’t need to know the detailed physics or internal
mechanisms of how it produces light.
You only interact with its interface:
Input: Electrical current.
Output: Visible light.
Interface:
Connect the LED to a power source with the appropriate
voltage and current.
The LED emits light based on the supplied energy.
ABSTRACTION IDEA: do not need to know how LED works to use it
EXAMPLE –LED

Create a large LED screen, such as a billboard or stadium display.


Each LED takes input and produces separate output
The LED work together to display the full image or video seamlessly.
DECOMPOSITION IDEA: different devices work together to achieve
an end goal
APPLY THESE CONCEPTS
TO PROGRAMMING!
CREATE STRUCTURE
with DECOMPOSITION
in LED example, separate devices
in programming, divide code into modules
are self-contained
used to break up code
intended to be reusable
keep code organized
keep code coherent
this lecture, achieve decomposition with functions
SUPRESS DETAILS
with ABSTRACTION
in LED example, instructions for how to use it are sufficient,
no need to know how to build one
in programming, think of a piece of code as a black box
cannot see details
do not need to see details
do not want to see details
hide tedious coding details
achieve abstraction with function specifications or
docstrings
FUNCTIONS
write reusable pieces/chunks of code, called functions
functions are not run in a program until they are “called” or
“invoked” in a program
function characteristics:
has a name
has parameters (0 or more, seperate by comma)
has a docstring (optional but recommended)
has a body
name
returns something

parameters body return


docstring
HOW TO WRITE and CALL/INVOKE
A FUNCTION o r
ters
m e
e r a en ts
ord nam pa u m
yw ar g
ke
def is_even( i ): n ,
atio
""" ific
c g
spe cstrin
Input: i, a positive int do
Returns True if i is even, otherwise False
"""
print("inside is_even")
ody
b return i%2 == 0

later in the code, you can call the


is_even( 3 ) function using its name and values
for parameters
IN THE FUNCTION BODY

def is_even( i ):
"""
Input: i, a positive int
Returns True if i is even, otherwise False
"""
print("inside is_even") run some comands

ord return i%2 == 0


eyw n to
k ssio turn
pre d re
ex e an
u a t
val
e
Function
write a function:
name add_numbers
parameter a and b
write docstring for it
body:
do the sum of a and b
return the result

call the function 2 times with input/parameter :

5 mins
1, 2
102, 431
take a

R E
EAAK
K
BBR
VARIABLE SCOPE
formal parameter gets bound to the value of actual parameter
when function is called
new scope/frame/environment created when enter a function
scope is mapping of names to objects

parameter
def f( x ): formal
x = x + 1
n definition
Functio
print('in f(x): x =', x)
return x
ra m c o d e
Main prog b le x
x = 3 v a ri a
arameter initializes a a ll f(x)
z = f( x ) actual p a f un ct io n c z
ma ke s o v ariables
f fu nc t io n t
g n re tu rn o
assi
VARIABLE SCOPE
VARIABLE SCOPE

Global scope Local scope

def f( x ): f some code x 3


x = x + 1
print('in f(x): x =', x)
x 3
return x

x = 3 z
z = f( x )
VARIABLE SCOPE

Global scope Local scope

def f( x ): f some code x 4


x = x + 1
print('in f(x): x =', x)
x 3
return x

x = 3 z
z = f( x )
VARIABLE SCOPE

Global scope Local scope

def f( x ): f some code x 4


x = x + 1
print('in f(x): x =', x)
x 3
return x

x = 3 z
return 4
z = f( x )
VARIABLE SCOPE

Global scope

def f( x ): f some code x


x = x + 1
print('in f(x): x =', x)
x 3
return x

x = 3 z 4

z = f( x )
ONE WARNING IF NO
returnSTATEMENT
def is_even( i ):
"""
Input: i, a positive int
Does not return anything
"""
print("inside is_even") n
t retur
i%2 == 0 withou
e ywo rd
k

Python returns the value None, if no return given


represents the absence of a value
return vs. print

return only has meaning print can be used outside


inside a function functions
only one return executed can execute many print
inside a function statements inside a function
code inside function but code inside function can be
after return statement not executed after a print
executed statement
has a value associated with has a value associated with
it, given to function caller it, outputted to the console
FUNCTIONS AS ARGUMENTS
arguments can take on any type, even functions
def func_a():
print ('inside func_a')
def func_b(y):
print ('inside func_b')
return y
def func_c(z):
print ('inside func_c')
return z()
ument
w ithno arg
n_a,
call fu ume nt
print (func_a()) on e arg unction
, w it h otherf
ll fun_b en t, an
print (5 + func_b(2)) ca e argum
wi th on
fun_c,
print (func_c(func_a)) call
FUNCTIONS AS ARGUMENTS
Global scope func_a scope
def func_a(): func_a some code
print ('inside func_a')
def func_b(y): func_b some code
print ('inside func_b')
return y func_c some code
def func_c(z):
None return None
print ('inside func_c')
return z()

print (func_a())
print (5 + func_b(2))
print (func_c(func_a))
FUNCTIONS AS ARGUMENTS
Global scope func_b scope
def func_a(): func_a some code y 2
print ('inside func_a')
def func_b(y): func_b some code
print ('inside func_b')
return y func_c some code
def func_c(z):
print ('inside func_c') None
return 2
return z()
7

print (func_a())
print (5 + func_b(2))
print (func_c(func_a))
FUNCTIONS AS ARGUMENTS
Global scope func_c scope
def func_a(): func_a some code z func_a
print ('inside func_a')
def func_b(y): func_b some code
print ('inside func_b')
return y func_c some code func_a scope
def func_c(z):
print ('inside func_c') None
return None
return z()
7

print (func_a())
None return None
print (5 + func_b(2))
print (func_c(func_a))
SCOPE EXAMPLE
inside a function, can access a variable defined outside
inside a function, cannot modify a variable defined outside --
can using global variables, but frowned upon

def f(y): def g(y): def h(y):


e d x = 1 print(x) x += 1
x re-d
efin x from g
ff de of
in sco
p e o x += 1 outsi print(x + 1)
print(x) x = 5
x = 5 h(x)
x = 5 re nt x g(x) print(x)
diffe
f(x) o b je ct print(x)
en a lE r ro r:
x wh d L oc
up
ick u n l
print(x) e g p Unbo es s lo c a
x insid c tiong n n ot a c c
it i s n ot
led fun ca wh e r e
ca l
ia b le 'x' a lue
var it h a v
ate d w
s oc i
as
SCOPE EXAMPLE
inside a function, can access a variable defined outside
inside a function, cannot modify a variable defined outside --
can using global variables, but frowned upon

def f(y): def g(y): def h(y):


x = 1 print(x) x += 1
x += 1 print(x + 1)
print(x) x = 5
x = 5 h(x)
x = 5 g(x) print(x)
f(x) print(x)
print(x)
l/m a in
g loba
x from c ode
m
progra
HARDER SCOPE EXAMPLE
Python Tutor is your best friend to help sort this out!
[Link]
SCOPE DETAILS
using [Link]

def g(x):
def h():
x = 'abc'
x=x+1
print('g: x =', x)
h()
return x
x=3
z = g(x)
End....
contact using MSTeam/Email

nvtngan@[Link]

You might also like