Skip to main content
Editor

Python Variables and Data Types: A Practical Introduction

Beginner25 min7 exercises125 XP

Leer en españolЧитать на русскомLer em portuguêsอ่านภาษาไทย

0/7 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
# The five core data types
age = 25 # int - whole numbers
temperature = 98.6 # float - decimal numbers
name = "Alice" # str - text
is_sunny = True # bool - True or False
result = None # None - absence of a value
print(type(age)) # <class 'int'>
print(type(temperature)) # <class 'float'>
print(type(name)) # <class 'str'>
print(type(is_sunny)) # <class 'bool'>
print(type(result)) # <class 'NoneType'>
Output
<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.

Integers vs floats
# Integers - whole numbers, no decimal point
students = 30
lives_remaining = 3
year = 2025
negative_number = -42
# Floats - numbers with a decimal point
pi = 3.14159
batting_average = 0.325
bank_balance = 1042.50
tiny_number = 0.001
print(type(students)) # <class 'int'>
print(type(bank_balance)) # <class 'float'>
Output
<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.

Underscores in large numbers
# Hard to read
population = 8000000000
# Easy to read - underscores are ignored by Python
population = 8_000_000_000
print(population) # 8000000000
print(type(population)) # <class 'int'>
# Works with floats too
budget = 1_250_000.75
print(budget) # 1250000.75
Output
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:

The floating-point surprise
print(0.1 + 0.2)
Output
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).

How to deal with floating-point issues
# The problem
print(0.1 + 0.2 == 0.3) # False!
# Solution 1: round() for display
print(round(0.1 + 0.2, 1)) # 0.3
# Solution 2: check if values are "close enough"
result = 0.1 + 0.2
print(abs(result - 0.3) < 0.0001) # True - close enough!
Output
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.

Division always returns a float
print(10 / 2) # 5.0 - float, not int!
print(type(10 / 2)) # <class 'float'>
# Use // for integer division
print(10 // 2) # 5 - int!
print(type(10 // 2)) # <class 'int'>
Output
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.

Booleans and comparisons
is_raining = True
has_umbrella = False
print(is_raining) # True
print(type(is_raining)) # <class 'bool'>
# Comparisons produce booleans
print(10 > 5) # True
print(10 < 5) # False
print(10 == 10) # True
print(10 != 10) # False
Output
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().

Truthy and falsy values
# Falsy values - these all act like False
print(bool(0)) # False - zero
print(bool(0.0)) # False - zero float
print(bool("")) # False - empty string
print(bool(None)) # False - None
print(bool([])) # False - empty list
print("---")
# Truthy values - everything else acts like True
print(bool(1)) # True - any non-zero number
print(bool(-5)) # True - negative numbers too!
print(bool("hello")) # True - any non-empty string
print(bool("False")) # True - the STRING "False" is truthy!
print(bool([1, 2])) # True - non-empty list
Output
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 ValueTypeWhy it's falsy
FalseboolIt literally is False
0intZero
0.0floatZero
""strEmpty string
NoneNoneTypeAbsence of value
[]listEmpty list
{}dictEmpty dictionary
()tupleEmpty tuple
set()setEmpty 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 is not zero or empty
middle_name = None
print(middle_name) # None
print(type(middle_name)) # <class 'NoneType'>
# None is NOT the same as 0, False, or ""
print(None == 0) # False
print(None == False) # False
print(None == "") # False
Output
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.

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
# Common pattern: using None as a default
def greet(name=None):
if name is None:
print("Hello, stranger!")
else:
print(f"Hello, {name}!")
greet() # Hello, stranger!
greet("Alice") # Hello, Alice!
Output
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.

Using type() for inspection
print(type(42)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type("hello")) # <class 'str'>
print(type(True)) # <class 'bool'>
print(type(None)) # <class 'NoneType'>
# You can compare types directly
age = 25
print(type(age) == int) # True
print(type(age) == str) # False
Output
<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.

isinstance(): the preferred way to check types
age = 25
name = "Alice"
temperature = 98.6
# Check against one type
print(isinstance(age, int)) # True
print(isinstance(name, str)) # True
print(isinstance(age, str)) # False
# Check against multiple types at once
print(isinstance(age, (int, float))) # True - age is an int
print(isinstance(temperature, (int, float))) # True - temp is a float
print(isinstance(name, (int, float))) # False - name is a str
Output
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.

The bool-int relationship
# Booleans are secretly integers
print(isinstance(True, int)) # True - bool is a subclass of int!
print(isinstance(True, bool)) # True
# This means you can do math with booleans
print(True + True) # 2
print(True * 10) # 10
print(False + 42) # 42
Output
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()

Type conversion basics
# str → int
age_text = "25"
age_number = int(age_text)
print(age_number + 5) # 30 - now we can do math!
# str → float
price_text = "9.99"
price = float(price_text)
print(price * 2) # 19.98
# int → str
score = 100
message = "Your score: " + str(score)
print(message) # Your score: 100
# int → float
whole = 42
decimal = float(whole)
print(decimal) # 42.0
# float → int (truncates - does NOT round!)
pi = 3.99
whole_pi = int(pi)
print(whole_pi) # 3 - the .99 is chopped off!
Output
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.

Conversions that fail
# These work fine
print(int("42")) # 42
print(float("3.14")) # 3.14
print(str(100)) # "100"
# These will CRASH
try:
print(int("hello")) # ValueError! "hello" isn't a number
except ValueError as e:
print(f"Error: {e}")
try:
print(int("3.14")) # ValueError! int() can't handle decimals in strings
except ValueError as e:
print(f"Error: {e}")
# Fix: convert string to float first, then to int
print(int(float("3.14"))) # 3 - works!
Output
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:

Converting to bool
# bool() follows truthy/falsy rules
print(bool(1)) # True
print(bool(0)) # False
print(bool("text")) # True
print(bool("")) # False
print(bool(None)) # False
# Careful: the string "0" is truthy!
print(bool("0")) # True - it's a non-empty string!
Output
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.

Multiple assignment
# Assign multiple variables at once
x, y, z = 10, 20, 30
print(x) # 10
print(y) # 20
print(z) # 30
# Great for related values
first_name, last_name, age = "Alice", "Smith", 25
print(f"{first_name} {last_name}, age {age}")
# Assign the same value to multiple variables
a = b = c = 0
print(a, b, c) # 0 0 0
Output
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.

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.

# Create one variable of each type
# Print the type of each variable
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
fahrenheit = 98.6
# Calculate celsius using the formula
# Print the result
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.

print(bool("")) # Your prediction:
print(bool(0)) # Your prediction:
print(bool("False")) # Your prediction:
print(bool(None)) # Your prediction:
print(bool(-1)) # Your prediction:
print(bool(" ")) # Your prediction:
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.).

name = "Alice"
age = 25
height = 5.6
print("Name: " + name)
print("Age: " + age)
print("Height: " + height + " feet")
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
a = 10
b = 20
# Swap a and b without a temp variable
print(f"a = {a}")
print(f"b = {b}")
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.

price_text = "49"
quantity = 3
# Step 1: Convert price_text to an integer
# Step 2: Calculate the total
# Step 3: Print the formatted result
Prices in Cents
Stretch

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

def to_cents(price_text):
pass
Solution unlocks after your first Check

Summary: Python Variables and Data Types

Here's a quick reference of everything you learned in this tutorial:

TypeExampleWhat it stores
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:

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

Harder problems

More problems on this topic: Python Basics

Related Tutorials

Was this tutorial helpful?