Skip to main content

Python Variables and Data Types: A Practical Introduction

Beginner25 min6 exercises95 XP
0/6 exercises

Imagine you're shipping a package. You fill out a label that asks for the weight. You write "heavy" instead of a number. The shipping system crashes — it can't calculate a price from the word "heavy."

That's exactly the kind of problem data types solve in programming. Types tell Python whether something is a number, a piece of text, a true/false answer, or nothing at all. Getting this right is the difference between code that works and code that explodes.

In the previous tutorial, you learned how to create variables and work with strings and numbers. Now we're going deeper. You'll meet every core data type in Python, learn how to check and convert between them, and avoid the most common type-related bugs.

What Are Python Data Types?

A data type is a label that tells Python what kind of value something is. It determines what operations you can perform on that value.

Think of it like containers in a kitchen. A measuring cup holds liquids. A scale weighs solids. You wouldn't pour flour into a measuring cup and expect an accurate weight. Each container is designed for a specific kind of thing.

Python has five core data types you'll use every day:

The five core Python data types
Loading editor...

The type() function is your best friend when working with data types. It tells you exactly what kind of value you're dealing with. When your code isn't working, checking types is usually the fastest way to find the problem.

How Python Integers and Floats Work

Python has two types of numbers: integers (int) for whole numbers and floats (float) for decimals. Most of the time, you don't need to think about the difference. But sometimes it really matters.

When to Use Integers vs Floats

Use integers when something is always a whole number — like counting people, tracking scores, or indexing a list. Use floats when you need precision — like measuring temperature, calculating percentages, or working with money.

Integers vs floats
Loading editor...

Making Large Numbers Readable with Underscores

Big numbers are hard to read. Is 1000000 one million or ten million? Python lets you use underscores as visual separators. Python completely ignores the underscores — they're just for your eyes.

Underscores in large numbers
Loading editor...

The 0.1 + 0.2 Problem in Python

Here's something that surprises almost everyone the first time they see it. Try running this code:

The floating-point surprise
Loading editor...

You expected 0.3, but you got 0.30000000000000004. This isn't a Python bug. Every programming language has this problem.

Computers store numbers in binary (1s and 0s). Some decimal numbers, like 0.1, can't be represented perfectly in binary — just like 1/3 can't be written perfectly as a decimal (0.333333... goes on forever).

How to deal with floating-point issues
Loading editor...

One more important detail: regular division (/) always produces a float, even when both numbers are integers and the result is a whole number.

Division always returns a float
Loading editor...

How Python Booleans Work (True and False)

A boolean is the simplest data type in Python. It can only be one of two values: True or False. That's it.

Booleans are like light switches — on or off, yes or no. They're the foundation of every decision your code makes. Every if statement, every while loop, every comparison boils down to a boolean.

Booleans and comparisons
Loading editor...

What Are Truthy and Falsy Values in Python?

Every value in Python can be treated as a boolean. Some values count as True (called "truthy") and some count as False (called "falsy"). You can check any value by passing it to bool().

Truthy and falsy values
Loading editor...
Here's the complete rule for falsy values. Memorize these — everything else is truthy:
---------
FalseboolIt literally is False
0intZero
0.0floatZero
""strEmpty string
NoneNoneTypeAbsence of value
[]listEmpty list
{}dictEmpty dictionary

What Is None in Python?

None is Python's way of saying "nothing here." It's not zero. It's not an empty string. It's the complete absence of a value.

Think of a form with a "middle name" field. If someone leaves it blank, that's different from writing the number 0 or an empty string "". They just don't have a middle name. That blank field is None.

None is not zero or empty
Loading editor...

How to Check for None in Python

Always use is None or is not None to check for None. Don't use ==. This is a Python convention backed by a real technical reason.

Avoid: == None
value = None

if value == None:
    print("No value")
Prefer: is None
value = None

if value is None:
    print("No value")
None as a default value
Loading editor...

You'll see None used as a default value in functions all the time. It's a clean way to say "this argument is optional."


How to Check the Type of a Variable in Python

Python gives you two tools for checking types: type() and isinstance(). They look similar but serve different purposes.

Using type() to Identify a Value

type() tells you the exact type of a value. It's great for debugging — when something isn't working, checking the type often reveals the problem immediately.

Using type() for inspection
Loading editor...

Using isinstance() for Type Checking

isinstance() checks if a value is of a certain type (or one of several types). It's the preferred way to check types in real code because it works with inheritance and is more readable.

