TypeError: unsupported operand type(s) for -: 'str' and 'int'

PythonPython 3.x

Python 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

  1. The reason this is failing is because (Python 3) input returns a string. To convert it to an integer, use int(some_string).

  2. 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)
    
  3. 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.

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!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser285896View Question on Stackoverflow
Solution 1 - PythonMike GrahamView Answer on Stackoverflow
Solution 2 - PythonjathanismView Answer on Stackoverflow