2016-06-24 30 views
-3

該函數採用兩個整數x是小時,y是分鐘。該函數應該將文本中的時間打印到最近的小時。 這是我寫的代碼。需要兩個值的Python函數

def approxTime(x, y): 
    if int(y) <= 24: 
     print("the time is about quarter past" + int(y)) 
    elif 25 >= int(y) <=40: 
     print("the time is about half past" + int(y)) 
    elif 41 >= int(y) <= 54: 
     print("the time is about quarter past" + int(y+1)) 
    else: 
     print("the time is about" + int(y+1) +"o'clock") 
approxTime(3, 18) 

但是我收到此錯誤消息。

Traceback (most recent call last): File 
    "C:/Users/Jafar/Documents/approxTime.py", line 14, in <module> 
     approxTime(3, 18) File "C:/Users/Jafar/Documents/approxTime.py", line 5, in approxTime 
     print("the time is about quarter past" + int(y)) TypeError: Can't convert 'int' object to str implicitly 
+2

不要叫'INT(Y + 1)''調用STR(INT(Y)+1)'或再次更好的使用'str.format' –

+0

BTW,這應該是'x',不'print'語句中的'y' - 請將變量名改爲'hours'和'minutes'或類似的東西來使事情變得更加明顯。 –

+1

下次嘗試使用Google搜索錯誤消息。 – TigerhawkT3

回答

3

您試圖連接字符串和整數對象!將對象y(或y+1)轉換爲字符串,然後追加。像:

print("the time is about quarter past" + str(y)) #similarly str(int(y)+1) 
+0

'y'是一個字符串,我想這樣加1你需要'str(int(y)+ 1)' –

+0

正確,我剛纔在答案中解決了這個問題。 – SuperSaiyan

+0

@SuperSaiyan如果'y'是一個字符串我猜它應該是str(int(y)+1)str(int(y + 1)) – mgc

1

您必須投射到一個字符串。你試圖連接一個int和一個字符串,這是不兼容的。

def approxTime(x, y): 
    if int(y) <= 24: 
     print("the time is about quarter past" + str(y)) 
    elif 25 >= int(y) <=40: 
     print("the time is about half past" + str(y)) 
    elif 41 >= int(y) <= 54: 
     print("the time is about quarter past" + str(y+1)) 
    else: 
     print("the time is about" + str(y+1) +"o'clock") 
approxTime(3, 18) 
相關問題