Browse Python Topics ▼
Pick a Web Framework

Data Types

📂 Variables & Data Types 📘 Lesson 7 of 57

Explore Python's fundamental data types—int, float, str, bool, and None—and learn how Python combines dynamic typing with strict type safety.

In variables, you learned that variables are named sticky notes pointing to objects in memory. But what kinds of objects can you actually store?

In the physical world, different materials have different properties: you can pour liquids into glasses, slice bread, and hammer nails. You cannot slice water, and you cannot pour bread.

The same rule applies to computer programming. A data type defines what kind of value an object represents and what operators and operations can legally be performed on it. You can add two numbers together, but you cannot subtract a sentence from a person’s name.


The Four Core Primitive Data Types

Python comes with four fundamental scalar types that form the foundation of almost every program:

Data TypePython ClassWhat It RepresentsExamples
IntegerintWhole numbers (positive, negative, or zero)42, -15, 0, 1_000_000
Floating-PointfloatReal numbers with decimal points3.14159, -0.001, 2.0, 1.5e3
StringstrTextual data and sequences of characters"Hello", 'Python 3', ""
BooleanboolLogical truth values (True or False)True, False

Let’s examine how each of these behaves in practice.


1. Integers (int)

An integer is a whole number without any fractional or decimal component:

player_score = 350
temperature_celsius = -5
zero_balance = 0

Arbitrary Precision: No Integer Overflow

In languages like C, C++, or Java, integers are constrained by hardware limits (such as 32-bit or 64-bit bounds). If a number exceeds $2,147,483,647$, it overflows into negative numbers and crashes software.

Python integers have arbitrary precision. A Python int can grow as large as your computer’s RAM permits:

# Calculating 2 to the power of 100
huge_number = 2 ** 100
print(huge_number)
# Output: 1267650600228229401496703205376

Readability: Visual Digit Separators

When working with large numbers, you can insert underscores _ as thousands separators. Python ignores underscores during execution:

# Clean and readable:
annual_revenue = 1_500_000_000  # Exactly 1.5 billion

2. Floating-Point Numbers (float)

A floating-point number represents a decimal value or real number:

pi = 3.14159
item_price = 19.99
fractional_rate = 0.05

Note: Even if a number has a decimal value of zero (like 5.0), Python considers it a float, not an int.

Scientific Notation

For extremely large or tiny scientific numbers, use the e (or E) notation:

speed_of_light = 3.0e8   # 3.0 * 10^8 = 300,000,000.0
electron_charge = 1.6e-19

The Floating-Point Precision Quirk

Computers store numbers using binary transistors (base 2). Certain base-10 decimals (like $0.1$ or $0.2$) cannot be represented with infinite precision in binary, just like $1/3$ ($0.3333…$) cannot be represented precisely in decimal:

print(0.1 + 0.2)
# Output: 0.30000000000000004

This is not a Python bug—it is an intrinsic property of IEEE 754 computer hardware arithmetic across every programming language. When comparing floats in conditions, round them or check for close proximity.


3. Strings (str)

Strings represent text and are enclosed in either single quotes (') or double quotes ("):

greeting = "Welcome to Engineering!"
file_path = 'src/app.py'
empty_string = ""

You will explore comprehensive text manipulation, slicing, and methods in strings.


4. Booleans (bool)

A boolean holds one of only two possible logical values: True or False:

is_server_online = True
has_admin_rights = False

Booleans are the bedrock of decision-making and flow control. In Python, bool is actually a specialized subclass of int:

  • True has an internal numeric value of 1.
  • False has an internal numeric value of 0.

5. The Special Value: None (NoneType)

Python includes a unique keyword named None. It represents the intentional absence of a value or an unassigned state (similar to null in JavaScript or Java):

user_profile_photo = None

if user_profile_photo is None:
    print("Using default placeholder avatar.")

None is frequently used as a default argument in functions or to mark that an operation did not return a result.


Inspecting Types: type() vs. isinstance()

Python provides two built-in tools to inspect what data type an object has:

1. type(object)

Returns the raw class of the object:

print(type(42))       # <class 'int'>
print(type(3.14))     # <class 'float'>
print(type("Hello"))  # <class 'str'>
print(type(True))     # <class 'bool'>
print(type(None))     # <class 'NoneType'>

Checks whether an object matches a given type (or a tuple of types), returning True or False. This is the preferred professional pattern because it cleanly supports inheritance:

user_input = 42

if isinstance(user_input, int):
    print("Valid integer received.")

# Check multiple types at once:
if isinstance(user_input, (int, float)):
    print("Value is a valid number.")

Dynamic Typing vs. Strong Typing

Many beginners conflate dynamic typing with weak typing. Python is:

  1. Dynamically Typed: Variables are not permanently bound to a type. A name can point to an integer now and a string later.
  2. Strongly Typed: Python strictly enforces type boundaries. It will never guess or silently convert incompatible types during operations.

Compare Python to a weakly typed language like JavaScript:

// JavaScript (Weakly Typed):
"Total: " + 50    // Evaluates to "Total: 50" (Silently converts number to text)
"10" - 2          // Evaluates to 8 (Silently converts text to number)

In Python, attempting to add text to a number is strictly forbidden:

# Python (Strongly Typed):
print("Total: " + 50)
# Crashes with: TypeError: can only concatenate str (not "int") to str

This strictness is a major asset: it catches mistakes immediately rather than allowing corrupted data to silently propagate through your database. To combine text and numbers in Python, you explicitly perform type-casting or use formatted strings.


Primitive vs. Composite Types

Scalar types (int, float, str, bool) represent single atomic pieces of data. As your programs grow, you will group multiple values together using composite data structures:

  • lists: Ordered, mutable collections ([1, 2, 3]).
  • tuples: Ordered, immutable records ((10, 20)).
  • dicts: Key-value lookup tables ({"name": "Elena", "age": 28}).
  • sets: Unordered collections of unique items ({1, 2, 3}).

Summary Checklist

  • int: Whole numbers with unlimited size.
  • float: Decimals and real numbers.
  • str: Text data enclosed in single or double quotes.
  • bool: Truth values (True or False).
  • None: Represents the deliberate absence of a value.
  • Strong Typing: Python strictly enforces type safety and refuses to silently mix incompatible types.
  • isinstance(): The idiomatic way to verify an object’s type.

Now that you know how values are classified, continue to operators to learn how to calculate, compare, and manipulate these values mathematically and logically.

Test your understanding of Data Types

Quick interactive practice questions with instant feedback.

Take Quiz →