繁体   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-2024 STACKOOM.COM