【问题标题】:TypeError: unsupported operand type(s) for -: 'str' and 'int'TypeError: 不支持的操作数类型 -: 'str' 和 'int'
【发布时间】:2010-03-04 02:13:23
【问题描述】:

我怎么会收到这个错误?

我的代码:

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'

【问题讨论】:

    标签: python python-3.x


    【解决方案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)
      
    3. 我稍微更改了您的 API。在我看来n 应该是次数s 应该是字符串

    【讨论】:

    • +1 用于使用 for 循环。不仅在 Python 中,在绝大多数编程语言中,for-loop 构造都比 while-loop 构造好得多,因为初始化和更新代码与终止条件保持更接近,从而减少了机会犯错误。
    • 很高兴知道在 python 3 中只有 python 2 具有 int(input(some_string)) 的快捷方式 int(some_string)。同样,用于返回字符串的 raw_input() 是 python 2 的函数python 3中的输入()。
    【解决方案2】:

    供将来参考 Python 是strongly typed。与其他动态语言不同,它不会自动从一种类型或另一种类型转换对象(例如从strint),因此您必须自己执行此操作。从长远来看,你会喜欢的,相信我!

    【讨论】:

      猜你喜欢
      • 2016-04-15
      • 2012-11-29
      • 2012-12-31
      • 2021-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多