Categories
Python Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *