Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do I fix unsupported operand type s?

The Python "TypeError: unsupported operand type(s) for /: 'str' and 'int'" occurs when we try to use the division / operator with a string and a number. To solve the error, convert the string to an int or a float , e.g. int(my_str) / my_num .

What does TypeError unsupported operand type S for -: STR and STR mean?

The Python "TypeError: unsupported operand type(s) for -: 'str' and 'str'" occurs when we try to use the subtraction - operator with two strings. To solve the error, convert the strings to int or float values, e.g. int(my_str_1) - int(my_str_2) .

What does unsupported operand type S for +: int and STR mean?

The TypeError: unsupported operand type(s) for +: 'int' and 'str' error occurs when an integer value is added with a string that could contain a valid integer value. Python does not support auto casting. You can add an integer number with a different number. You can't add an integer with a string in Python.

How do you fix unsupported operand type S for NoneType and int?

Unsupported operand type(s) for +: 'NoneType' and 'int' # The Python "TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'" occurs when we try to use the addition (+) operator with a None value. To solve the error, figure out where the variable got assigned a None value and correct the assignment.


  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.


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!