首页  >  文章  >  后端开发  >  如何解决 Python 中的“TypeError: Unsupported Operand Types for -: \'str\' and \'int\'\”错误?

如何解决 Python 中的“TypeError: Unsupported Operand Types for -: \'str\' and \'int\'\”错误?

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-10-19 13:35:02539浏览

How to Resolve

TypeError: 不支持的减法操作数类型

遇到错误“TypeError: unsupported operand type(s) for -: 'str'和 'int'”,它表示尝试减去两个不兼容的操作数,通常是字符串和整数。

在这种情况下,提供的 Python 代码演示了此错误:

<code class="python">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)</code>

该错误源于试图将变量 s(指定输入的结果)减 1。但是,输入返回一个字符串,Python 无法对字符串和整数执行减法。

解决此问题,收到输入后立即使用 int(num) 将 num 转换为整数:

<code class="python">num = int(input("How many times: "))</code>

此外,可以使用 for 循环简化代码:

<code class="python">def cat_n_times(s, n):
    for _ in range(n):
        print(s)</code>

修改后的代码将接受文本的字符串和 num 的整数,确保减法运算正确执行。

以上是如何解决 Python 中的“TypeError: Unsupported Operand Types for -: \'str\' and \'int\'\”错误?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn