TypeError: can only concatenate str (not "float") to str in Python

Dung Do Tien Apr 23 2022 41

Hello Guys, I am a beginner in Python and I have a homework need to calculate the area of a circle.  I wrote a small function like this:

 def areaOfCicle():
  PI = 3.14
  radius = float(input(' Please Enter the radius of a circle: '))
  area = PI * radius * radius
  circumference = 2 * PI * radius
  
  print(" The area of a circle = "  + area)
  print(" The circumference of a circle = " + circumference)

areaOfCicle()

But running the code above I got an exception TypeError: can only concatenate str (not "float") to str.

 Please Enter the radius of a circle: 6
Traceback (most recent call last):
  File "main.py", line 10, in <module>
    areaOfCicle()
  File "main.py", line 7, in areaOfCicle
    print(" Area Of a Circle = "  + area)
TypeError: can only concatenate str (not "float") to str

Why does python not auto-convert numbers to strings? and how can I solve it?

I'm using window 11 and Python 3.9.

Thank in advance

Have 2 answer(s) found.
  • r

    ramesh Apr 23 2022

    You need to convert the float value to a string before concatenating it with a string. You can use str() function to help convert float to string in Python. See example below:

     def areaOfCicle():
      PI = 3.14
      radius = float(input(' Please Enter the radius of a circle: '))
      area = PI * radius * radius
      circumference = 2 * PI * radius
      
      print(" Area Of a Circle = "  + str(area))
      print(" Circumference Of a Circle = " + str(circumference))
    
    areaOfCicle()

    #Output

     Please Enter the radius of a circle: 67
    Area Of a Circle = 14095.46
    Circumference Of a Circle = 420.76 
  • M

    Mohan Reddy Apr 23 2022

    If you concatenate the string with some dynamic value you can use format %.2f. It will auto convert any type to string. See example:

     print(" Area Of a Circle = %.2f" %area)

    I hope this tip will useful for you.

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