简体   繁体   English

TypeError: 不支持的操作数类型 -: 'str' 和 'int'

[英]TypeError: unsupported operand type(s) for -: 'str' and 'int'

How come I'm getting this error?我怎么会收到这个错误?

My code:我的代码:

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)

Error:错误:

TypeError: unsupported operand type(s) for -: 'str' and 'int'
  1. The reason this is failing is because (Python 3) input returns a string.失败的原因是(Python 3) input返回一个字符串。 To convert it to an integer, use int(some_string) .要将其转换为整数,请使用int(some_string)

  2. You do not typically keep track of indices manually in Python.您通常不会在 Python 中手动跟踪索引。 A better way to implement such a function would be实现这种功能的更好方法是

    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.我在上面更改了您的 API。 It seems to me that n should be the number of times and s should be the string .在我看来, n应该是次数s应该是字符串

For future readers, use annotations to prevent such mistakes:对于未来的读者,请使用注释来防止此类错误:

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 gives a nice error: 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.

相关问题 typeerror 不支持 / &#39;str&#39; 和 &#39;int&#39; 的操作数类型 - typeerror unsupported operand type(s) for / 'str' and 'int' TypeError:-:“ str”和“ int”的不受支持的操作数类型 - TypeError:unsupported operand type(s) for -: 'str' and 'int' + 不支持的操作数类型:“int”和“str”[TypeError] - unsupported operand type(s) for +: 'int' and 'str' [TypeError] 类型错误:-= 不支持的操作数类型:'int' 和 'str' - TypeError: unsupported operand type(s) for -=: 'int' and 'str' 类型错误:&lt;&lt;:&#39;str&#39; 和 &#39;int&#39; 的操作数类型不受支持 - TypeError: unsupported operand type(s) for <<: 'str' and 'int' TypeError:-:“ int”和“ str”不支持的操作数类型 - TypeError: unsupported operand type(s) for -: 'int' and 'str' 类型错误:不支持 / 的操作数类型:&#39;str&#39; 和 &#39;int&#39; (2) - TypeError: unsupported operand type(s) for /: 'str' and 'int' (2) TypeError:-:“ str”和“ int”的不受支持的操作数类型 - TypeError: unsupported operand type(s) for -: 'str' and 'int' TypeError:+ =不支持的操作数类型:“ int”和“ str” - TypeError: unsupported operand type(s) for +=: 'int' and 'str' TypeError:|:“ int”和“ str”不支持的操作数类型 - TypeError: unsupported operand type(s) for |: 'int' and 'str'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM