Skip to content

Python Variables and Data Types: Int, Float, Str, Bool, None

  • How variable assignment works in Python and what “dynamic typing” really means.
  • The core scalar types: int with arbitrary precision, float as IEEE 754, bool as a subclass of int, the immutable str, and None.
  • Why money should never be a float, and how decimal.Decimal fixes that.
  • How to inspect a value’s type with type() and check it with isinstance().
  • The truthiness rules that control if and while, and the empty values that count as false.

Variables and types are the foundation every later page builds on. Python’s type system is dynamic, so a name can refer to any type, but the objects themselves have fixed types and well-defined behavior. This tutorial covers the types you will use constantly in an OrdersPortal order-management system, with a verification step after each one so you can confirm the behavior on your own machine.

  • Python 3.9 or later. Run python --version to confirm the version.
  • Save examples as types_demo.py and run python types_demo.py. Every complete sample prints its output.
  • No prior Python knowledge is required; this is the first substantive page in the basics sequence.

One idea to hold onto throughout: in Python, variables are names that refer to objects, and the type lives on the object, not the name. The next step makes that concrete.

Step 1 — Assign variables and see dynamic typing

Section titled “Step 1 — Assign variables and see dynamic typing”

Assignment binds a name to an object with =. Because Python is dynamically typed, you can rebind the same name to an object of a completely different type, which a statically typed language would reject.

x = 42 # x refers to an int
print(type(x))
x = "Acme" # now refers to a str — perfectly valid
print(type(x))
# <class 'int'>
# <class 'str'>

The name x has no type of its own; only the objects it points to do. Rebinding changes which object the name refers to, not any property of the name. This is why Python lets the same variable hold different types over its lifetime.

Verify: assign x = 42 then x = "Acme" and print type(x) after each. The class changes from int to str, confirming the name carries no type.

Step 2 — Use int with arbitrary precision

Section titled “Step 2 — Use int with arbitrary precision”

Python’s int has unlimited precision. There is no overflow at a fixed width; an integer grows as large as the memory allows, which removes a whole class of bugs that plague fixed-width integers in other languages.

big = 10 ** 40
print(big)
# 100000000000000000000000000000000000000000
print(2 ** 64) # no overflow, unlike a 64-bit int
# 18446744073709551616

Because of this, you can compute factorial of large numbers, sum totals that span many orders of magnitude, and shift bits without worrying about wraparound. The cost is that very large integers are slower and use more memory, but correctness never depends on a hidden bit limit.

Verify: compute 10 ** 40 and confirm you see all forty digits, not scientific notation or a wrapped-around value. Try 2 ** 1000 to see a 302-digit integer print in full.

Step 3 — Use float and learn why money is different

Section titled “Step 3 — Use float and learn why money is different”

A float is a double-precision IEEE 754 binary fraction. It cannot represent most decimal numbers exactly, so arithmetic on money produces small errors that compound across thousands of orders. For money, use decimal.Decimal instead.

total = 0.1 + 0.1 + 0.1
print(total)
# 0.30000000000000004 <- binary float surprise
from decimal import Decimal
money = Decimal("0.10") + Decimal("0.10") + Decimal("0.10")
print(money)
# 0.30 <- exact decimal
print(money == Decimal("0.30"))
# True

The 0.1 + 0.1 + 0.1 example is the classic illustration: the binary float is just barely not 0.3, so a naive equality check fails. Decimal constructed from a string preserves the decimal value exactly, which is why it is the right type for currency, tax rates, and anything where a penny must be a penny.

Verify: run the float sum and see the trailing 00000000000000004. Then run the Decimal sum and confirm it equals Decimal("0.30") exactly. Never construct Decimal from a float like Decimal(0.1), which imports the float’s error.

Step 4 — Treat bool as a subclass of int

Section titled “Step 4 — Treat bool as a subclass of int”

bool has two values, True and False, and it is a subclass of int where True is 1 and False is 0. This means a bool works anywhere an int works, which is occasionally useful and occasionally a source of surprises.

print(True + True) # 2 — bools add like ints
print(isinstance(True, int)) # True — bool IS an int
flags = [True, False, True]
print(sum(flags)) # 2 — count of True values

The subclass relationship lets you count True values with sum, since each True contributes 1. It also means True == 1 and False == 0, so be careful not to mix booleans into arithmetic where you meant real numbers.

Verify: print True == 1 and False == 0, both True. Then print isinstance(False, int) to confirm the subclass relationship.

A str is an immutable sequence of Unicode code points. Immutability means any operation that seems to modify a string actually returns a new one, which is safe to share and hash. Strings are covered fully in the strings tutorial, so this step only notes the type-level facts.

name = "OrdersPortal"
print(type(name)) # <class 'str'>
print(name[0]) # 'O' — indexing returns a one-char string, not a char type
# name[0] = "o" # TypeError: strings are immutable
upper_name = name.upper()
print(name, upper_name) # OrdersPortal ORDERSPORTAL — original unchanged

There is no separate character type in Python; a single character is just a string of length one. Immutability is what makes strings usable as dictionary keys, and it is why you rebind the result of a method rather than expecting it to change the original.

Verify: try name[0] = "o" and confirm the TypeError. Then print name again to confirm it was not changed by the attempted assignment.

Step 6 — Use None to mean “no value”

