You are on page 1of 2

Python notes

Type Conversion

The process of converting the value of one data type (integer, string, float,
etc.) to another is called type conversion. Python has two types of type
conversion.

Implicit Type Conversion


Implicit conversion doesn't need any user involvement. For example:

num_int = 123 # integer type


num_flo = 1.23 # float type

num_new = num_int + num_flo

print("Value of num_new:",num_new)
print("datatype of num_new:",type(num_new))

When you run the program, the output will be:

Value of num_new: 124.23


datatype of num_new: datatype of num_new: <class 'float'>

Here,  num_new  has float data type because Python always converts smaller
data type to larger data type to avoid the loss of data.
Here is an example where Python interpreter cannot implicitly type convert.

num_int = 123 # int type


num_str = "456" # str type

print(num_int+num_str)

When you run the program, you will get

TypeError: unsupported operand type(s) for +: 'int' and 'str'


However, Python has a solution for this type of situation which is know as
explicit conversion.

Explicit Conversion
In case of explicit conversion, you convert the datatype of an object to the
required data type. We use predefined functions like int(), float(), str() etc.
to perform explicit type conversion. For example:

num_int = 123 # int type


num_str = "456" # str type

# explicitly converted to int type


num_str = int(num_str)

print(num_int+num_str)

What is pass statement in Python?


In Python programming, the pass statement is a null
statement. The difference between a comment and a pass
statement in Python is that while the interpreter ignores a
comment entirely, pass is not ignored.

However, nothing happens when the pass is executed. It


results in no operation (NOP).

You might also like