Page 483 - ComputerScience_Class_11
P. 483
Output
Value of a: 12
Value of b: 4.5
Result after addition: 16.5
Data type of result: <class ‘float’>
12.6.2 Explicit Conversion
Explicit conversion is the process of manually converting one data type into another data type in a program using
built-in functions. In this method, the programmer clearly specifies the desired data type to which a value should be
converted.
In Python, explicit conversion is performed using functions such as int(), float(), str() and bool(). It is required
when automatic conversion is not possible or when the programmer wants to change the data type intentionally. This
process is also known as type casting.
Program 17: To demonstrate Explicit Type Conversion in Python.
Program 17.py
File Edit Format Run Options Window Help
# Assign a string value to variable num_str
num_str = "50"
# Convert string to integer using int()
num_int = int(num_str)
# Convert integer to float using float()
num_float = float(num_int)
# Convert number to string using str()
num_string = str(num_float)
# Display original value and its type
print("Original value:", num_str)
print("Type of original value:", type(num_str))
# Display converted integer value and its type
print("After converting to integer:", num_int)
print("Type:", type(num_int))
# Display converted float value and its type
print("After converting to float:", num_float)
print("Type:", type(num_float))
# Display converted string value and its type
print("After converting to string:", num_string)
print("Type:", type(num_string))
Operators and Expressions 481

