Concepts / Converting Between Data Types: An Overview

Converting Between Data Types: An Overview

A value can be represented in more than one data type.

  • Programming
Interactive lab

Try it: Type conversion: int(), float(), str(), bool()

Exactly how int(), int(text, base), float(), str() and bool() turn a value into another type: Python's real parsing rules for text (whitespace, sign, underscores, 0x/0o/0b prefixes, inf/nan, exponents) and its truthiness rules.

How it works

  1. int(text) strips surrounding whitespace, allows one sign, then reads digits (underscores only between digits); any other character raises ValueError: invalid literal for int().
  2. int(text, base) reads digits in that base; base 0 takes the base from a 0x / 0o / 0b prefix like a Python literal.
  3. float(text) accepts decimals like '.5', '5.', '1e3' and the names inf, infinity and nan, then rounds to the nearest double.
  4. int() of a float truncates toward zero; str() gives the printed form (repr digits for floats).
  5. bool() is truthiness: '', 0, 0.0 and None are False; every non-empty string — even '0' or 'False' — is True.

Default run (8 steps): int(' -0x_1F ', 0): the argument is a str of 10 characters. … int(' -0x_1F ', 0) → -31

Simplified: The argument is a Python literal typed as text (ASCII only; escapes \t \n \r). Unicode digits and bytes arguments are not modelled.

Educational simulation

Loading the simulation…

From Whole Numbers to Decimal Form

A value can be represented in more than one data type. The float() conversion changes an integer or a numeric string into a floating-point number. When an integer has no decimal representation, float() adds one to the representation while preserving the number's quantity.

python
Output
7.0
7integerfloat()conversion7.0floating-point numberinputreturns
What changes when the integer 7 passes into float()?

Tracing Numeric Strings

User input commonly arrives as a string, even when the user typed a number. float() can convert a string representation of a number into a floating-point number. For example, the numeric string "3.14" becomes the floating-point value 3.14. The important condition is that the string must represent a valid number.

Worked example

Converting a Numeric String

Convert the numeric string "3.14" into a floating-point number.

  1. 1
    Start with the string

    The input is a string representation of a number rather than a numeric value already stored as a number.

  2. 2
    Apply float()

    float() reads the valid numeric string and converts it to floating-point form.

  3. 3
    Read the result

    The resulting numeric value is represented as 3.14.

Result

float("3.14") produces 3.14 as a floating-point number.

python
Output
3.14
"3.14"numeric stringfloat()conversion3.14floating-point numbervalid numeric textreturns
What value and type come out when a valid numeric string passes through float()?

float() and int() Compared

The key difference is what happens to a fractional part. float() preserves fractional values and returns a true floating-point type. int(), by contrast, truncates a value when converting it to an integer. Therefore, choosing between the two conversions depends on whether the fractional part must remain available.

ConversionBehavior with a fractional valueResulting form
float()Preserves the fractional valueFloating-point number
int()Truncates the fractional valueInteger

The source's central distinction between float() and int() conversion behavior.

3.14numeric valuefloat()preserves fractionint()truncates fraction3.14floating-point number3integersame valuepreservessame valuetruncates
How do float() and int() handle the same numeric value when it contains a decimal part?

Predicting Conversion Results

What do you think happens?

What happens when float() receives each of these inputs?

  • float(7) returns 7.0

  • float("3.14") returns 3.14

  • float("not a number") returns a floating-point value

  • All three inputs produce the same result

Reveal answer
Answer:

float(7) returns 7.0. float("3.14") returns 3.14. float("not a number") raises a ValueError because the string does not represent a valid number.

Integers and valid numeric strings can be converted to floating-point numbers. An input string that is not a valid number cannot be converted by float().

7integer7.0floating-point number"3.14"numeric string3.14floating-point number"not a number"invalid numeric stringValueErrorconversion failsfloat()float()float()
Given an integer, a numeric string, or an invalid string, what does float() return or do next?

Mistakes Beginners Make

  • Common mistake

    Assuming float() removes the fractional part.

    What it looks like

    A value with a fractional part is passed to float().

    Why it fails

    float() preserves fractional values.

    Do this instead

    Use float() when the fractional part must remain available. int() is the conversion described as truncating.

  • Common mistake

    Treating every string as convertible.

    What it looks like
    float("not a number")
    Why it fails

    The string does not represent a valid number, so float() raises a ValueError.

    Do this instead

    Provide a string representation of a valid number before using float().

  • Common mistake

    Forgetting that float() changes the data type.

    What it looks like

    float(7) is considered the same type as the original integer.

    Why it fails

    float() returns a true floating-point type.

    Do this instead

    Remember that 7 becomes the floating-point representation 7.0.

Choosing the Conversion

Use float() when a calculation needs values in floating-point form or when a numeric value arrives as a string and its fractional part should be preserved. This is especially useful when handling user input represented as strings. Use int() instead when the intended behavior is truncation and an integer result is required.

EASY

For each input, predict the result of float(): float(12), float("8.5"), and float("eight"). Then identify which input causes a ValueError.

Hints
  • An integer is converted to floating-point form with decimal representation.
  • A valid numeric string can be converted.
  • A string that does not represent a valid number causes a ValueError.

Key Takeaways

  1. 1
    float() converts integers and valid numeric strings to floating-point numbers.
  2. 2
    Converting an integer adds decimal representation, such as 7 becoming 7.0.
  3. 3
    float() preserves fractional values, while int() truncates them.
  4. 4
    An invalid numeric string causes float() to raise a ValueError.
  5. 5
    float() is useful for converting string-based user input and for ensuring values are in floating-point form for calculations.

At a glance

  • float() converts integers and numeric strings into floating-point numbers.
  • An integer such as 7 is represented as 7.0 after conversion.
  • float() preserves fractional values, unlike int(), which truncates them.
  • Invalid numeric strings cause float() to raise a ValueError.

Related concepts

More concepts starting with C