TypeError unsupported operand types - 'str' and '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 types - 'str' and 'int'
有人知道吗 失败的原因是因为(Python 3)input返回一个字符串。要将其转换为整数,请使用int(some_string),你通常不会在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]