[Tutor] scope question
Norvell Spearman
norvell@houseofspearman.org
Wed Jan 15 10:00:03 2003
--pf9I7BMVVzbSWLtt
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
python v2.2.2
I think I'm confused about scope and functions' passing of parameters.
I've been working through the ``How to Think Like a Computer Scientist''
tutorial and up 'til now everything has been fairly clear to me. The
attached file is what I've typed in from exercises and examples in
Chapter 13, ``Classes and Functions,'' with the last function,
increment, being the one I'm having problems with. Below is a
transcript from running the program and then manually calling some
functions (in idle):
************************************************
Hours: 4
Minutes: 57
Seconds: 45
Seconds to add to given time: 34
The time is now: 4:57:45
>>> t1 = Time()
>>> t1.hours, t1.minutes, t1.seconds = 4, 57, 45
>>> printTime(t1)
4:57:45
>>> increment(t1, 34)
>>> printTime(t1)
4:57:45
>>> t1 = addTime(t1, makeTime(34))
>>> printTime(t1)
4:58:19
************************************************
My question (finally) is this: Why doesn't increment alter t1 while
``t1 = addTime(t1, makeTime(34))'' in an interactive session does alter
t1?
Thanks much for any help with this.
--
Norvell Spearman
--pf9I7BMVVzbSWLtt
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment; filename="classtime.py"
import copy
class Time:
pass
def printTime(Time):
print "%d:%d:%d" % (Time.hours, Time.minutes, Time.seconds)
def convertToSeconds(t):
minutes = t.hours*60 + t.minutes
seconds = minutes*60 + t.seconds
return seconds
def makeTime(seconds):
time = Time()
time.seconds = seconds%60
time.minutes = (seconds/60)%60
time.hours = seconds/3600
return time
def addTime(t1, t2):
seconds = convertToSeconds(t1) + convertToSeconds(t2)
return makeTime(seconds)
def after(t1, t2):
if convertToSeconds(t1) > convertToSeconds(t2):
return 1
else:
return 0
# Figure out why following function doesn't work as expected:
def increment(time, seconds):
time = addTime(time, makeTime(seconds))
inTime = Time()
inTime.hours = input("Hours: ")
inTime.minutes = input("Minutes: ")
inTime.seconds = input("Seconds: ")
inSeconds = input("Seconds to add to given time: ")
increment(inTime, inSeconds)
print "The time is now: ",
printTime(inTime)
--pf9I7BMVVzbSWLtt--