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'

原文由 user285896 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 676
1 个回答
  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)

  1. 我稍微更改了上面的 API。在我看来 n 应该是 _次数_, s 应该是 _字符串_。

原文由 Mike Graham 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题