Section titled “Step 6 — Use None to mean “no value””

None is the singleton that represents the absence of a value. Functions with no return statement return None. The correct way to test for it is is None, not == None, because is checks identity and is faster and clearer.

status = None
if status is None:
print("no status set yet")
# no status set yet
def log(message):
print(message) # returns None implicitly
result = log("order placed")
print(result is None)
# True

None is falsy, so if not status is True when status is None, but that test also passes for empty strings, zero, and empty lists. Use is None when you specifically mean “the value is absent,” and reserve truthiness tests for “is there something here.”

Verify: call log("hi") and print the result; confirm it is None. Then compare status == None and status is None; both are True here, but is None is the form recommended by the style guide.

Step 7 — Inspect types with type() and isinstance()

Section titled “Step 7 — Inspect types with type() and isinstance()”

type() returns the exact class of an object. isinstance() checks whether an object belongs to a class or any of its subclasses, which is usually what you want because it respects inheritance.

value = 42
print(type(value)) # <class 'int'>
print(isinstance(value, int)) # True
print(isinstance(value, bool)) # False — an int is not a bool
flag = True
print(isinstance(flag, int)) # True — a bool IS an int

The asymmetry matters: an int is not a bool, but a bool is an int, because bool is the subclass. isinstance honors that relationship, so isinstance(True, int) is True. Prefer isinstance over type(x) is int in your own code; it handles subclasses and reads as intent.

Verify: run the four checks above and confirm the asymmetric results. Try isinstance(value, (int, float)) to see that isinstance accepts a tuple of types.

Every object is either truthy or falsy, and the rules decide how if, while, and and/or treat it. The falsy values are: None, False, any numeric zero (0, 0.0, 0j), and any empty collection ("", [], {}, set()).

falsy = [None, False, 0, 0.0, "", [], {}, set()]
for v in falsy:
print(bool(v), end=" ")
print()
# False False False False False False False False
# the and/or operators return a value, not a bool
print("Acme" or "default") # 'Acme' — first truthy value
print(None or "default") # 'default' — falls through to the second

The or trick returns the first truthy operand or the last operand if all are falsy, which is a common way to supply a default: customer = customer or "Guest". Just remember it returns ""-as-falsy too, so for strings you sometimes want an explicit if customer is None.

Verify: run the loop to confirm every falsy value prints False. Then print 0 or "fallback" to see the default behavior in action.

This script models an OrdersPortal order with every core type and demonstrates the money pitfall plus the right fix. It is runnable on Python 3.9 and later.

from decimal import Decimal
def summarize(order_id, customer, amount, paid, discount_code):
print(f"order id type : {type(order_id).__name__}")
print(f"customer type : {type(customer).__name__}")
print(f"amount type : {type(amount).__name__}")
print(f"paid type : {type(paid).__name__} (is int: {isinstance(paid, int)})")
if discount_code is None:
print("no discount")
else:
print(f"discount: {discount_code}")
# truthiness: count truthy flags
flags = [paid, bool(customer), discount_code is not None]
print(f"truthy flags : {sum(flags)}")
# float-based money accumulates error
float_total = 0.0
for _ in range(3):
float_total += 0.10
print(f"float total : {float_total}")
# Decimal money is exact
dec_total = Decimal("0.00")
for _ in range(3):
dec_total += Decimal("0.10")
print(f"Decimal total : {dec_total}")
summarize(1023, "Acme", dec_total, True, None)

Expected output:

float total : 0.30000000000000004
Decimal total : 0.30
order id type : int
customer type : str
amount type : Decimal
paid type : bool (is int: True)
no discount
truthy flags : 2

The output shows the float error next to the exact Decimal, and confirms that paid is a bool that isinstance reports as an int. The truthy-flags count is 2 because discount_code is None, so the third flag is False.

Real error messages and their fixes, drawn from the mistakes that surface when you work with Python’s core types.

  • TypeError: 'str' object does not support item assignment — you tried to mutate a string. Strings are immutable; build a new one with a method like replace or slicing.
  • TypeError: unsupported operand type(s) for +: 'Decimal' and 'float' — you mixed a Decimal with a float. Convert both to Decimal first; never let a float touch a money calculation.
  • TypeError: 'NoneType' object is not subscriptable — you indexed into a None, usually because a function returned None and you expected a list. Check the function’s return path.
  • Decimal(0.1) gives a long, wrong value — you built a Decimal from a float, importing the float’s error. Always build money Decimals from strings: Decimal("0.10").
  • Storing money as a float. Binary floats cannot represent most decimal currency exactly, and the errors add up across an order book. Use Decimal for any money value.
  • Comparing floats with ==. Two floats that should be equal often differ by a tiny amount. Compare with a tolerance, or use Decimal for exact comparisons.
  • Testing None with == instead of is. is None checks identity, which is faster and immune to classes that override __eq__. The style guide recommends is.
  • Forgetting bool is an int. True + True is 2, and sum([True, False, True]) is 2. Useful for counting, but a trap if you expected real numbers.
  • Assuming a falsy value is None. An empty string, zero, and an empty list are all falsy but are not None. Use is None when absence is what you mean.
  • Using type(x) is int instead of isinstance. The type check rejects subclasses; isinstance honors them. Use isinstance unless you specifically need an exact class match.