Python Variables and Data Types: A Practical Introduction
Leer en españolЧитать на русскомLer em portuguêsอ่านภาษาไทย
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:
<class 'int'> <class 'float'> <class 'str'> <class 'bool'> <class 'NoneType'>
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 for numbers that can have a decimal part - like measuring temperature, calculating percentages, or working with money.
<class 'int'> <class 'float'>
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.
8000000000 <class 'int'> 1250000.75
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:
0.30000000000000004
You expected 0.3, but you got 0.30000000000000004. This isn't a Python bug. Most programming languages give the same answer, because they store decimal numbers the same way.
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).
False 0.3 True
One more important detail: regular division (/) always produces a float, even when both numbers are integers and the result is a whole number.
5.0 <class 'float'> 5 <class 'int'>
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.
True <class 'bool'> True False True False
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().
False False False False False --- True True True True True
Here are the falsy values you'll meet most often. The pattern: False, None, zero of any number type, and anything empty. Everything else is truthy:
| Falsy Value | Type | Why it's falsy |
|---|---|---|
False | bool | It literally is False |
0 | int | Zero |
0.0 | float | Zero |
"" | str | Empty string |
None | NoneType | Absence of value |
[] | list | Empty list |
{} | dict | Empty dictionary |
() | tuple | Empty tuple |
set() | set | Empty set |
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 <class 'NoneType'> False False False
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.
value = None
if value == None:
print("No value")value = None
if value is None:
print("No value")Hello, stranger! Hello, Alice!
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.
<class 'int'> <class 'float'> <class 'str'> <class 'bool'> <class 'NoneType'> True False
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.
True True False True True False
Here's a fun fact: booleans are actually a subclass of integers in Python. True is secretly 1 and False is secretly 0.
True True 2 10 42
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()
30 19.98 Your score: 100 42.0 3
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.
42 3.14 100 Error: invalid literal for int() with base 10: 'hello' Error: invalid literal for int() with base 10: '3.14' 3
Converting to bool() follows the truthy/falsy rules we covered earlier:
True False True False False True
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.
10 20 30 Alice Smith, age 25 0 0 0
Swapping Variables Without a Temporary Variable
In most languages, swapping two variables requires a temporary variable. Python has a cleaner way.
a = 1
b = 2
# Need a third variable to hold the value
temp = a
a = b
b = temp
print(a, b) # 2 1a = 1
b = 2
# Python handles the swap in one step
a, b = b, a
print(a, b) # 2 1The 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.
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.
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.0CWithout 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.
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 feetYou may fix it any way you like (f-strings, str() conversion, etc.).
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 = 10You'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 totalYou must use the original variables - don't hardcode the numbers in your print statement.
Shops keep money as whole cents, because a decimal number is not always stored exactly (remember 0.1 + 0.2). Write a function to_cents(price_text) that takes a price written as text and returns the number of cents as an int.
to_cents("12.34") # 1234
to_cents("5") # 500
to_cents("-2.50") # -250 (a refund)The text may have spaces around it. The def line is written for you: put your code under it, indented four spaces, and end with return and your answer. Check calls to_cents() with its own prices, some of them hidden. (Functions get their own lesson later.)
Summary: Python Variables and Data Types
Here's a quick reference of everything you learned in this tutorial:
| Type | Example | What it stores |
|---|---|---|
int | 42, -7, 1_000 | Whole numbers |
float | 3.14, 0.0, -2.5 | Decimal numbers |
str | "hello", 'world' | Text |
bool | True, False | Yes/no values |
None | None | Absence of value |
Key tools:
| Tool | Purpose | Example |
|---|---|---|
type(x) | See what type x is | type(42) → <class 'int'> |
isinstance(x, int) | Check if x is a certain type | isinstance(42, int) → True |
int(), float(), str() | Convert between types | int("42") → 42 |
bool() | Check truthy/falsy | bool("") → False |
a, b = 1, 2 | Multiple assignment | Assign several variables at once |
a, b = b, a | Swap values | No temp variable needed |
What's Next?
In the next tutorial - 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.