Home  >  Article  >  Backend Development  >  How to Resolve \"TypeError: Unsupported Operand Types for -: \'str\' and \'int\'\" Error in Python?

How to Resolve \"TypeError: Unsupported Operand Types for -: \'str\' and \'int\'\" Error in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-19 13:35:02539browse

How to Resolve

TypeError: Unsupported Operand Types for Subtraction

When encountering the error "TypeError: unsupported operand type(s) for -: 'str' and 'int'", it signifies that an attempt has been made to subtract two incompatible operands, typically a string and an integer.

In this instance, the provided Python code demonstrates this error:

<code class="python">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)</code>

The error stems from attempting to subtract the variable s (assigned the result of input) by 1. However, input returns a string, and Python cannot perform subtraction on strings and integers.

To resolve this, convert num to an integer using int(num) immediately after receiving the input:

<code class="python">num = int(input("How many times: "))</code>

Additionally, the code could be simplified using a for loop:

<code class="python">def cat_n_times(s, n):
    for _ in range(n):
        print(s)</code>

This revised code will accept a string for text and an integer for num, ensuring that the subtraction operation is performed correctly.

The above is the detailed content of How to Resolve \"TypeError: Unsupported Operand Types for -: \'str\' and \'int\'\" Error in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn