TypeError:不支持的操作数类型 - :'str'和'int'

47 python python-3.x

新的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)
Run Code Online (Sandbox Code Playgroud)

Mik*_*ham 52

  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)
    
    Run Code Online (Sandbox Code Playgroud)
  3. 我稍微改变了你的API.在我看来n应该是次数,s应该是字符串.

  • +1用于使用for循环.不仅在Python中,而且在绝大多数编程语言中,for循环结构比while循环结构更好用,因为初始化和更新代码与终止条件保持更接近,减少了机会犯了错误. (13认同)

jat*_*ism 26

为了将来参考,Python是强类型的.不像其他动态语言,它不会自动地投对象从一种类型或其他(比如从strint),所以你必须自己做.从长远来看,你会喜欢这样,相信我!