Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes

Python Variables & Data Types

Master Python variables and built-in data types (int, float, string, bool) with clear examples and a practical exercise. Understand dynamic typing, common pitfalls, and when to use each data type — perfect for step-by-step learners.

Focus: python variables and data types

Sponsored

Ever tried to write a Python script only to get a cryptic TypeError because you thought a piece of data was a number but it was actually text? Or spent an hour debugging a bug caused by mixing up a string and an integer? That confusion stems from one of the most fundamental concepts in programming: understanding variables and data types. Think of variables as labeled boxes that hold your data, and data types as the rules for what can go in each box. By mastering this, you'll write cleaner, more predictable code and finally break free from those frustrating runtime errors.

The problem this lesson solves

When you start coding, your first instinct is to just "store stuff" and move on. But Python's dynamic typing means a variable can hold any type of data, and it can even change type mid-program. That flexibility is powerful, but it also leads to:

  • Unpredictable bugs: You accidentally add a string to a number and get an error or unexpected concatenation.
  • Hard-to-read code: Without clear data types, you can't tell if price is a string like "19.99" or a float like 19.99.
  • Broken assumptions: You thought a function returned a list, but it returned None, and your loop crashes.
  • Wasted debugging time: You chase the wrong error because you misidentified what kind of data you're working with.

This lesson solves that problem by giving you a systematic mental model for how Python variables and data types actually work. You'll learn to spot the difference between int, float, str, and bool, and use that knowledge to write code that behaves exactly as you expect.

Core concept / mental model

Think of a variable as a sticky note with a name written on it. That sticky note is attached to a value (the data). Python doesn't care what that value is — it just follows the sticky note to find the data. But the data itself has a type that determines:

  • What operations you can perform (e.g., you can divide a number but not a string).
  • How much memory it uses.
  • How it behaves in expressions.

The four built-in types you'll use 90% of the time

Type Example Use case
int 42, -5, 0 Whole numbers, ages, counts
float 3.14, 2.0, -0.001 Decimals, measurements, prices
str "hello", 'Python', "" Text, names, messages, file names
bool True, False Conditions, flags, toggles

💡 Pro tip: In Python, even True and False are actually integers under the hood! True == 1 and False == 0. This is useful but can lead to subtle bugs if you're not careful.

Dynamic typing — the superpower and the trap

Python is dynamically typed: a variable can hold any type, and the type can change as you run the program.

define x = 10        # x is an int
x = "ten"           # now x is a str – Python doesn't complain
x = [1, 2, 3]       # now x is a list – still fine

This is different from languages like Java or C++, where you must declare the type upfront and it never changes. While dynamic typing gives you flexibility, it also means you must track what type a variable is at every point in your program.

How it works step by step

When you assign a value to a variable, Python does three things:

  1. Creates an object: An internal Python object (the actual data) is created in memory. That object knows its own type.
  2. Creates a reference: Python creates a name (the variable) that points to that object.
  3. Attaches the name: The variable name is added to the current namespace. You can then use the name to access the object.

Step-by-step: tracing variable assignment

# Step 1: Create an int object with value 42
age = 42

# Step 2: age now references that int object
print(age)   # Output: 42
print(type(age))  # Output: <class 'int'>

# Step 3: Assign a new value – now age references a different object (a str)
age = "forty-two"
print(age)   # Output: forty-two
print(type(age))  # Output: <class 'str'>

⚠️ Important: age didn't change from int to str. The name age now points to a different object. The old 42 object still exists (unless garbage collected). This is a classic point of confusion for beginners.

Type checking with type()

Use the built-in type() function to ask Python what type a variable is at any moment:

price = 19.99
print(type(price))   # <class 'float'>

name = "Laptop"
print(type(name))    # <class 'str'>

in_stock = True
print(type(in_stock)) # <class 'bool'>

Hands-on walkthrough

Let's build a small program that demonstrates all four basic types and shows how to avoid common mixing bugs.

Exercise: Build a product info system

We'll create variables for a product, then try to combine them into a description.

# --- Product data ---
product_name = "Wireless Mouse"      # str
price = 29.99                        # float
quantity = 3                         # int
in_stock = True                      # bool

# --- Problem: mixing types in a string ---
description = "Product: " + product_name + " | Price: $" + price
print(description)  # ❌ TypeError! Can't concatenate str and float

Fix: Convert non-string values to strings with str() before combining.

description = "Product: " + product_name + " | Price: $" + str(price) + " | Qty: " + str(quantity)
print(description)  # ✅ Output: Product: Wireless Mouse | Price: $29.99 | Qty: 3

Better approach: Use f-strings (Python 3.6+) – they handle type conversion automatically.

description = f"Product: {product_name} | Price: ${price} | Qty: {quantity}"
print(description)  # ✅ Clean, no manual str() needed

Working with booleans in arithmetic

Booleans can be used in math – but beware of unintended behavior.

# Boolean arithmetic (works but can confuse)
result = True + False + True   # 1 + 0 + 1
print(result)  # Output: 2

