2013-07-03 29 views
1

有了這段代碼,我沒有得到 那種我想要的顯示方式。這段代碼不是按我想要的那樣打印的 - python

def printTime(time): 
    print time.hours,":",time.minutes,":",time.seconds, 

def makeTime(seconds): 
    time = Time() 
    print "have started converting seconds into hours and minutes" 
    time.hours = seconds/3600 
    print "converted into hours and no.of hours is :",time.hours 
    seconds = seconds - time.hours *3600 
    print "number of seconds left now:",seconds 
    time.minutes = seconds/60 
    print "number of minutes now is :",time.minutes 
    seconds = seconds - time.minutes*60 
    print "number of seconds left now is :",seconds 
    time.seconds = seconds 
    print "total time now is:",printTime(time) 

最後一行原因造成的問題是:

print "total time now is:",printTime(time) 

我想要的結果是在格式如下─現在 總時間爲:12時42分25秒

但我得到的是 總時間現在是:12:42:25無

但是當我將該行寫爲:

print "total time now is:" 
printTime(time) 

然後我得到的結果是 - 總現在時間是: 12時42分二十五秒

當我不處於同一行寫 的printTime(時間)功能無事不出現作爲印刷品。

那麼,這裏真的發生了什麼?

編輯:我試過使用return語句,但結果仍然是一樣的。所以,我應該在哪裏使用return語句。也許我錯誤地使用了它。 我試着這樣做,因爲

print "total time now is:",return printTime(time) 

但這給出了一個錯誤。

然後,我嘗試做這種方式 -

print "total time now is:",printTime(time) 
return printTime(time) 

仍然得到同樣的結果。

回答

4

您正在打印printTime()函數的返回值

Python中的所有函數都有一個返回值,如果您不使用return語句,則該值默認爲None

而是在printTime()打印功能的,該函數重命名爲formatTime(),並使其返回格式化字符串:

def formatTime(time): 
    return '{0.hours}:{0.minutes}:{0.seconds}'.format(time) 

然後用

print "total time now is:",formatTime(time) 

上述str.format() method使用format string syntax引用傳入的第一個參數(0,python索引是從0開始的),並插入來自該參數的屬性。第一個參數是您的time實例。

可以就此展開,並添加一些更多的格式,如零填充你的號碼:

def formatTime(time): 
    return '{0.hours:02d}:{0.minutes:02d}:{0.seconds:02d}'.format(time) 
+0

的Martijn嗨,你的代碼的偉大工程,但我不明白使用「{} 0.hours:{0 .minutes}:{0.seconds}'。你能解釋一下嗎? 什麼是0?我使用time.minutes和time.hours代替。 – faraz

+0

@faraz:我稍微擴展了答案;你也可以使用關鍵字參數:''{time.hours}:{time.minutes}:{time.seconds}'.format(time = time)'。 –

+0

感謝您的解釋。 我也會閱讀關於格式字符串語法。 – faraz

1

printTime返回一個打印功能調用,你再嘗試打印。

更改printTime到:

return time.hours + ":" + time.minutes + ":" + time.seconds 

或者,更有效地:

return "%s:%s:%s" % (time.hours, time.minutes, time.seconds) 
+0

乍得,返回time.hours +「:」+ time.minutes +「:」+ time.seconds行給出一個類型錯誤:不支持的操作數類型。 而第二行效果很好。 現在,我不明白爲什麼會發生這種情況? – faraz

+0

@faraz,哦,那是因爲'time.hours','time.minutes'和'time.seconds'是返回的整數(或者一些非字符串值),python不能將字符串連接到非字符串。所以實際上寫這個的方式是'return str(time.hours)+「:」+ str(time.minutes)'等等。但是由於python處理字符串連接的方式,效率要低得多,所以我會推薦第二行。 – Chad

相關問題