Scrollable Nav Bar

Data Types in Python

Python’s built-in number types (like int and float) cover most everyday programming needs. But once you start working with different number bases (binary, hex, etc.) or require high-precision decimal arithmetic (especially for financial calculations), it helps to know a few extra tools.

In this tutorial, you’ll learn two important ideas:

  1. How to use the int class to convert strings from other bases into base-10 integers.
  2. How to use the decimal module to do precise decimal math and avoid common floating-point surprises.

1. Convert Strings to Integers

You already know that int() can convert a number-like string into an integer.

int("100")
Code language: JavaScript (javascript)

This converts the string "100" to the integer 100.

[ Output of int(“100”) in your notebook]

Why this matters

Data often comes in as text—user input, CSV files, JSON APIs, etc. Converting text to the right numeric type is a very common task.


2. Converting Numbers from Other Bases with int(value, base)

A less commonly used—but extremely handy—feature of int() is that it can convert a number written in another base into a base-10 integer.

The syntax looks like this:

int("100", 2)
Code language: JavaScript (javascript)

Here:

  • The first argument ("100") is the value, written as a string.
  • The second argument (2) tells Python that this string is written in base 2 (binary).

Binary 100 means:

  • 1 × 2² + 0 × 2¹ + 0 × 2⁰ = 4

So the result is:

int("100", 2)  # 4
Code language: PHP (php)

[: Output of int(“100”, 2)]

Common bases you’ll see

  • Base 2 (binary): digits 0–1
  • Base 8 (octal): digits 0–7
  • Base 10 (decimal): digits 0–9
  • Base 16 (hexadecimal): digits 0–9 and letters a–f

Try a few examples:

int("11", 2)      # 3
int("77", 8)      # 63
int("101", 10)    # 101
int("ff", 16)     # 255
Code language: PHP (php)

[: Multiple base conversion outputs]


3. Why the First Argument Must Be a String

You might wonder why this works:

int("100", 2)
Code language: JavaScript (javascript)

…but this does not:

int(100, 2)

The second version raises an error because the “base conversion” form of int() expects the number to be written as a string.

The real reason

When numbers are written in bases above 10 (like hex), they can contain letters, which cannot be represented as a normal integer literal.

For example, this is a valid hexadecimal number:

int("1ab", 16)
Code language: JavaScript (javascript)

Hex 1ab means:

  • 1 × 16² + a × 16¹ + b × 16⁰
  • a is 10, b is 11
  • 1×256 + 10×16 + 11 = 256 + 160 + 11 = 427

So:

int("1ab", 16)  # 427
Code language: PHP (php)

The value "1ab" is not an integer in Python syntax, but it is perfectly valid text for a base-16 number—so Python requires it to be a string.

[ Output of int(“1ab”, 16)]

What happens with invalid digits

If you pass characters that don’t belong to the specified base, Python raises a ValueError.

int("2", 2)  # invalid because base 2 allows only 0 or 1
Code language: PHP (php)

This is a good reminder: when converting user input, you should handle errors safely.


4. The Float Problem: Why 0.2 Sometimes Isn’t Exactly 0.2

Floating-point numbers (float) are fast and extremely useful, but they can produce results that look “wrong” if you expect perfect decimal arithmetic.

For example:

1.2 - 1.0
Code language: CSS (css)

You might expect 0.2, but you may see something like:

0.19999999999999996
Code language: CSS (css)

This happens because floats store numbers in binary internally, and some decimal fractions cannot be represented exactly in binary—similar to how 1/3 cannot be represented exactly in base 10.

[: Output of 1.2 – 1.0 showing floating-point precision issue]

For many applications, this is totally fine. But in some cases—especially when working with money or accounting-style arithmetic—this can become annoying or risky.


5. Using the decimal Module for Precise Decimal Arithmetic

Python includes a built-in module called decimal that provides decimal floating-point arithmetic with configurable precision.

Step 1: Import Decimal and getcontext

It’s standard practice to keep imports near the top of your file or notebook.

from decimal import Decimal, getcontext
Code language: JavaScript (javascript)
  • Decimal is the number type you will use.
  • getcontext() gives you a context object that controls global settings such as precision.

[ Import statement at the top of the notebook]

Step 2: Explore the current context

getcontext()

You’ll get a context object with several settings. The key one for now is prec (precision).

[ Printed Decimal context]


6. Controlling Precision with getcontext().prec

You can change the number of significant digits used in Decimal operations.

getcontext().prec = 4

Now try a calculation like 1 / 3 using Decimal:

Decimal(1) / Decimal(3)

With precision set to 4, you’ll see something like:

0.3333
Code language: CSS (css)

Change precision to 2:

getcontext().prec = 2
Decimal(1) / Decimal(3)

Now the output becomes:

0.33
Code language: CSS (css)

What you’re seeing is rounded output based on the current context precision.

[ Same division shown at different precisions]

Tip: getcontext() is a global setting (within your process). If you change it, it affects subsequent Decimal operations.


7. A Big Rule: Prefer Strings When Creating Decimal Values

A common mistake is to create a Decimal from a float:

Decimal(3.14)
Code language: CSS (css)

This can produce a long-looking decimal value. That isn’t a bug in decimal—it’s actually showing you what the float really contains internally.

This is one of the clearest demonstrations of why floating-point “errors” show up: the float 3.14 is not stored exactly as 3.14.

The better approach

Create Decimal values from strings:

Decimal("3.14")
Code language: JavaScript (javascript)

Now you get a clean decimal value that matches what you intended.

[ Decimal(3.14) vs Decimal(“3.14”) output comparison]

In real projects, this is especially important for currency-like data, where you care about precise decimal representation.


8. Should You Always Use Decimal Instead of float?

Not necessarily.

Floats are fast, widely supported, and (for most practical programming tasks) accurate enough. In many applications, you can keep floats and simply round appropriately before displaying values to users.

For example:

round(1.2 - 1.0, 2)
Code language: CSS (css)

This produces a user-friendly value for display.

That said, you should consider using Decimal when:

  • You’re dealing with money, invoices, taxes, or balances.
  • You need predictable decimal rounding behavior.
  • You’re doing calculations where small rounding differences could accumulate and cause problems.

Even when using Decimal, you should still think carefully about rounding rules—especially before showing results to end users.


9. Quick Practice: Try These in Your Notebook

A. Base conversions

  1. Convert binary "1010" to base 10.
  2. Convert hex "2f" to base 10.
  3. Convert octal "20" to base 10.

B. Decimal precision

  1. Set precision to 6 and compute Decimal(1) / Decimal(7).
  2. Set precision to 3 and compute the same division.
  3. Compare Decimal(0.1) vs Decimal("0.1").

[ Your solutions and outputs]


Summary

You now have two powerful tools for “other types of numbers” in Python:

  • int("value", base) lets you convert strings written in bases like binary (2) or hex (16) into normal integers.
  • The decimal module provides the Decimal type, which can help you avoid floating-point surprises and work with controlled precision—especially useful for currency or precise decimal math.

In the next lessons, you’ll see how these number types fit into larger programs, and when each is the best choice.