# Common pitfall: checking if a number is even
number = 3
is_even = (number % 2 == 0)
print(is_even)  # Output: False (a bool)
print(is_even + 5)  # Output: 5 (because False == 0)

💡 Pro tip: If you ever see True or False in a numerical calculation, it's probably a bug in your logic.

Compare options / when to choose what

Situation Use int Use float Use str Use bool
Whole counts (people, items, index) ✅ Yes ❌ No ❌ No ❌ No
Monetary values, measurements ❌ No ✅ Yes ❌ No ❌ No
Text, labels, user input ❌ No ❌ No ✅ Yes ❌ No
Flags, on/off states ❌ No ❌ No ❌ No ✅ Yes
Mixed types for display ❌ Convert with str() ❌ Convert with str() ✅ Centerpiece ❌ Convert with str()

When to choose what: - Always prefer int for whole numbers – they are exact and faster. - Use float only when you need fractional values – but be aware of floating-point precision issues (e.g., 0.1 + 0.2 is not exactly 0.3). - Use str for any text – and never treat a string as a number without explicit conversion. - Use bool for conditions – avoid using int 0/1 for logic; it's less readable.

Troubleshooting & edge cases

Here are the most common mistakes and how to fix them.

# Mistake 1: Treating a string like a number
age_input = input("Enter your age: ")   # Returns a string!
age = age_input + 5                     # ❌ TypeError: can only concatenate str (not "int") to str
# Fix: convert to int
age = int(age_input) + 5                # ✅ Works

# Mistake 2: Forgetting type after logical expression
score = 85
passing = score >= 70
print("Passing status: " + passing)     # ❌ TypeError: can only concatenate str (not "bool") to str
# Fix: convert to string
print("Passing status: " + str(passing))  # ✅

# Mistake 3: Accidentally using int where float is needed
total = 10 + 20   # int arithmetic → result is int (30)
average = total / 2  # This works, but returns a float (15.0)
# But if you need exact division: use // for integer division
exact = total // 2  # Returns int 15

# Edge case: Checking type with `isinstance()` is safer than `type()`
def process(value):
    if not isinstance(value, (int, float)):
        raise TypeError("Expected a number")
    return value * 2

What you learned & what's next

You've mastered the four core Python variables and data types: int, float, str, and bool. You understand:

  • How variables are just labels that point to objects.
  • How dynamic typing works (and why it's both powerful and tricky).
  • How to check types with type() and avoid type mixing errors.
  • How to use f-strings to cleanly combine different types.

Next lesson: Learn how to convert between data types safely using int(), float(), str(), and bool(), and explore more complex data types like list and dict. That knowledge will unlock storing collections of data — a cornerstone of real-world Python programming.

Ready to level up? Move on to "Type Conversion and Collections."

Practice recap

Now it's your turn! Write a short script that asks the user for their birth year (as a string), converts it to an integer, calculates their age, and prints a message like "You are 25 years old." Store the age in a variable of type int and the message in a str. Use an f-string for the output. Bonus: handle the case where the user enters text that isn't a valid integer — for now, just let the program crash, but note where you'd add error handling.

Common mistakes

  • Using + to combine a string and a number — Python raises TypeError: can only concatenate str (not "int") to str. Always convert numbers to strings with str().
  • Forgetting that input() always returns a string — trying to do math directly on user input leads to errors. Convert first with int(input(...)) or float(input(...)).
  • Assuming True and False are just for conditions — they are actually int subclasses, so True + 5 works but often indicates a logic bug.
  • Relying on type() for type checking in production code — use isinstance() which handles inheritance correctly and is more robust.

Variations

  1. Type annotations (Python 3.6+): Use x: int = 10 to suggest the intended type (but Python doesn't enforce it). Great for code clarity and IDE support.
  2. f-strings vs % formatting: f-strings are the modern, readable way to embed variables in strings. Avoid % formatting or .format() for new code.
  3. decimal.Decimal for precise money: Use the decimal module instead of float when exact decimal arithmetic matters (e.g., financial calculations).

Real-world use cases

  • E-commerce checkout: Store product price as float, quantity as int, and description as str — then format them with f-strings for an order summary.
  • User age verification: Accept user input as str from a form, convert to int, compare with a threshold using bool logic to grant access.
  • Game score tracking: Keep player health as int, position coordinates as float, player name as str, and game-over flag as bool.

Key takeaways

  • Variables are names that reference objects in memory — the type belongs to the object, not the variable.
  • Python has four fundamental built-in types: int (whole numbers), float (decimals), str (text), and bool (True/False).
  • Dynamic typing lets a variable change type, but you must track what type it holds to avoid runtime errors.
  • Use type() to inspect a variable's type, and isinstance() for safe type checking in production code.
  • Always convert non-string values to strings with str() when concatenating with +, or use f-strings for automatic conversion.
  • Booleans are integers under the hood — True equals 1, False equals 0 — so be careful when mixing them with arithmetic.

Sponsored

Sponsored

Discussion

Questions, corrections, and tips help everyone reading this page.

0 comments

Add a comment

Shown publicly with your comment.

Be constructive · max 4,000 characters

No comments yet — start the thread.

Related tutorials, quizzes, and articles for this topic.