Python Data Types
Python has several built-in data types that are the building blocks of any program. Every value in Python has a data type, and Python automatically assigns the type based on the value.
Overview of Data Types
| Category | Types | Example |
|---|---|---|
| Numeric | int, float, complex | 42, 3.14, 2+3j |
| Text | str | "hello" |
| Boolean | bool | True, False |
| Sequence | list, tuple, range | [1,2], (1,2), range(5) |
| Mapping | dict | {"a": 1} |
| Set | set, frozenset | {1, 2, 3} |
| Binary | bytes, bytearray, memoryview | b"hello" |
| None | NoneType | None |
Numeric Types
Integers (int)
Whole numbers with no size limit:
python
x = 42
y = -100
big = 999_999_999_999 # Underscores for readability
print(type(x)) # <class 'int'>
# Different number bases
binary = 0b1010 # Binary: 10
octal = 0o17 # Octal: 15
hexadecimal = 0xFF # Hexadecimal: 255
print(binary, octal, hexadecimal) # 10 15 255Floats (float)
Decimal numbers (64-bit double precision):
python
pi = 3.14159
negative = -0.001
scientific = 2.5e4 # 25000.0
print(type(pi)) # <class 'float'>
# Float precision issues
print(0.1 + 0.2) # 0.30000000000000004
print(0.1 + 0.2 == 0.3) # False!
# Use round() or decimal module for precision
print(round(0.1 + 0.2, 1) == 0.3) # True
# Special float values
import math
print(float('inf')) # inf
print(float('-inf')) # -inf
print(math.isnan(float('nan'))) # TrueComplex Numbers (complex)
Numbers with real and imaginary parts:
python
z = 3 + 4j
print(z.real) # 3.0
print(z.imag) # 4.0
print(abs(z)) # 5.0 (magnitude)
print(type(z)) # <class 'complex'>
# Complex arithmetic
z1 = 2 + 3j
z2 = 1 - 1j
print(z1 + z2) # (3+2j)
print(z1 * z2) # (5+1j)Strings (str)
Text data enclosed in quotes:
python
single = 'Hello'
double = "World"
multi = """This is a
multi-line string"""
# String length
print(len("Python")) # 6
# Indexing and slicing
text = "Python"
print(text[0]) # P
print(text[-1]) # n
print(text[0:3]) # Pyt
print(text[::2]) # Pto (every 2nd char)
print(text[::-1]) # nohtyP (reversed)String Methods
python
text = " Hello, World! "
print(text.strip()) # "Hello, World!"
print(text.lower()) # " hello, world! "
print(text.upper()) # " HELLO, WORLD! "
print(text.replace("World", "Python")) # " Hello, Python! "
print(text.split(",")) # [' Hello', ' World! ']
print(text.strip().startswith("Hello")) # True
print(text.strip().endswith("!")) # True
print("world" in text.lower()) # TrueString Formatting
python
name = "Alice"
age = 30
# f-strings (recommended - Python 3.6+)
print(f"{name} is {age} years old")
# f-string expressions
print(f"Next year: {age + 1}")
print(f"Name uppercase: {name.upper()}")
print(f"Price: ${19.99:.2f}")
print(f"{'centered':^20}") # " centered "
# .format() method
print("{} is {} years old".format(name, age))
print("{0} likes {1}. {0} is {2}.".format(name, "Python", age))
# % operator (old style)
print("%s is %d years old" % (name, age))Escape Characters
| Escape | Description | Example |
|---|---|---|
\n | Newline | "line1\nline2" |
\t | Tab | "col1\tcol2" |
\\ | Backslash | "C:\\path" |
\' | Single quote | 'it\'s' |
\" | Double quote | "say \"hi\"" |
python
# Raw strings (ignore escape characters)
path = r"C:\Users\name\documents"
print(path) # C:\Users\name\documentsBooleans (bool)
Boolean values are True or False:
python
is_active = True
is_deleted = False
print(type(is_active)) # <class 'bool'>
# Booleans are subclass of int
print(True + True) # 2
print(True * 10) # 10
print(False + 1) # 1Truthy and Falsy Values
python
# Falsy values (evaluate to False)
print(bool(0)) # False
print(bool(0.0)) # False
print(bool("")) # False
print(bool([])) # False
print(bool({})) # False
print(bool(None)) # False
# Truthy values (evaluate to True)
print(bool(1)) # True
print(bool(-1)) # True
print(bool("text")) # True
print(bool([1, 2])) # True
print(bool({"a":1})) # TrueComparison and Logical Operators
python
# Comparisons return booleans
print(10 > 5) # True
print(10 == 10) # True
print(10 != 5) # True
# Logical operators
print(True and False) # False
print(True or False) # True
print(not True) # False
# Chained comparisons
x = 15
print(10 < x < 20) # True (same as 10 < x and x < 20)None Type
None represents the absence of a value:
python
result = None
print(result) # None
print(type(result)) # <class 'NoneType'>
# Check for None using 'is'
if result is None:
print("No value assigned")
# Common use: default function parameters
def greet(name=None):
if name is None:
print("Hello, stranger!")
else:
print(f"Hello, {name}!")
greet() # Hello, stranger!
greet("Alice") # Hello, Alice!
# Functions without return statement return None
def do_something():
pass
print(do_something()) # NoneType Checking and Conversion
python
# Check type
x = 42
print(type(x)) # <class 'int'>
print(isinstance(x, int)) # True
print(isinstance(x, (int, float))) # True (check multiple types)
# Convert between types
print(int("42")) # 42
print(float("3.14")) # 3.14
print(str(42)) # "42"
print(list("abc")) # ['a', 'b', 'c']
print(tuple([1,2,3])) # (1, 2, 3)
print(set([1,1,2,3])) # {1, 2, 3}
print(bool(42)) # TruePractical Example
python
"""
A simple data type explorer program.
"""
def analyze_value(value):
"""Analyze and describe a value's type and properties."""
print(f"Value: {value!r}")
print(f"Type: {type(value).__name__}")
print(f"Bool: {bool(value)}")
print(f"String: '{str(value)}'")
if isinstance(value, (int, float)):
print(f"Positive: {value > 0}")
print(f"Even: {value % 2 == 0}" if isinstance(value, int) else "")
elif isinstance(value, str):
print(f"Length: {len(value)}")
print(f"Alpha: {value.isalpha()}")
print(f"Digit: {value.isdigit()}")
print("-" * 30)
# Test with different types
test_values = [42, 3.14, "Hello", "", True, None, 0]
for val in test_values:
analyze_value(val)Summary
- Python has numeric (
int,float,complex), text (str), boolean (bool), and None types - Integers have unlimited precision; floats have precision limitations
- Strings are immutable sequences of characters with powerful built-in methods
- Use f-strings for string formatting (modern and readable)
- Values are truthy or falsy β
0,"",[],Noneare falsy - Use
type()andisinstance()for type checking - Use
int(),float(),str(),bool()for type conversions
Next, we'll learn about Python operators and how to perform operations on data.