w3resource

Difference between the int and float data types in Python

Understanding the difference between int and float data types in Python

Python's int and float data types represent numerical values, but they differ in how they store and handle numbers.

Integers (int):

  • Integers are whole numbers, both positive and negative, without fractions.
  • In Python, they are represented by ints, which have unlimited precision, so they can hold any number (limited only by memory).
  • Integers are immutable, so once created, their value cannot be changed.

Floating-Point Numbers (float):

  • Floating-point numbers represent real numbers and can have fractions.
  • They are represented as float in Python and adhere to the IEEE 754 standard for floating-point arithmetic.

Python's Handling of Integers and Floating-Point Numbers:

Precision:

  • Due to their unlimited precision, integers can accurately represent large numbers without sacrificing accuracy.
  • Floating-point numbers have limited precision due to fixed-size binary representation. As a result, certain calculations may produce small rounding errors.

Arithmetic Operations:

  • Python supports basic arithmetic operations (addition, subtraction, multiplication, division) for both integers and floating-point numbers.
  • When an integer and a floating-point number are involved in an operation, Python automatically transforms the integer to a floating-point number and performs the operation using floating-point arithmetic.

Type of conversion:

  • Python performs implicit type conversion when mixing integers and floating-point numbers in expressions. The result is a float if any of the operands are floating.
  • Explicit type conversion (casting) can also be used to convert an integer to a float and vice versa if required.

Division:

  • The division operator (/) always returns a float, even if the division results in a whole number.
  • To perform integer division (floor division), you can use the double slash operator (//).

Example:

Code:

# Integer and float operations
x = 15     # Integer
y = 14.45  # Float
add_result = x + y
sub_result = x - y
mul_result = x * y
# Result will be a float
div_result = x / y      
# Integer division, result will be an floor
floor_div_result = x // y

print(add_result)        # Output: 29.45  
print(sub_result)        # Output: 0.5500000000000007  
print(mul_result)        # Output: 216.75 
print(div_result)        # Output: 1.0380622837370244 
print(floor_div_result)  # Output: 1.0

Output:

29.45
0.5500000000000007
216.75
1.0380622837370244
1.0


Follow us on Facebook and Twitter for latest update.