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