Menu Close

How to fix TypeError: unsupported operand type(s) for -: ‘str’ and ‘int’ when using Python input?

Sometimes, we want to fix TypeError: unsupported operand type(s) for -: ‘str’ and ‘int’ when using Python input

In this article, we’ll look at how to fix TypeError: unsupported operand type(s) for -: ‘str’ and ‘int’ when using Python input.

How to fix TypeError: unsupported operand type(s) for -: ‘str’ and ‘int’ when using Python input?

To fix TypeError: unsupported operand type(s) for -: ‘str’ and ‘int’ when using Python input, we should convert the string returned by input to an int.

For instance, we write

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: "))

cat_n_times(text, num)

We call input with a string for the prompt.

And then we call input to get the number entered by the user.

Next, we call int to convert the string of the value entered by the user to an int.

Then we can use value n in cat_n_times as an argument of range`.

Conclusion

To fix TypeError: unsupported operand type(s) for -: ‘str’ and ‘int’ when using Python input, we should convert the string returned by input to an int.

Posted in Python, Python Answers