TypeError:-: ‘ str’和‘ 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'
536848 次浏览
  1. 失败的原因是(Python3) 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. I changed your API above a bit. It seems to me that n should be the number of times and s should be the string.

对于将来的参考,Python 是 强类型。与其他动态语言不同,它不会自动将对象从一种类型强制转换为另一种类型(比如从 strint) ,因此必须自己进行强制转换。从长远来看,你会喜欢的,相信我!

对于未来的读者,使用 注释来避免这样的错误:

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)