PROGRAMMING

m9/ PYTHON
REMEMBERS




Pure Function

p278 ! A pure function does not modify any of the objects passed. Also, it has no effect, like displaying a value or getting an input.
 
class Time:
    """Represents the day time.

    attributes: hour, minute, seconds
    """

def add_time(t, d): # pure function
    sum = Time()
    sum.hour = t.hour + d.hour
    sum.min = t.min + d.min
    sum.sec = t.sec + d.sec
    return sum

t = Time()
t.hour = 9
t.min = 45
t.sec = 0

duration = Time()
duration.hour = 1
duration.min = 35
duration.sec = 0

end = add_time(t, duration)

def print_time(t): # 2 digits
    print('%.2d:%.2d:%.2d' % (t.hour, t.min, t.sec))
    
print_time(end) # 10:80:00
... 16 lines
 
 
class Time: pass

def add_time(t, d): # pure function

    sum = Time()
    sum.hour = t.hour + d.hour
    sum.min = t.min + d.min
    sum.sec = t.sec + d.sec

    if sum.sec >= 60:
        sum.sec -= 60
        sum.min += 1

    if sum.min >= 60:
        sum.min -= 60
        sum.hour += 1

    return sum

t = Time()
t.hour = 9
t.min = 45
t.sec = 0

duration = Time()
duration.hour = 1
duration.min = 35
duration.sec = 0

end = add_time(t, duration)

def print_time(t): # 2 digits
    print('%.2d:%.2d:%.2d' % (t.hour, t.min, t.sec))
    
print_time(end) # 11:20:00
... 19 lines
 

Modifiers

p280 Functions that modifiy the objects are called modifiers. The changes are visible to the caller.
 
class Time: pass

def increment(t, seconds): # modifier
    t.sec += seconds

t = Time()
t.hour = 9
t.min = 45
t.sec = 0

increment(t, 20)

def print_time(t):
    print('%.2d:%.2d:%.2d' % (t.hour, t.min, t.sec))
    
print_time(t) # 10:45:20
... 5 lines
 
p282 Pure functions are faster to develop and less error-prone. But modifiers are convenient at times and efficient.
 
class Time: pass

def int_to_time(seconds): # pure function
    time = Time()
    minutes, time.seconds = divmod(seconds, 60)
    hour, time.minutes = divmod(minutes, 60)
    time.hour = hour
    return time

t = int_to_time(160)

def print_time(t):
    print('%.2d:%.2d:%.2d' % (t.hour, t.minutes, t.seconds))

print_time(t) # 00:02:40
... 5 lines
 

Questions    
Methods

        A B C D E F
🔔
1/1