0
繼續閱讀本書如何像計算機科學家一樣思考。有一段代碼不起作用 - 函數內部的變量不會從外部獲取(NameError:name'suma'未定義)。我想這個問題可能與回報聲明有關,而回報聲明似乎與手冊相一致。從函數返回(不工作在教程代碼上)
有云:
class Time:
pass
time1=Time()
time1.hours=11
time1.minutes=58
time1.seconds=30
time2=Time()
time2.hours=11
time2.minutes=59
time2.seconds=30
def TimePrint(p):
print( int(p.hours), ":" , int(p.minutes) , ":" , int(p.seconds) )
print()
# add these two times. Taken from the book, doesnt work though
def addTime(t1, t2):
suma = Time()
suma.hours = t1.hours + t2.hours
suma.minutes = t1.minutes + t2.minutes
suma.seconds = t1.seconds + t2.seconds
if suma.seconds >= 60:
suma.seconds = suma.seconds - 60
suma.minutes = suma.minutes + 1
if suma.minutes >= 60:
suma.minutes = suma.minutes - 60
suma.hours = suma.hours + 1
return suma
TimePrint(suma)
我可以問一個幫助?我100%肯定縮進到位。
TimePrint(更新時間(時間1,時間2)) –
'suma'是defind在本地的addTime''的範圍,而不是外界 – WhatsThePoint
WhatsThePoint可見:是的,我也覺得所以。但我沒有足夠的經驗來了解解決方案。 – Jewenile