簡體   English   中英

TypeError: 不支持的操作數類型 -: 'str' 和 'int'

[英]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)

錯誤:

TypeError: unsupported operand type(s) for -: 'str' and 'int'
  1. 失敗的原因是(Python 3) input返回一個字符串。 要將其轉換為整數,請使用int(some_string)

  2. 您通常不會在 Python 中手動跟蹤索引。 實現這種功能的更好方法是

    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: ")) # Convert to an int immediately. cat_n_times(text, num)
  3. 我在上面更改了您的 API。 在我看來, n應該是次數s應該是字符串

對於未來的讀者,請使用注釋來防止此類錯誤:

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


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

cat_n_times(text, num)

Mypy給出了一個很好的錯誤:

annotations.py:9: error: Argument 2 to "cat_n_times" has incompatible type "str"; expected "int"
Found 1 error in 1 file (checked 1 source file)

暫無
暫無

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

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