Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python TypeError:';的操作数类型不受支持;str';和';int';_Python_Python 3.x - Fatal编程技术网

Python TypeError:';的操作数类型不受支持;str';和';int';

Python TypeError:';的操作数类型不受支持;str';和';int';,python,python-3.x,Python,Python 3.x,我怎么会犯这个错误 我的代码: 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) 错误: Typ

我怎么会犯这个错误

我的代码:

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 3)
    input
    返回一个字符串。要将其转换为整数,请使用
    int(一些字符串)

  • 在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)
    
  • 我对你的API做了一点以上的修改。在我看来,
    n
    应该是次数,
    s
    应该是字符串


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

    +1用于使用for循环。不仅在Python中,而且在绝大多数编程语言中,for循环构造要比while循环构造好得多,因为初始化和更新代码更接近终止条件,从而减少了出错的机会。很高兴知道,只有Python 2具有快捷方式int(some_string)表示python 3中的int(input(some_string))。同样,用于返回字符串的raw_input()也是python 3中用于input()的python 2函数。