Concepts / Converting Between Data Types

Converting Between Data Types

The important distinction is between a numeric value that has a decimal portion and a string whose characters contain a decimal point: int() can handle the former, but a decimal string must use an additional conversion step.

  • 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…

A Decimal Does Not Get Rounded

Suppose a program receives the value 7.9 but needs an integer. The int() function does not choose the nearest integer. Instead, it removes the decimal portion completely. That means 7.9 becomes 7, even though 8 is the nearer rounded value. This single rule explains many results that surprise beginners.

What do you think happens?

What integer does int() produce for 3.99999?

  • 3

  • 4

  • An error in every case

Reveal answer
Answer:

3

int() truncates by removing the decimal part. It does not round according to the size of the decimal portion.

Following the Decimal Portion

Truncation means chopping off the decimal part rather than changing the whole-number part according to a rounding rule. The decimal portion is removed regardless of how large it is. Therefore, 7.1 and 7.9 both become 7, and 3.99999 also becomes 3. For a negative value such as -7.9, removing the decimal portion leaves -7.

7.9decimal value7integer result7.1decimal value7integer result-7.9decimal value-7integer resultint() removes .9int() removes .1int() removes .9
What happens to the decimal portion when int() converts positive and negative decimal values?
Worked example

Tracing Three Decimal Values

Determine the result of applying int() to 7.9, 7.1, and -7.9.

  1. 1
    Process 7.9

    Remove the decimal portion .9. The result is 7.

  2. 2
    Process 7.1

    Remove the decimal portion .1. The result is 7.

  3. 3
    Process -7.9

    Remove the decimal portion .9 while keeping the whole-number part -7. The result is -7.

Result

The results are 7, 7, and -7. None of these conversions rounds to a nearby integer.

Accepted and Rejected Inputs

The int() function works with floating-point values and with strings that represent whole numbers. It raises an error for strings that contain a decimal portion, such as a decimal string, and it also raises an error for invalid input. The important distinction is between a numeric value that has a decimal portion and a string whose characters contain a decimal point: int() can handle the former, but a decimal string must use an additional conversion step.

7.9float value7integer result'7'whole-number string7integer result'3.14'decimal stringerrorint() failsinvalid inputnot a supported valueerrorint() failsint() truncatesint() convertsdecimal stringinvalid input
Which input values successfully become integers, and which inputs cause int() to raise an error?
Input categoryint() behavior
Float valueConverts it to an integer by truncating the decimal portion
Whole-number stringConverts it to an integer
Decimal stringRaises an error
Invalid inputRaises an error

The input's form matters: a float and a decimal string do not follow the same direct int() path.

The Two-Step Decimal String Path

A decimal string such as '3.14' cannot be passed directly to int(). The source-prescribed solution is to convert the string to a floating-point value first and then convert that result to an integer: int(float('3.14')). The first conversion makes the decimal value available to the second conversion; int() then removes the decimal portion and produces 3.

python
Output
3
'3.14'decimal string3.14float value3integer resultfloat()int() truncates
How does a decimal string move through float() and int() to become an integer?

Comparing Conversion Roles

int(), float(), and str() should not be treated as interchangeable names. In the supplied material, int() is the operation that produces an integer, float() is used as the intermediate step that turns the decimal string '3.14' into a value int() can process, and str() is identified as a separate conversion function. The source pack does not provide a detailed rule for the exact result of str(), so the reliable rule for this lesson is to focus on int()'s integer result and float()'s role in the two-step decimal-string conversion.

int()produces an integerintegerint() resultfloat()intermediate step for'3.14'3.14value passed onward toint()str()separate conversionfunctionstring conversionexact output rule notspecified hereconverts tocreates intermediate valueseparate role
How do int(), float(), and str() differ in the conversion roles covered by this lesson?

Mistakes to Avoid

  • Common mistake

    Assuming int() rounds to the nearest integer

    What it looks like
    Treating int(3.99999) as 4
    Why it fails

    int() removes the decimal portion instead of rounding it.

    Do this instead

    Apply truncation: 3.99999 becomes 3.

  • Common mistake

    Expecting a decimal string to work directly

    What it looks like
    Passing '3.14' directly to int()
    Why it fails

    The source states that int() raises an error for decimal strings.

    Do this instead

    Convert the string to a float first, then pass that result to int().

  • Common mistake

    Treating a float and a decimal string as the same input

    What it looks like

    Assuming 3.14 and '3.14' follow the same direct conversion path

    Why it fails

    One is a floating-point value and the other is a string containing decimal characters.

    Do this instead

    Use int() directly for the float, but use int(float('3.14')) for the decimal string.

  • Common mistake

    Ignoring invalid input

    What it looks like

    Assuming every value can be converted by int()

    Why it fails

    Invalid input causes int() to raise an error.

    Do this instead

    Check whether the input is a supported float or whole-number string before relying on conversion.

Check Your Prediction

MEDIUM

For each input, predict whether int() produces an integer or raises an error. If it produces an integer, state the result: 7.1, 3.99999, '7', and '3.14'. Then explain why the last input requires a different path.

Hints
  • For a floating-point value, remove the decimal portion rather than rounding.
  • A whole-number string is supported by int().
  • A decimal string must first be converted with float().
  1. 1
    Use int() when the desired result is an integer. Remember that it truncates by removing the decimal portion, so 7.9 becomes 7 and 3.99999 becomes 3. It works with floats and whole-number strings, but decimal strings and invalid input raise an error. To process a decimal string such as '3.14', convert it to a float first and then apply int().

Key Takeaways

  • int() converts values to integers by truncating rather than rounding.
  • The decimal portion is removed completely, regardless of its size.
  • Floats and whole-number strings can be converted directly, while decimal strings and invalid input raise an error.
  • A decimal string can be converted with int(float('3.14')).
  • float() can serve as the intermediate step for a decimal string, while str() is a separate conversion function.

Related concepts

More concepts starting with C