image
image
image

II.  Explicit Conversion

image

Here, programmers convert the data type of a named programming object to the needed data type. Explicit conversion is attained through the functions float(), int(), and str() among others.

The syntax for the specific or explicit conversion is:

(needed_datatype) (expression)

Example

Summing of a string and integer using by using explicit conversion

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

number_int=431

number_str=”231”

print(“Type of data of number_int-“, type(number_int))

print(“Type of data number_str prior to Type Casting-“, type(number_str))

number_str=int(number_str)

number_sum=number_int+number_str

print(“Addition of number_int and number_str-“, number_sum)

print(“Type of data of the sum-“, type(number_sum))

Note: Running this program will display the data types and sum and display an integer and string.

Discussion

In the above program, we added number_str and number_int variable. We then converted number_str from string(higher data type) to integer(lower data type)type using int() function to perform the summation. Python manages to add the two variables after converting number_str to an integer value. The number_sum value and data type are an integer data type.

Summary

The conversion of the object from one data type to another data type is known as type conversion. The python interpreter automatically performs implicit type conversion. Implicit type conversion intends to enable Python to avoid data loss. Typecasting or explicit conversion happens when the data types of object are converted using the predefined function by the programmer. Unlike implicit conversion, typecasting can lead to data loss as we enforce the object to a particular data type.

The previous explicit conversion/typecasting can be written as:

Start IDLE.

Navigate to the File menu and click New Window.

Type the following:

number_int=431  #int data type

number_str=”231”  #string data type

number_str=int(number_str)  #int function converting string into int data type

number_sum=number_int+number_str  #variable number_sum

print(“Addition of number_int and number_str-“, number_sum)

Point to Note

Explicit conversion/Type casting requires some practice to master, but it is easy.

The trick is here:

the variable name to convert=predefined function for the desired data type (variable name to convert)

Practice Exercise

Use the knowledge of type casting/explicit data conversion to write a program to compute the sum of:

a.  score_int=76

score_str=”61.”

b.  count_str=231

count_str=”24”

Use the knowledge of type casting/explicit data conversion to write a program find the product of:

c.  number_int=12

number_str=”5.”

d.  odds_int=6

odds_str=”2”

e.  minute_int=45

minute_str=”7”