Beginner

Basic Data Types in Python

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.

Understanding Python's Core Data Types

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:

What is an 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.

What is a 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.

What is a 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.

What is a 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?).

What is 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.

How do these work?

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.

The Container Analogy

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.

Visual Mental Model

DATA TYPE LANDSCAPE ═══════════════════════════════════════════════════════════════ NUMBERS TEXT LOGIC ABSENCE ├─────────┬──────────┐ ┌────────┐ ┌─────────┐ ┌──────┐ │ │ │ │ │ │ │ │ │ int float │ str │ bool │ None │ │ │ │ │ │ │ │ │ │ 42 3.14 │ "Hello!" │ True │ (empty)│ -7 0.99 │ "Python" │ False │ │ 0 -2.5 │ "123" │ │ │ 1000 6.022e23 │ │ │ │ │ │ │ │ │ │ │ │ │ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ Math Math Math Text Text Yes/No Yes/No Placeholder ops ops ops ops ops decisions checks "not set yet" (+,-,*,/) (+,-,*,/) (.upper(), (==,!=) (if/else) .lower()) TYPE CHECKING: type(variable) → reveals the container shape

💡 Key Insight: The arrows at the bottom show what you can DO with each type. The type determines which operations are valid!

Code Examples

Example 1: Basic Type Assignment

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'>

Example 2: Type Differences in Action

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

Example 3: Practical Type Conversion

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

Example 4: User Input Processing Pattern

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")

Hands-On Exercise: Create Your Personal Profile

Goal: Create a Python program that stores different types of information about yourself and demonstrates understanding of data types.

Step 1: Setup

  1. Open your text editor or IDE
  2. Create a new file called my_profile.py
  3. Save it in a folder where you can easily find it (like Desktop/python-practice/)

Step 2: Write the Starter Code

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.

Step 3: Add Your Profile Data

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

Step 4: Display and Inspect Your Data

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)}")

Step 5: Add Type Conversions

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)})")

Step 6: Run Your Program

  1. Save your file (Ctrl+S or Cmd+S)
  2. Open your terminal/command prompt
  3. Navigate to the folder: cd Desktop/python-practice/
  4. Run: python my_profile.py

Step 7: Expected Output

You 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:

Common Mistakes to Avoid

Mistake 1: String Numbers vs. Actual Numbers

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.

Mistake 2: Forgetting Python 3 Division Behavior

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.

Mistake 3: Lowercase true and false

Problem:

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).

Mistake 4: Treating None Like Zero

Problem:

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:

Mistake 5: Mixing Types in Concatenation

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.

Mistake 6: Invalid Type Conversions

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!

Mini-Project: BMI Calculator with Health Categories

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

Requirements Checklist

Complete Starter Code

# 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)

Expected Output

========================================
   BMI CALCULATOR
========================================

Please enter your measurements:
Weight (kg): 70
Height (m): 1.75

========================================
   RESULTS
========================================
Your BMI: 22.86
Category: Normal weight
========================================

Testing Your Project

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

Bonus Challenges 🌟

  1. Add Input Validation:
    • Check if the user entered valid numbers
    • Handle errors gracefully if they enter text instead of numbers
    • Hint: Use try/except (we'll learn this later, but you can look it up!)
  2. Imperial Units Support:
    • Ask the user if they want to use pounds and feet/inches
    • Convert imperial to metric before calculating
    • Formula: weight_kg = weight_lbs / 2.205, height_m = height_inches * 0.0254
  3. Health Advice:
    • Add personalized messages for each category
    • Example: "Great! You're in the healthy range. Keep it up!"
    • Store different messages in variables (strings!)

Summary

Key Takeaways ✅

What Makes Data Types Special 🌟

  1. They're the foundation of everything: Every variable, every function return value, every piece of data has a type. Understanding types means understanding how Python thinks.
  2. They prevent errors: Python's type system catches mistakes early. If you try to divide text, Python stops you with an error instead of giving you garbage results.
  3. They're automatic but controllable: Python figures out types for you (dynamic typing), but you can always convert them when needed. It's the best of both worlds!

📚 Level Up Your Python Learning

Master Python faster with interactive courses and structured practice

🎯

DataCamp - Interactive Python Courses

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:

  • Learn by doing—write code in every lesson (not just watching videos)
  • Instant feedback on your code with smart hints
  • Bite-sized lessons (3-4 min each) perfect for busy schedules
  • 300+ Python exercises from basics to data science
Start Free Trial →
🎓

Udemy Python Complete Courses

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:

  • "100 Days of Code: Python Pro" - 60+ hours, 4.7★ rating
  • "Complete Python Bootcamp" - Build 10+ real projects
  • "Python for Data Science" - Learn NumPy, Pandas, Matplotlib
  • 30-day money-back guarantee on all courses
Browse Python Courses →

💡 These resources complement our free tutorials with structured practice and expert guidance—but you can absolutely master Python without them!

Your Next Steps 📋

🎯 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! 🚀

🎯 Test Your Knowledge: Data Types in Python

Check your understanding of Python's basic data types

1. Which of the following is a float in Python?

42
3.14
"3.14"
True

2. What is the result of: type("Hello")?

<class 'int'>
<class 'str'>
<class 'float'>
<class 'bool'>

3. Which value represents "nothing" or "no value" in Python?

0
False
None
""

4. What happens when you add an integer and a float: 10 + 3.5?

Python throws an error
Result is 13.5 (a float)
Result is 13 (an integer)
Result is "103.5" (a string)

5. Which of these is NOT a boolean value in Python?

True
False
"True"
Both True and False are boolean
← Previous: Variables Next: Operators →