[英]TypeError: unsupported operand type(s) for -: 'str' and 'int'
How come I'm getting this error?我怎么会收到这个错误?
My code:我的代码:
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)
Error:错误:
TypeError: unsupported operand type(s) for -: 'str' and 'int'
The reason this is failing is because (Python 3) input
returns a string.失败的原因是(Python 3) input
返回一个字符串。 To convert it to an integer, use int(some_string)
.要将其转换为整数,请使用int(some_string)
。
You do not typically keep track of indices manually in Python.您通常不会在 Python 中手动跟踪索引。 A better way to implement such a function would be实现这种功能的更好方法是
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)
I changed your API above a bit.我在上面更改了您的 API。 It seems to me that n
should be the number of times and s
should be the string .在我看来, n
应该是次数, s
应该是字符串。
For future reference Python is strongly typed<\/a> .供将来参考 Python 是强类型<\/a>的。 Unlike other dynamic languages, it will not automagically cast objects from one type or the other (say from str<\/code> to
int<\/code> ) so you must do this yourself.
与其他动态语言不同,它不会自动从一种类型或另一种类型转换对象(例如从
str<\/code>到
int<\/code> ),因此您必须自己执行此操作。
You'll like that in the long-run, trust me!从长远来看,你会喜欢的,相信我!
"
For future readers, use annotations to prevent such mistakes:对于未来的读者,请使用注释来防止此类错误:
def cat_n_times(s: str, n: int):
for i in range(n):
print(s)
text = input("What would you like the computer to repeat back to you: ")
num = input("How many times: ") # Convert to an int immediately.
cat_n_times(text, num)
Mypy gives a nice error: Mypy给出了一个很好的错误:
annotations.py:9: error: Argument 2 to "cat_n_times" has incompatible type "str"; expected "int"
Found 1 error in 1 file (checked 1 source file)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.