Introduction:
This Python code demonstrates how to convert a float to an integer using explicit type conversion. It showcases the difference in data types before and after the conversion.
Code:
num1 = 10.2
num2 = 20.6
num3 = (num1 + num2)
print(num3)
print(type(num3))
num4 = int(num1 + num2)
print(num4)
print(type(num4))
Logic:
- The program assigns the values 10.2 and 20.6 to two float variables, num1 and num2 respectively.
- It then calculates the sum of num1 and num2 and assigns the result to num3.
- The program then prints the value of num3 and its data type.
- Next, the sum of num1 and num2 is converted to an integer using the int() function, and the resulting value is assigned to num4.
- Finally, the program prints the value of num4 and its data type.
Output:
>> 30.8
>> <class ‘float’>
>> 30
>> <class ‘int’>