簡體   English   中英

%的Python錯誤不支持的操作數類型:我的代碼為“ NoneType”和“ str”

[英]Python Error unsupported operand type(s) for %: 'NoneType' and 'str' on my code

因此,我在使用此代碼時遇到了很多麻煩...它給了我一個錯誤,並且我沒有發現任何錯誤! 我學習Python大約有15天,但我的代碼中沒有真正看到錯誤

當我嘗試在python shell中運行它時,出現此錯誤:

"unsupported operand type(s) for %: 'NoneType' and 'str'"

請幫我T____T我很沮喪!

    @classmethod
    def populationCount(cls):
        print ("The total number of humans is: %d.") %(cls.population)

您在此行遇到問題的原因:

print ("The total number of humans is: %d.") %(cls.population)

是先執行print ,然后將第一組括號中的內容作為參數。 然后,將print返回值%運算符一起使用。 print返回None ,這就是Python想要做的事情:

None % (cls.population)

您可能會弄清楚為什么行不通。

要解決此問題,請將整個%操作放在括號內,以便調用print 之前完成此操作 畢竟,您希望打印插值的結果。

print("The total number of humans is: %d." % cls.population)

如果您更換該怎么辦

print ("The total number of humans is: %d.") %(cls.population)

print ("The total number of humans is: %d." % cls.population)

在您的打印報表中?

注意:提出問題時,請嘗試將代碼示例調整為有問題的部分。 它使人們可以更輕松地為您提供幫助,實際上,在某些情況下,它甚至可以幫助您在問問題之前就發現問題。

在Python中,除非代碼另有說明,否則括號僅更改操作的順序:

print ("%s *remains silent*" % (self.name,)) # comma indicates tuple, not change of order

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM