Python - Videos and Questions

38 / 78

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 the string. Let's do it.

INSTRUCTIONS

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

  • Define a variable area_of_circle with the value 78.5

  • Convert area_of_circle to string with the 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)
    


Note - Having trouble with the assessment engine? Follow the steps listed here

Loading comments...