TypeError: unsupported operand type(s) for /: 'str' and 'int' in Python

Dung Do Tien May 07 2022 21

Hello guys, I'm using Python to help create an application that helps calculate the area of the triangle. Three sides of the triangle when input from the user, it's not hard to code. Like this:

 side_1st = input('Enter first side: ')
side_2nd = input('Enter second side: ')
side_3rd = input('Enter third side: ')

# calculate the semi-perimeter
s = (side_1st + side_2nd + side_3rd) / 2

# calculate the area
area = (s*(s-side_1st)*(s-side_2nd)*(s-side_3rd)) ** 0.5

print('The area of the triangle equal '  + str(area))

But when I was running this code, I get an exception TypeError: unsupported operand type(s) for /: 'str' and 'int'.

 Enter first side: 5
Enter second side: 5
Enter third side: 5
Traceback (most recent call last):
  File "<string>", line 6, in <module>
TypeError: unsupported operand type(s) for /: 'str' and 'int'

Anyone can help me explain it?

I'm using Python 3.9 and Windows 11.

Thanks in Advance.

Have 1 answer(s) found.
  • R

    Ramesh kumar May 07 2022

    You cannot multiply a string with a non-integer value in Python. If we multiply a string with another string without converting to an integer or floating-point, we get an error can’t multiply sequence by non-int of type ‘str’.

    Solution: Use the float() method to help converts strings to number first. See the example below:

     side_1st = float(input('Enter first side: '))
    side_2nd = float(input('Enter second side: '))
    side_3rd = float(input('Enter third side: '))
    
    # calculate the semi-perimeter
    s = (side_1st + side_2nd + side_3rd) / 2
    
    # calculate the area
    area = (s*(s-side_1st)*(s-side_2nd)*(s-side_3rd)) ** 0.5
    
    print('The area of the triangle equal '  + str(area))

    #Output

     Enter first side: 6
    Enter second side: 7
    Enter third side: 8
    The area of the triangle equal 20.33316256758894

    I hope this answer is all you need.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close