Back to Python
2026-03-266 min read

Python float()

Learn Python float() step by step with clear examples and exercises.

Why This Matters

Python's float() function is a powerful tool for working with real numbers, or floating point numbers, in your code. This lesson will walk you through the core concept of using float(), provide worked examples, common mistakes to avoid, practice questions, and answers to frequently asked questions (FAQ).

Why This Matters

In programming, we often need to work with real numbers that have decimal points, like 3.14 or -2.718. Python provides the float() function for working with these floating point numbers. Understanding how to use float() correctly is essential for solving complex mathematical problems, handling data analysis tasks, and creating accurate simulations in your code.

Prerequisites

Before diving into the core concept of using Python's float(), you should have a basic understanding of:

  1. Variables and data types in Python
  2. Basic arithmetic operations (addition, subtraction, multiplication, division)
  3. String formatting with f-strings

Core Concept

The float() function is used to convert a number or string into a floating point number. Here are the key points to remember when using float():

  1. Syntax: float(number) or float(string)
  2. The number can be an integer, float, or string representing a real number.
  3. If you pass a string containing a real number to the function, Python will convert it into a floating point number. For example:
pi_str = "3.14"
pi = float(pi_str)
print(pi) # Output: 3.14
  1. If you pass an integer to the function, Python will convert it into a floating point number with the decimal point after the last digit. For example:
num = 123
num_float = float(num)
print(num_float) # Output: 123.0
  1. You can also use float() to convert a string containing an integer into a floating point number with a decimal point at the end, like this:
num_str = "123"
num_float = float(num_str)
print(num_float) # Output: 123.0
  1. When performing arithmetic operations with floating point numbers in Python, it is essential to understand that the results may not be exactly what you expect due to the way floating point numbers are stored internally. This can lead to common mistakes, which we will discuss later.

Worked Example

Let's work through a simple example of using float():

Define some variables as integers and strings representing real numbers

num1 = 7

num2_str = "3.14"

num3_str = "-2.718"

Convert the string variables to floating point numbers using float()

num2 = float(num2_str)

num3 = float(num3_str)

Perform some arithmetic operations with the floating point numbers

sum = num1 + num2 + num3

product = num1 num2 num3

Print the results using f-strings for formatting

print(f"The sum is: {sum}")

print(f"The product is: {product}")


When you run this code, you should see output similar to the following:

The sum is: 13.858

The product is: -274.9608

Common Mistakes

Mistake 1: Assuming exact results with floating point numbers

When working with floating point numbers, it's essential to understand that the results of arithmetic operations may not be exactly what you expect due to the way floating point numbers are stored internally. For example:

num1 = 0.1 + 0.2
print(num1) # Output: 0.30000000000000004

In this case, the sum of 0.1 and 0.2 is not exactly 0.3. This is due to the way floating point numbers are stored internally in binary format. To avoid confusion, it's best to use the round() function to round your results to a specific number of decimal places:

num1 = round(0.1 + 0.2, 4)
print(num1) # Output: 0.3

Mistake 2: Mixing integer and floating point numbers in arithmetic operations

When you perform arithmetic operations with a mix of integers and floating point numbers, Python will automatically convert the integer to a floating point number before performing the operation. This can lead to unexpected results if you're not careful:

num1 = 5
num2 = 0.3
sum = num1 + num2
print(sum) # Output: 5.3

In this case, the integer 5 is converted to a floating point number (5.0) before adding it to 0.3. To avoid confusion, it's best to ensure that all numbers involved in an arithmetic operation are either integers or floating point numbers:

num1 = 5.0
num2 = 0.3
sum = num1 + num2
print(sum) # Output: 5.3

Mistake 3: Using float() with a string containing an invalid real number

If you pass a string to float() that cannot be converted into a valid floating point number, Python will raise a ValueError. For example:

num_str = "not a number"
try:
num = float(num_str)
except ValueError as e:
print("Invalid real number:", e)

In this case, the code will output: Invalid real number: invalid literal for float() with base 10: 'not a number'. To avoid this error, ensure that the string you pass to float() contains a valid real number.

Practice Questions

  1. Write a Python script that calculates the area of a circle given its radius (in meters) as an integer input. Use float() to convert the radius to a floating point number before calculating the area.
  2. Modify the worked example to include another variable representing the constant e, which is approximately equal to 2.71828. Convert this constant from a string to a floating point number using float().
  3. Write a Python script that calculates the average of three test scores (as integers) and rounds the result to two decimal places using the round() function. Use float() to convert the test scores to floating point numbers before performing the calculation.
  4. Write a Python script that determines whether a given number is an integer or a floating point number by checking if its string representation contains a decimal point. If it does, use float() to convert the number to a floating point number; otherwise, leave it as an integer.

FAQ

Q1: Why do I see small differences when adding or subtracting floating point numbers?

A1: These differences are due to the way floating point numbers are stored internally in binary format. The binary representation of real numbers is not exact, so performing arithmetic operations with floating point numbers can result in slight discrepancies. To minimize these discrepancies, you can use the round() function to round your results to a specific number of decimal places.

Q2: Why do I get a ValueError when using float() with an invalid real number?

A2: The ValueError is raised by Python when it encounters a string that cannot be converted into a valid floating point number using the float() function. This can happen if the string contains non-numeric characters or if it represents an invalid real number, such as "not a number". To handle this error gracefully, you should use a try/except block to catch the ValueError and provide a meaningful error message.

Q3: Is there a limit to the number of decimal places that I can store in a floating point number using Python?

A3: Yes, there is a limit to the number of decimal places that you can store in a floating point number in Python. The limit depends on the size of the memory allocated for the floating point number (32-bit or 64-bit), but typically you can store around 15-17 significant digits accurately. To ensure accurate results, it's best to use the round() function to round your results to a specific number of decimal places before displaying them.

Python float() | Python | XQA Learn