Data Types
Core built-in types: numbers, strings, booleans, and type checking
Overview
Python provides rich built-in types for numbers, text, and logic. Understanding types helps you choose the right structure and avoid subtle bugs when converting or comparing values.
Syntax / Usage
# Numbers
integer = 42
floating = 3.14
complex_num = 2 + 3j
# Strings
message = "Hello"
multiline = """Line one
Line two"""
# Boolean
is_valid = True
is_empty = False
# Type inspection
type(42) # <class 'int'>
isinstance(3.14, float) # True
# Conversion
int("10") # 10
str(42) # "42"
float("3.5") # 3.5
bool(0) # False
bool("text") # True (non-empty strings are truthy)
Examples
Validate and convert user age from a string:
raw_age = "25"
if raw_age.isdigit():
age = int(raw_age)
print(f"You are {age} years old.")
else:
print("Invalid age.")
Format a price with two decimal places:
price = 19.5
label = f"${price:.2f}" # "$19.50"
Common Mistakes
- Comparing floats with
==instead of using tolerance (math.isclose) - Concatenating strings and numbers without
str()conversion - Confusing
is(identity) with==(equality) for small integers vs objects - Treating empty collections as
Falseinifwithout realizing0is also falsy
See Also
python-variables python-list-comprehension python-dictionaries