isinstance() — the preferred way to check types
Loading editor...

Here's a fun fact: booleans are actually a subclass of integers in Python. True is secretly 1 and False is secretly 0.

The bool-int relationship
Loading editor...

How to Convert Between Types in Python

Sometimes you have a value in one type but need it in another. A user types their age into a form — it arrives as the string "25", but you need the integer 25 to do math. Python gives you built-in functions to convert between types.

Converting with int(), float(), str(), and bool()

Type conversion basics
Loading editor...

Common Type Conversion Gotchas

Not every conversion works. Python will crash with a ValueError if you try to convert something that doesn't make sense.

Conversions that fail
Loading editor...

Converting to bool() follows the truthy/falsy rules we covered earlier:

Converting to bool
Loading editor...

Python Variable Assignment: Multiple Assignment and Swapping

Python has some convenient shortcuts for working with variables that most other languages don't have. These aren't just clever tricks — professional developers use them every day.

Multiple Assignment in One Line

You can assign values to multiple variables on a single line. This is especially nice when you have a group of related values.

Multiple assignment
Loading editor...

Swapping Variables Without a Temporary Variable

In most languages, swapping two variables requires a temporary variable. Python has a cleaner way.

Other languages: need a temp variable
a = 1
b = 2

# Need a third variable to hold the value
temp = a
a = b
b = temp
print(a, b)  # 2 1
Python: one-line swap
a = 1
b = 2

# Python handles the swap in one step
a, b = b, a
print(a, b)  # 2 1

The line a, b = b, a works because Python evaluates the entire right side first (b, a becomes 2, 1), and then assigns those values to the left side. No temporary variable needed.


Practice Exercises

Time to put your knowledge to the test! These exercises cover everything from this tutorial. They go from easiest to hardest.

Remember: struggling is learning. Try each exercise before peeking at hints. Read error messages carefully — they usually tell you exactly what went wrong.

Exercise 1: Create Variables of Each Type
Write Code

Create one variable of each core Python type and print its type. Your output should be exactly:

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

You can name the variables anything you like and give them any value — as long as the types match.

Loading editor...
Exercise 2: Temperature Converter
Write Code

Convert a temperature from Fahrenheit to Celsius.

The formula is: **Celsius = (Fahrenheit - 32) * 5 / 9**

A variable fahrenheit is given with the value 98.6. Calculate the Celsius equivalent and print the result in this exact format:

98.6F = 37.0C
Loading editor...
Exercise 3: Predict the Output — Truthy or Falsy?
Predict Output

Without running the code, predict what each line will print. Then run it to check your answers.

Write your predictions as comments, then click Run to verify.

Loading editor...
Exercise 4: Fix the Bug — String + Number Crash
Fix the Bug

This code is supposed to print a user's profile summary, but it crashes with a TypeError. Fix the code so it prints:

Name: Alice
Age: 25
Height: 5.6 feet

You may fix it any way you like (f-strings, str() conversion, etc.).

Loading editor...
Exercise 5: Swap Two Variables
Write Code

Two variables are given: a = 10 and b = 20. Swap their values without using a temporary variable, then print both.

Expected output:

a = 20
b = 10
Loading editor...
Exercise 6: Type Conversion Chain
Write Code

You're given a string price_text containing "49" and an integer quantity of 3.

1. Convert price_text to an integer

2. Calculate the total (price times quantity)

3. Print the result in this exact format:

3 items at $49 each = $147 total

You must use the original variables — don't hardcode the numbers in your print statement.

Loading editor...

Summary: Python Variables and Data Types

Here's a quick reference of everything you learned in this tutorial:
---------
int42, -7, 1_000Whole numbers
float3.14, 0.0, -2.5Decimal numbers
str"hello", 'world'Text
boolTrue, FalseYes/no values
NoneNoneAbsence of value
Key tools:
---------
type(x)See what type x istype(42)<class 'int'>
isinstance(x, int)Check if x is a certain typeisinstance(42, int)True
int(), float(), str()Convert between typesint("42")42
bool()Check truthy/falsybool("")False
a, b = 1, 2Multiple assignmentAssign several variables at once
a, b = b, aSwap valuesNo temp variable needed

What's Next?

In the next tutorial — [Numbers and Math](/python/numbers-and-math) — you'll dive deeper into Python's number system. You'll learn about the math module, rounding strategies, number formatting, and how to build programs that crunch numbers like a pro.