Historical Context & Motivation
When you write a program, you are telling a computer how to manipulate data—numbers, words, true-or-false decisions, and more. But computers store everything as binary ones and zeros. How does the machine know that the bits 01000001 represent the letter "A" rather than the number 65? The answer is data types. A type tells Python what kind of value it is working with so it can choose the right operations, catch mistakes, and use memory efficiently.
Programming languages have adopted different strategies for handling types over the decades. Some languages, like C and Java, require you to declare a variable's type before you use it. Python takes a different approach: it uses dynamic typing, meaning the interpreter figures out the type at runtime based on the value you assign. This makes Python code concise and beginner-friendly, but it also means you need to understand how types behave under the hood.
int x = 5;, giving programmers fine-grained control over memory but increasing code verbosity.x = 5 and the interpreter infers that x is an integer automatically.bool as a distinct type with values True and False, making conditional logic more readable.int and long, made all strings Unicode by default, and solidified the four core types students learn today.Understanding the four core types—int, float, bool, and str—is the foundation for every Python program you will write. The central question of this lesson is: how do you choose the right type for your data, and what happens when you combine or convert between them?
Core Principles & Definitions
Python's type system rests on a few key ideas. Every value you create—whether it is the number 42, the decimal 3.14, the truth value True, or the greeting "Hello"—is an object that carries a type tag. That tag determines which operations are valid. You can add two integers, but you cannot add an integer and a string without converting one of them first.
int — Whole Numbers
7, -3, 0. In Python 3, integers can be arbitrarily large—there is no overflow limit.float — Decimal Numbers
3.14, -0.001, 2.0. They follow the IEEE 754 standard and have limited precision (~15–17 significant digits).bool — True or False
True and False. They are the backbone of if statements, loops, and logical operations.str — Text Strings
"hello" or 'world'. They support slicing, concatenation, and dozens of built-in methods like .upper().A crucial concept is type conversion (also called casting). Python sometimes converts types automatically—for instance, 3 + 2.5 promotes the integer 3 to the float 3.0 before adding. This is called implicit conversion. Other times you must convert explicitly, like writing int("42") to turn a string into an integer. That is explicit conversion.
Visual Explanation — The Four Core Types
type() on a sample value. Notice that bool is actually a subclass of int—a fact that surprises many beginners.The diagram above organizes the four types into a visual grid. On the left column you see the numeric and logical types (int and bool), and on the right you see float and str. You can always check a value's type by passing it to the built-in type() function. For example, type(3.14) returns <class 'float'>. This is your go-to debugging tool whenever you are unsure what type a variable holds.
How Types Work — Operations & Conversions
Each type supports a specific set of operations. Integers and floats support arithmetic: +, -, *, /, // (floor division), % (modulo), and ** (exponentiation). Booleans support logical operators: and, or, and not. Strings support concatenation (+), repetition (*), and indexing (s[0]).
Arithmetic Rules for int and float
/ operator always returns a float, even if both operands are integers. Use // for integer (floor) division.% returns the remainder after division. It is commonly used to check if a number is even (n % 2 == 0) or to wrap values around a range.bool → int → float. Strings are never implicitly converted to numbers—you must use int() or float() explicitly.Explicit Conversion (Casting) Functions
| Function | Example | Result |
|---|---|---|
int() | int("42") | 42 |
int() | int(3.9) | 3 (truncates, does not round) |
float() | float(7) | 7.0 |
str() | str(3.14) | "3.14" |
bool() | bool(0) | False (0, 0.0, "", and None are falsy) |
"Age: " + 17 causes a TypeError. Python refuses to guess whether you want "Age: 17" or something else. Fix it with "Age: " + str(17) or use an f-string: f"Age: {17}".Detailed Breakdown — Each Type Up Close
bool → int → float without your intervention. Dashed arrows show conversions to and from str that you must request explicitly using casting functions.int — Integers in Depth
Python integers have arbitrary precision, meaning they can grow as large as your computer's memory allows. In many other languages, an integer overflows after reaching a fixed limit (like 2³¹ − 1 in Java), but Python quietly allocates more memory as needed. You can write 2 ** 1000 and Python will compute the entire 302-digit result without error.
float — Floating-Point Numbers in Depth
Floats follow the IEEE 754 double-precision standard, which uses 64 bits to store a number. This gives about 15–17 significant decimal digits of precision. However, some simple decimals cannot be represented exactly in binary. For example, 0.1 + 0.2 evaluates to 0.30000000000000004 rather than 0.3. This is not a bug—it is an inherent limitation of floating-point arithmetic that affects virtually every programming language.
bool — Booleans in Depth
In Python, bool is technically a subclass of int. This means True behaves like 1 and False behaves like 0 in arithmetic contexts. Writing True + True gives 2, and sum([True, False, True, True]) gives 3—a handy trick for counting how many items satisfy a condition.
str — Strings in Depth
Strings in Python 3 are sequences of Unicode characters, which means they can represent text in any language—English, Japanese, Arabic, emoji, and more. Strings are immutable: once created, the characters inside cannot be changed. Operations like .upper() or .replace() return a new string rather than modifying the original. You can access individual characters by index ("Python"[0] gives "P") and extract substrings using slicing ("Python"[0:3] gives "Pyt").
Worked Example — Building a Temperature Converter
Let's build a small program that reads a temperature in Fahrenheit from the user, converts it to Celsius, and prints a formatted message. This exercise will require us to use all four core types: str (user input), float (the converted temperature), int (rounding), and bool (checking if water freezes).
input() function always returns a string, even if the user types a number. We store the raw input:
user_input = input("Enter temp in °F: ")
If the user types 72, then user_input is the string "72", not the number 72.user_input = "72" (type: str)fahrenheit = float(user_input)
Now fahrenheit holds the float value 72.0. We chose float instead of int because the user might enter a decimal like 98.6.fahrenheit = 72.0 (type: float)celsius = (fahrenheit - 32) * 5 / 9
Python evaluates (72.0 - 32) * 5 / 9 = 40.0 * 5 / 9 = 200.0 / 9 ≈ 22.222222222222221.celsius ≈ 22.222222222222221 (type: float)celsius_rounded = int(round(celsius))
The round() function returns 22 (an int when called with one argument and the result is whole), and int() ensures the type.celsius_rounded = 22 (type: int)is_freezing = celsius <= 0
Since 22.22 is not ≤ 0, is_freezing is False.is_freezing = False (type: bool)print(f"{fahrenheit}°F = {celsius_rounded}°C. Freezing? {is_freezing}")
Inside the curly braces, Python automatically calls str() on each value to embed it in the string.72.0°F = 22°C. Freezing? FalseStrengths & Pitfalls of Each Type
Each type excels in certain situations and can trip you up in others. The table below summarizes common strengths and pitfalls you should watch out for as you write Python programs.
| Type | Strengths | Common Pitfalls |
|---|---|---|
int | Exact arithmetic, unlimited size, great for counters, indices, and IDs | Division with / always returns a float; int(3.9) truncates to 3, not 4 |
float | Handles decimals and scientific notation, essential for math/science calculations | Rounding errors (0.1 + 0.2 ≠ 0.3); avoid using == to compare floats directly |
bool | Clean conditional logic, can count True values with sum() | Many values are "truthy" or "falsy" (e.g., 0, empty string, None are all False), which can cause unexpected behavior |
str | Rich built-in methods, Unicode support, f-string formatting | Immutable—cannot change characters in place; concatenating in a loop is slow for large data; "5" + "3" gives "53" not 8 |
int(), float(), str(), and bool() are the converters that reshape data so it fits where you need it.Connection to Advanced Concepts
The four core types you have learned are just the beginning. As you progress in Python, you will encounter collection types like list, dict, tuple, and set that group multiple values together. You will also meet type hints (introduced in Python 3.5), which let you annotate your code with expected types to catch bugs before your program even runs.
| Core Concept (This Lesson) | Advanced Extension |
|---|---|
int for whole numbers | decimal.Decimal for exact decimal arithmetic (e.g., financial applications) |
float for approximate decimals | complex type for complex numbers (3 + 4j) |
bool for True/False | Custom __bool__() method to define truthiness for your own classes |
str for text | bytes and bytearray for raw binary data, encoding, and network protocols |
| Dynamic typing (no declarations) | Type hints (x: int = 5) plus tools like mypy for static analysis |
Mastering int, float, bool, and str gives you a rock-solid foundation. Every data structure and every library you will use in the future ultimately stores and manipulates these primitive types. When you understand how they behave and how to convert between them, debugging becomes far easier and your code becomes more reliable.
Practice Problems
5 and the string "5" in Python? Why does 5 + 5 produce 10 while "5" + "5" produces "55"?10 / 3
(b) 10 // 3
(c) 10 % 3
(d) float(10)birth_year = input("Year born: "). Write Python code that calculates their age (assume the current year is 2025) and prints "You are X years old." Explain which type conversions are needed and why.4.99 and the quantity is 3. Write code that: (a) computes the total cost, (b) checks whether the customer gets a discount (total > $10), and (c) prints a receipt string like "Total: $14.97 | Discount: True". Identify the type of each variable.0.1 + 0.2 == 0.3 evaluates to False in Python. Then propose two different strategies a programmer could use to correctly compare floating-point numbers for near-equality. Discuss the trade-offs of each approach.Lesson Summary
Python provides four core data types that form the foundation of every program. The int type stores whole numbers with unlimited precision and supports arithmetic operations including floor division (//) and modulo (%). The float type handles decimal numbers using IEEE 754 double-precision but comes with inherent rounding limitations. The bool type represents True and False and is a subclass of int. The str type stores immutable sequences of Unicode characters.
Python uses dynamic typing, inferring types at runtime, and supports both implicit conversion (automatic widening from bool → int → float) and explicit conversion using casting functions like int(), float(), str(), and bool(). Use the type() function to check any value's type, and always remember that input() returns a string that must be explicitly converted before performing arithmetic.