2015-10-20 163 views
0

我想在python中做一個簡單的計時器腳本。我看到很多其他人都太有這個錯誤,但我覺得我的錯誤可能會有所不同,因爲我是新來的Python:python錯誤「typeerror:nonetype object not callable」

time=60 
from time import sleep 
while (time>0): 
    print ("you have") (time) ("seconds left") 
    time-=1 
    sleep(1) 
下面

結果如下:

>>> you have Traceback (most recent call last): File "H:\counter.py", line 4, in <module> print ("you have") (time) ("seconds left") TypeError: 'NoneType' object is not callable

任何人都可以發現此錯誤?使用%s的 也使我無法在時間變量周圍使用+'s和str()

回答

1

函數只能有一組參數。

print_statement = "you have" + str(time) + "seconds left" 
print(print_statement) 

上面的代碼應該可以工作。

+0

作品,,謝謝! – dioretsa

+0

@dioretsa:如果它對你有幫助,請接受我的回答:) –

1

您對print函數使用了錯誤的語法。請注意,中的print是可調用的。所以當你打電話給你的時候,你可以通過你需要打印的所有參數作爲參數。

因此

print ("you have", time, "seconds left") 

是正確的語法。您也可以選擇指定分隔符。


對於後人,TypeError: 'NoneType' object is not callable是拋出當您嘗試使用NoneType對象調用錯誤。當Python發現你試圖通過time(一個對象)到print ("you have"),它返回一個NoneType對象標記出Python。

請記住,在print調用,它主要是返回一個NullType對象(這是什麼都沒有爲此事,因此不可調用的)。

+0

即使對於python2,語法也是錯誤的,應該是'print(「you have」),(time),(「seconds left」)'。 dioretsa的打印幾乎看起來像haskell函數調用 –

+0

@Lærne確實如此。 :d。它也是[tag:python-2]'print'中元組打包和解包的極好例子。我只參考了[tag:python-3],因爲這就是原始代碼語言對我來說的樣子。 [tag:python-2]'print'實際上並不需要將個別參數放在圓括號內(看起來過多並且促成了不好的做法)。 – Quirk

相關問題