TypeError: unsupported operand type(s) for -: 'str' and 'int'
PythonPython 3.xPython Problem Overview
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'
Python Solutions
Solution 1 - Python
-
The reason this is failing is because (Python 3)
input
returns a string. To convert it to an integer, useint(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 ands
should be the string.
Solution 2 - Python
For future reference Python is strongly typed. Unlike other dynamic languages, it will not automagically cast objects from one type or the other (say from str
to int
) so you must do this yourself. You'll like that in the long-run, trust me!