Python Variables and Data Types: Int, Float, Str, Bool, None
What you’ll learn
Section titled “What you’ll learn”- How variable assignment works in Python and what “dynamic typing” really means.
- The core scalar types:
intwith arbitrary precision,floatas IEEE 754,boolas a subclass ofint, the immutablestr, andNone. - Why money should never be a
float, and howdecimal.Decimalfixes that. - How to inspect a value’s type with
type()and check it withisinstance(). - The truthiness rules that control
ifandwhile, 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.
Prerequisites
Section titled “Prerequisites”- Python 3.9 or later. Run
python --versionto confirm the version. - Save examples as
types_demo.pyand runpython 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 intprint(type(x))x = "Acme" # now refers to a str — perfectly validprint(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 ** 40print(big)# 100000000000000000000000000000000000000000print(2 ** 64) # no overflow, unlike a 64-bit int# 18446744073709551616Because 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.1print(total)# 0.30000000000000004 <- binary float surprise
from decimal import Decimalmoney = Decimal("0.10") + Decimal("0.10") + Decimal("0.10")print(money)# 0.30 <- exact decimalprint(money == Decimal("0.30"))# TrueThe 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 intsprint(isinstance(True, int)) # True — bool IS an intflags = [True, False, True]print(sum(flags)) # 2 — count of True valuesThe 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.
Step 5 — Treat str as immutable Unicode
Section titled “Step 5 — Treat str as immutable Unicode”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 immutableupper_name = name.upper()print(name, upper_name) # OrdersPortal ORDERSPORTAL — original unchangedThere 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)# TrueNone 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 = 42print(type(value)) # <class 'int'>print(isinstance(value, int)) # Trueprint(isinstance(value, bool)) # False — an int is not a bool
flag = Trueprint(isinstance(flag, int)) # True — a bool IS an intThe 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.
Step 8 — Learn the truthiness rules
Section titled “Step 8 — Learn the truthiness rules”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 boolprint("Acme" or "default") # 'Acme' — first truthy valueprint(None or "default") # 'default' — falls through to the secondThe 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.
Complete working example
Section titled “Complete working example”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 errorfloat_total = 0.0for _ in range(3): float_total += 0.10print(f"float total : {float_total}")
# Decimal money is exactdec_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.30000000000000004Decimal total : 0.30order id type : intcustomer type : stramount type : Decimalpaid type : bool (is int: True)no discounttruthy flags : 2The 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.
Troubleshooting
Section titled “Troubleshooting”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 likereplaceor slicing.TypeError: unsupported operand type(s) for +: 'Decimal' and 'float'— you mixed aDecimalwith afloat. Convert both toDecimalfirst; never let a float touch a money calculation.TypeError: 'NoneType' object is not subscriptable— you indexed into aNone, usually because a function returnedNoneand you expected a list. Check the function’s return path.Decimal(0.1)gives a long, wrong value — you built aDecimalfrom a float, importing the float’s error. Always build money Decimals from strings:Decimal("0.10").
Common mistakes
Section titled “Common mistakes”- Storing money as a
float. Binary floats cannot represent most decimal currency exactly, and the errors add up across an order book. UseDecimalfor any money value. - Comparing floats with
==. Two floats that should be equal often differ by a tiny amount. Compare with a tolerance, or useDecimalfor exact comparisons. - Testing
Nonewith==instead ofis.is Nonechecks identity, which is faster and immune to classes that override__eq__. The style guide recommendsis. - Forgetting
boolis anint.True + Trueis2, andsum([True, False, True])is2. 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 notNone. Useis Nonewhen absence is what you mean. - Using
type(x) is intinstead ofisinstance. Thetypecheck rejects subclasses;isinstancehonors them. Useisinstanceunless you specifically need an exact class match.
Next steps
Section titled “Next steps”- Combine these types into sequences with Strings and Lists.
- Express the types of these values in code with Type Hints.
- Group related values with Tuples and Dictionaries.
- For exact money arithmetic beyond this page, read the Python
decimalmodule docs.
Official references
Section titled “Official references”- Python 3 — Built-in Types — int, float, bool, str, and None at a glance.
- Python 3 —
decimalmodule — exact decimal arithmetic for money. - Python 3 — Truth Value Testing — the complete truthiness rules.
- Python 3 — Numeric Types — int, float, and their operations.