Master Python's core data types and learn when to use each one
Imagine you're organizing a party. You need to track the number of guests (a whole number), split the bill down to cents (a decimal), store everyone's names (text), check who's confirmed (yes or no), and mark spots for people who haven't responded yet (nothing).
Data types are how Python understands what kind of information you're working with. Just like you wouldn't measure someone's height in dollars or count guests using fractions, Python needs to know whether you're dealing with numbers, text, or true/false values. This matters because different types of data can do different things—you can add numbers together, but you can't multiply words (well, not in the way you'd think!).
If you've ever filled out a form online, you've already encountered data types: number fields only accept digits, text boxes accept letters, and checkboxes are either checked or unchecked. Python uses the same logic.
Data types are categories that tell Python what kind of value you're storing and what operations you can perform with it. Python has five core built-in data types that you'll use constantly:
int (integer)?An integer is a whole number without any decimal point. It can be positive, negative, or zero. Examples: 42, -7, 0, 1000. You use integers when counting things that can't be divided into pieces—like the number of students in a class or items in your shopping cart.
float (floating-point number)?A float is a number with a decimal point. Examples: 3.14, -0.5, 2.0, 99.99. "Floating-point" refers to how computers store these numbers internally (the decimal point can "float" to different positions). You use floats for measurements, prices, or anything requiring precision beyond whole numbers.
str (string)?A string is text—any sequence of characters wrapped in quotes. Examples: "hello", 'Python', "42" (yes, numbers in quotes become text!). The name "string" comes from imagining characters strung together like beads on a necklace. You use strings for names, messages, addresses, or any textual information.
bool (boolean)?A boolean is a true/false value—it only has two options: True or False (capitalized in Python). Named after mathematician George Boole, booleans answer yes/no questions. You use them for conditions, flags, or tracking status (Is the user logged in? Did the payment succeed?).
None?None represents the absence of a value—it's Python's way of saying "nothing here." Unlike zero (which is a number) or an empty string (which is still text), None means "no data exists." You use it as a placeholder or to indicate that something hasn't been set yet.
Each data type has different capabilities. You can perform math operations on int and float, but not on str. You can capitalize a str, but not a bool. Unlike languages like C or Java, Python is "dynamically typed"—you don't have to declare types in advance. Python figures out the type automatically based on the value you assign.
Data types are like container shapes at a drink station.
Imagine a buffet with different beverage containers: coffee mugs, wine glasses, water bottles, shot glasses, and empty coasters. Each container is designed for a specific type of drink:
If you try to pour hot soup into a wine glass (wrong type), you'll make a mess. Similarly, if you try to do math with text ("5" + "3"), Python will "concatenate" (stick them together) to get "53" instead of adding to get 8. Using the right type for the right job prevents errors and makes your code work as intended.
💡 Key Insight: The arrows at the bottom show what you can DO with each type. The type determines which operations are valid!
Let's create one variable of each type and see what Python thinks they are:
# Creating one variable of each type
age = 25 # int: whole number
price = 19.99 # float: decimal number
name = "Alice" # str: text in quotes
is_student = True # bool: True or False (capitalized!)
middle_name = None # None: no value assigned
# Let's see what Python thinks these are
print(type(age)) # Output: <class 'int'>
print(type(price)) # Output: <class 'float'>
print(type(name)) # Output: <class 'str'>
print(type(is_student)) # Output: <class 'bool'>
print(type(middle_name)) # Output: <class 'NoneType'>
Output:
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>
<class 'NoneType'>
Watch what happens when the same-looking values have different types:
# Same-looking values, different types!
num_as_int = 5 # This is a number
num_as_str = "5" # This is text that looks like a number
num_as_float = 5.0 # This is a decimal number
# Watch what happens with addition
print(num_as_int + 3) # Math addition: 5 + 3 = 8
print(num_as_str + "3") # Text concatenation: "5" + "3" = "53"
print(num_as_float + 3) # Math with mixed types: 5.0 + 3 = 8.0
# Booleans have surprising numeric values!
print(True + 5) # True acts like 1: 1 + 5 = 6
print(False + 10) # False acts like 0: 0 + 10 = 10
# None is special—you can't do math with it
result = None
print(result) # Output: None
Output:
8
53
8.0
6
10
None
Converting between types (also called "type casting") is essential when working with user input:
# Converting between types (type casting)
user_input = "42" # Comes in as a string from input()
age = int(user_input) # Convert string to integer
print(f"Next year you'll be {age + 1}") # Now we can do math!
# Converting integers to floats for precision
miles = 26 # Whole number
kilometers = float(miles) * 1.60934 # Convert to float for decimal math
print(f"{miles} miles = {kilometers:.2f} km") # .2f means 2 decimal places
# Converting numbers to strings for display
score = 95
percentage = 87.5
report = "Score: " + str(score) + ", Percentage: " + str(percentage) + "%"
print(report)
# Checking if conversion is safe before doing it
maybe_number = "123"
if maybe_number.isdigit(): # Check if string contains only digits
number = int(maybe_number)
print(f"Successfully converted: {number}")
Output:
Next year you'll be 43
26 miles = 41.84 km
Score: 95, Percentage: 87.5%
Successfully converted: 123
This is a real-world pattern you'll use constantly:
# Real-world pattern: processing user data
print("=== Student Registration ===")
# Everything from input() comes as a string!
student_name = input("Enter name: ") # str
age_str = input("Enter age: ") # str (even though it's a number!)
gpa_str = input("Enter GPA: ") # str
is_fulltime = input("Full-time? (yes/no): ") # str
# Convert to appropriate types for processing
age = int(age_str) # Convert to int for comparison
gpa = float(gpa_str) # Convert to float for precision
full_time = (is_fulltime.lower() == "yes") # Convert to bool
# Now we can work with the data properly
print(f"\n--- Student Profile ---")
print(f"Name: {student_name} ({type(student_name).__name__})")
print(f"Age: {age} ({type(age).__name__})")
print(f"GPA: {gpa} ({type(gpa).__name__})")
print(f"Full-time: {full_time} ({type(full_time).__name__})")
# Demonstrate type-appropriate operations
if age >= 18:
print("✓ Eligible for adult courses")
if gpa > 3.5:
print("✓ Qualifies for honors program")
Goal: Create a Python program that stores different types of information about yourself and demonstrates understanding of data types.
my_profile.pyDesktop/python-practice/)Type this exact code into your file:
# My Personal Profile - Data Types Practice
# Created by: [Your Name]
print("=== CREATING MY PROFILE ===\n")
# TODO: Create variables for each data type below
💡 What you're doing: Setting up the structure with a header comment and print statement. Comments (lines starting with #) are notes for humans—Python ignores them.
Below your TODO comment, add these variables with YOUR information:
# Personal information (strings)
full_name = "Your Name Here" # Replace with your actual name
favorite_quote = "Your favorite quote" # Replace with a quote you like
# Numbers about you (integers and floats)
age = 25 # Replace with your age (int)
height_meters = 1.75 # Replace with your height (float)
favorite_number = 7 # Replace with your favorite number (int)
# True/False facts about you (booleans)
loves_python = True # Do you love Python? True or False
is_morning_person = False # Are you a morning person? True or False
# Optional information (None if not applicable)
nickname = None # Add your nickname as a string, or leave as None
Add this code to see your data and check the types:
# Display your profile
print("📋 MY PROFILE DATA:")
print(f"Name: {full_name}")
print(f"Quote: '{favorite_quote}'")
print(f"Age: {age} years old")
print(f"Height: {height_meters}m")
print(f"Favorite Number: {favorite_number}")
print(f"Loves Python: {loves_python}")
print(f"Morning Person: {is_morning_person}")
print(f"Nickname: {nickname}")
# Check the data types
print("\n🔍 DATA TYPE ANALYSIS:")
print(f"full_name is a: {type(full_name)}")
print(f"age is a: {type(age)}")
print(f"height_meters is a: {type(height_meters)}")
print(f"loves_python is a: {type(loves_python)}")
print(f"nickname is a: {type(nickname)}")
Add this code to practice converting between types:
# Type conversion practice
print("\n🔄 TYPE CONVERSIONS:")
age_as_string = str(age)
print(f"Age as string: '{age_as_string}' (type: {type(age_as_string)})")
height_in_cm = int(height_meters * 100)
print(f"Height in cm: {height_in_cm}cm (type: {type(height_in_cm)})")
favorite_as_float = float(favorite_number)
print(f"Favorite number as float: {favorite_as_float} (type: {type(favorite_as_float)})")
Ctrl+S or Cmd+S)cd Desktop/python-practice/python my_profile.pyYou should see something like this (with your data):
=== CREATING MY PROFILE ===
📋 MY PROFILE DATA:
Name: Alex Johnson
Quote: 'The only way to do great work is to love what you do.'
Age: 28 years old
Height: 1.75m
Favorite Number: 7
Loves Python: True
Morning Person: False
Nickname: None
🔍 DATA TYPE ANALYSIS:
full_name is a: <class 'str'>
age is a: <class 'int'>
height_meters is a: <class 'float'>
loves_python is a: <class 'bool'>
nickname is a: <class 'NoneType'>
🔄 TYPE CONVERSIONS:
Age as string: '28' (type: <class 'str'>)
Height in cm: 175cm (type: <class 'int'>)
Favorite number as float: 7.0 (type: <class 'float'>)
⚠️ Troubleshooting Tips:
True and False are capitalized25 not "25"Problem:
age = "25" # This is a string!
next_year = age + 1 # TypeError: can only concatenate str to str
Why it happens: When you put quotes around a number, Python treats it as text, not a number. You can't add 1 to text.
Solution:
age = 25 # No quotes = integer
next_year = age + 1 # Works! Result: 26
✅ Prevention tip: Only use quotes for actual text. If you'll do math with it, don't use quotes.
Problem:
result = 5 / 2
print(result) # Expecting 2, but get 2.5
Why it happens: In Python 3, the / operator ALWAYS returns a float (decimal), even when dividing integers.
Solution:
# For decimal division (default)
result = 5 / 2 # Returns 2.5 (float)
# For integer division (floor division)
result = 5 // 2 # Returns 2 (int, rounds down)
✅ Prevention tip: Use // when you want whole number division. Use / when you want precise division.
true and falseProblem:
is_valid = true # NameError: name 'true' is not defined
Why it happens: In Python, booleans MUST be capitalized: True and False. Other languages use lowercase, which causes confusion.
Solution:
is_valid = True # Capital T
is_complete = False # Capital F
✅ Prevention tip: Think of True and False as proper names (like "Python" itself).
None Like ZeroProblem:
value = None
total = value + 10 # TypeError: unsupported operand type(s) for +
Why it happens: None isn't zero—it's "nothing at all." You can't do math with nothing.
Solution:
value = None
# Check before using
if value is None:
value = 0 # Set a default if None
total = value + 10 # Now it works: 0 + 10 = 10
✅ Prevention tip: Always check if a variable is None before using it. Use if value is None:
Problem:
age = 25
message = "I am " + age + " years old" # TypeError
Why it happens: The + operator with strings means "stick together," but you can't stick text and numbers together directly.
Solution:
age = 25
# Option 1: Convert to string
message = "I am " + str(age) + " years old"
# Option 2: Use f-strings (modern and preferred!)
message = f"I am {age} years old"
# Option 3: Use commas in print
print("I am", age, "years old")
✅ Prevention tip: Get comfortable with f-strings (f"text {variable}"). They're the easiest way to mix text and variables.
Problem:
text = "hello"
number = int(text) # ValueError: invalid literal for int()
Why it happens: Not all conversions are possible. You can't turn random text into a number—the text must look like a number!
Solution:
# This works - text looks like a number
text = "42"
number = int(text) # Success: 42
# Check first if conversion is safe
text = "hello"
if text.isdigit():
number = int(text)
else:
print("Can't convert to number")
✅ Prevention tip: Before converting strings to numbers, use .isdigit() to check first!
Goal: Build a Body Mass Index calculator that takes user input, performs type conversions, does calculations with floats, and uses different data types appropriately.
💡 What you'll practice: Taking user input (strings), converting to floats, performing calculations, using booleans for comparisons, and displaying formatted output
Time estimate: 15-30 minutes
weight / (height ** 2)# BMI Calculator - Mini Project
# Practices: user input, type conversion, float math, conditionals
print("=" * 40)
print(" BMI CALCULATOR")
print("=" * 40)
print()
# Get user input
print("Please enter your measurements:")
weight_str = input("Weight (kg): ")
height_str = input("Height (m): ")
# Convert to floats
weight = float(weight_str)
height = float(height_str)
# Calculate BMI
bmi = weight / (height ** 2)
bmi_rounded = round(bmi, 2)
# Determine category
if bmi < 18.5:
category = "Underweight"
elif bmi < 25:
category = "Normal weight"
elif bmi < 30:
category = "Overweight"
else:
category = "Obese"
# Display results
print("\n" + "=" * 40)
print(" RESULTS")
print("=" * 40)
print(f"Your BMI: {bmi_rounded}")
print(f"Category: {category}")
print("=" * 40)
========================================
BMI CALCULATOR
========================================
Please enter your measurements:
Weight (kg): 70
Height (m): 1.75
========================================
RESULTS
========================================
Your BMI: 22.86
Category: Normal weight
========================================
Test with these values to verify it works correctly:
| Weight (kg) | Height (m) | Expected BMI | Expected Category |
|---|---|---|---|
| 70 | 1.75 | 22.86 | Normal weight |
| 50 | 1.75 | 16.33 | Underweight |
| 90 | 1.75 | 29.39 | Overweight |
| 100 | 1.75 | 32.65 | Obese |
weight_kg = weight_lbs / 2.205, height_m = height_inches * 0.0254int (whole numbers), float (decimals), str (text), bool (True/False), and None (absence of value)type(variable) to see what type Python thinks something isint(), float(), str(), and bool() to convert between typesinput(), you always get a string back—convert it if you need to do math!Master Python faster with interactive courses and structured practice
Price: $25/month (free trial available) | Perfect for: Hands-on learners who want instant feedback
Learn Python through interactive exercises with instant feedback. Type code directly in your browser, get hints when stuck, and track your progress with skill assessments.
What makes DataCamp great:
Price: ₹499 (on sale from ₹3,499) | Perfect for: Comprehensive video-based learning with projects
One-time payment for lifetime access to complete Python courses. Learn from industry experts with 20-40 hours of video content, downloadable resources, and certificate of completion.
Top-rated courses include:
💡 These resources complement our free tutorials with structured practice and expert guidance—but you can absolutely master Python without them!
type() on different values to build intuitionint + str? Learn from errors!🎯 Closing Motivation: You've just learned the alphabet of programming! Just like how 26 letters combine to create every English word, these five data types combine to create every Python program ever written. From Instagram to Spotify to NASA's spacecraft software—they all start with int, float, str, bool, and None.
The difference between a beginner and an expert isn't that experts use different types—they just get really good at choosing the right type for the right job. You're now equipped with that same foundation. Every line of code you write from now on will use these types, and you'll get faster and more confident with every program.
Don't just read this tutorial—type out the examples, break things on purpose, and build the mini-project. That's where the real learning happens. Your fingers need to remember this stuff, not just your eyes.
Next up: You'll learn operators—the verbs that let your data types actually do things. Addition, comparison, logic—that's where your code comes alive. But you needed to understand the nouns (data types) first, and now you do.
Keep coding! 🚀
Check your understanding of Python's basic data types
1. Which of the following is a float in Python?
2. What is the result of: type("Hello")?
3. Which value represents "nothing" or "no value" in Python?
4. What happens when you add an integer and a float: 10 + 3.5?
5. Which of these is NOT a boolean value in Python?