Table of Contents

Explicit type conversion from float to int | Pictoblox

Example Description
Convert a float to an integer in Python using explicit type conversion. Explore output and the difference in data types after the conversion.

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:

  1. The program assigns the values 10.2 and 20.6 to two float variables, num1 and num2 respectively.
  2. It then calculates the sum of num1 and num2 and assigns the result to num3.
  3. The program then prints the value of num3 and its data type.
  4. Next, the sum of num1 and num2 is converted to an integer using the int() function, and the resulting value is assigned to num4.
  5. Finally, the program prints the value of num4 and its data type.

Output:

>> 30.8

>> <class ‘float’>

>> 30

>> <class ‘int’>