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. To convert it to an integer, use int(some_string)
.
You do not typically keep track of indices manually in 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. It seems to me that n
should be the number of times and s
should be the string .
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:
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.