Introduction to Python

38 / 79
   

Python - Type Conversion

Different types behave differently in Python. For example, "+" operator on integers just sums up the integers, while on strings it concatenates the string.

Let's say in the previous example, we want to print the message "Area of the circle is - 78.5"

How do we do that? Below code will not work as we can not concatenate string and float

print("Area of the circle is - " + area_of_circle)

Then how should we do it?

We will have to convert area_of_circle to string. Let's do it.

Instructions-

Use Jupyter notebook on the right-hand side. Press "Shift + Enter" to run code in individual cells.

  • Convert area_of_circle to string with str() method.

    area_of_circle = str(area_of_circle)

  • Define a variable area_of_circle_msg and concatenate the two strings.

    area_of_circle_msg = "Area of the circle is - " + area_of_circle
    print(area_of_circle_msg)