Python 中的 / 運算符的一切運算結果都是浮點數


letters1 = ['天','前','我','最','是','人','間','留','不','住','去','日','台'] def print_center(letters): length = len(letters) n = (length - 7) / 2 print(letters[n:n+7]) print_center(letters1) # 報錯:TypeError: list indices must be integers or slices, not float #(類型錯誤:列表分片必須用數字,而不是浮點數)

你可能會奇怪,列表長度是 13,(13-7)/2 的結果是 3,不會出現小數的結果啊?

但實際上,Python 中的 / 運算符的一切運算結果都是浮點數。所以,(13 - 7) / 2 結果是 3.0,而不是 3。這樣,letters1[n:n+7] 就相當於 letters1[3.0:3.0+7],於是就報錯了。

應該改為:

 n =int( (length - 7) / 2)



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM