Python Type Casting

Python Type Casting

When you convert a type into another type that is called Type Casting.

Casting in Python can be acheive by constructors.

There are two type of Casting:

  1. Implicit Casting
  2. Explicit Casting

1. Implicit Casting

Python automatically converts one data type to another data type.

For Example:

        num1=10
        num2=1.2
        num3=num1+num2

        print(num3)

Result: 11.2

        num1=10
        name="deep"
        data=num1+name

        print(data)

data=num1+name TypeError: unsupported operand type(s) for +: 'int' and 'str'

Note in this case you can get error TypeError. Python is not able use Implicit Conversion in such condition it provide Explicit Casting.

2. Explicit Casting

Explicit Casting is used to convert a type to another type.

You can acheive Explicit Casting using predefine functions like int(), float(), str() etc.

For Example:

        n1="12"
        #convert string to int
        x=int(n1)

        #convert string into float
        y=float(n1)

        #convert int to string
        n2=10
        z=str(n2)

        print(x)
        print(y)
        print(z)

Result : 12

Result : 12.0

Result : 10

No comments: