Table of Contents

Explicit Type Conversion Int to Float | Pictoblox

Example Description
Convert integer to a float using explicit type conversion which convert the result to a float, also check types before/after the conversion.

Introduction:

In Python, you can convert an integer to a float using explicit type conversion. This allows you to perform mathematical operations with integers and then convert the result to a float if needed. By doing so, you can work with decimal values and have more control over the precision of your calculations.

Code:

num1 = 10
num2 = 20
num3 = num1 + num2
print(num3)
print(type(num3))
num4 = float(num1 + num2)
print(num4)
print(type(num4))

Logic:

The Python code provided demonstrates how to explicitly convert an integer to a float.

  1. It starts by defining two variables, “num1” and “num2,” and assigning them the values of 10 and 20, respectively.
  2. The next line adds “num1” and “num2” together, resulting in “num3.”
  3. The code then prints the value of “num3” and its type.
  4. To convert the sum to a float, the code assigns the result of “num1 + num2” to “num4” and explicitly converts it to a float using the “float()” function
  5. The code then prints the value of “num4” and its type.

Output:

>> 30

>> <class ‘int’>

>> 30.0

>> <class ‘float’>