」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何解決“TypeError: Unsupported Operand Type(s) for -: \'str\' and \'int\'\”錯誤?

如何解決“TypeError: Unsupported Operand Type(s) for -: \'str\' and \'int\'\”錯誤?

發佈於2024-11-09
瀏覽:506

How to Resolve \

"解決TypeError: Unsupported Operand Type(s) for -: 'str' and 'int'"

嘗試編碼時在Python中,遇到類似「TypeError: unsupported operand type(s) for -: 'str' and 'int'」錯誤的情況並不少見。當嘗試對不同資料類型執行數學運算(例如從字串中減去整數)時,通常會出現此錯誤。

要了解此錯誤,讓我們檢查導致該錯誤的程式碼:

def cat_n_times(s, n):
    while s != 0:
        print(n)
        s = s - 1

text = input("What would you like the computer to repeat back to you: ")
num = input("How many times: ")

cat_n_times(num, text)

這裡的問題在於輸入函數,它為text和num傳回一個字串。當程式碼嘗試從字串 (num) 中減去整數 (s - 1) 時,會導致錯誤。

解決方案 1:轉換輸入

One解決方案是在執行數學運算之前將輸入從字串轉換為整數。這可以使用int() 函數來完成:

num = int(input("How many times: "))

透過將num 轉換為整數,我們可以確保數學運算與s.

的兼容性解決方案2:使用替代迭代

不要手動追蹤索引,請考慮採用更Pythonic 的迭代方法:

def cat_n_times(s, n):
    for i in range(n):
        print(s)

text = input("What would you like the computer to repeat back to you: ")
num = int(input("How many times: "))

cat_n_times(text, num)

這裡,有range(n)的for迴圈有效地處理了迭代。

API注意事項

錯誤也突顯 API 設計的潛在問題。 text是字串,num表示次數可能更直觀。這種情況下可以對API進行對應的修改。

版本聲明 本文轉載於:1729316118如有侵犯,請洽[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3