REMEMBER PYTHON

# MINTE9 2REMEMBER

Last update:   23-07-2021

### 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.
 RunCode
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

def print_time(t): # 2 digits
print('%.2d:%.2d:%.2d' % (t.hour, t.min, t.sec))

print_time(end) # 10:80:00
... 22 lines˄˄˄
 RunCode
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

def print_time(t): # 2 digits
print('%.2d:%.2d:%.2d' % (t.hour, t.min, t.sec))

print_time(end) # 11:20:00
... 25 lines˄˄˄

### Modifiers

p280 Functions that modifiy the objects are called modifiers. The changes are visible to the caller.
 RunCode
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
... 11 lines˄˄˄
p282 Pure functions are faster to develop and less error-prone. But modifiers are convenient at times and efficient.
 RunCode
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
... 11 lines˄˄˄

Questions
CARD
26
32

A B C D E F
ðŸ””
1/1