Skip to main content

Variables and Data Types in Python with Examples

Concepts about variables and data types in Python

Learn what variables and data types are in Python, how to declare them, what types exist, and how to avoid common mistakes when working with them.

What exactly is a variable?

Imagine you're moving. You have a lot of boxes. To avoid going crazy, you stick a label on one box that says "Books" and you put your books inside.

In Python, the box is a space in your computer's RAM, the label is the variable name, and the content is the data.

Golden Rule: In Python, variables don't "store" data like physical boxes, but rather "point" to it like arrows. This is called a reference.

Declaration and Assignment

Unlike languages such as Java or C++, in Python you don't need to say "I'm going to store a number." Python is dynamic: it looks at the data and deduces what it is.

Python
# This is how simple it is to create a variable
username = "Gabriel"
age = 28
height = 1.75
is_developer = True

Naming Rules

You can't name your variables just any old way. Python has rules and conventions:

  • Allowed: Letters, numbers, and underscores _.

  • Forbidden: Starting with numbers or using spaces.

  • Case Sensitive: score and Score are two different variables.

The Snake Case Style 🐍

In Python, by convention (PEP 8), we use snake_case (lowercase words separated by underscores).

last_login

lastLogin (This is CamelCase, used in JavaScript).

Reserved words (keywords)

Python has words you cannot use as variable names because they already have a special meaning. Some of them are:

False, True, None, and, or, not, if, else, elif, for, while, break, continue, def, return, import, from, class, try, except, finally, with, as, pass, raise, in, is, lambda.

Python
# ❌ Error: 'if' is a reserved word
if = 10

# ✅ Correct: use a valid name
if_condition = 10
DivZone ad link Logo
AI PlatformTurn Code into Customers.Try it free

Primitive Data Types

To be an expert, you must know the 4 basic types that you will see 90% of the time:

TypeNameExampleUse
Stringstr"Hello"Text, messages, IDs.
Integerint42Whole numbers (no decimals).
Floatfloat3.14Numbers with decimals (precision).
BooleanboolTrueLogical values (True/False).

The NoneType type

Python has a special type called None that represents the absence of value. It is different from 0, "" (empty string), or False. It is used to indicate that a variable doesn't have a defined value yet.

Python
result = None  # We don't know the result yet
# Later...
result = 42 # Now it has a value

Dynamic Typing and its Risks

Python allows you to change the type of a variable on the fly. This is very flexible but dangerous in large projects.

Python
points = 10      # It's an int
points = "Ten" # Now it's a str! Python doesn't complain.

Pro Tip: To avoid confusion in advanced courses, we use Type Hints:

Python
# We tell other devs that 'age' should be an integer
age: int = 25
name: str = "Anna"

Operations with Variables

Variables aren't just there to look pretty; they interact with each other.

Python
product_price = 100
tax = 0.21

final_price = product_price * (1 + tax)
print(f"The total to pay is: ${final_price}")

The type() function

Python includes a useful function called type() that tells you the type of any variable. It's ideal for debugging and understanding what data type you're working with.

Python
name = "Anna"
age = 25
height = 1.75

print(type(name)) # <class 'str'>
print(type(age)) # <class 'int'>
print(type(height)) # <class 'float'>

String Manipulation

Python
first_name = "Gabriel"
last_name = "Maza"

# The modern way: f-strings
full_name = f"{first_name} {last_name}"
print(full_name.upper()) # Result: GABRIEL MAZA

# You can also multiply strings
separator = "-" * 20
print(separator) # --------------------

Type Conversion (casting)

Sometimes you need to convert one data type to another. Python provides functions for this:

Python
# Convert string to number
age_text = "25"
age_number = int(age_text)
print(age_number + 5) # 30

# Convert number to string
score = 95
message = "Your score is: " + str(score)
print(message) # Your score is: 95

# Convert to float
price = "19.99"
price_float = float(price)
print(price_float + 0.01) # 20.0

Common Mistakes (To Avoid Frustration)

  1. NameError: Trying to use a variable you haven't created yet.
Python
print(total_points)  # Error: name 'total_points' is not defined
  1. TypeError: Trying to combine things that don't belong together.
Python
age = 25
text = "My age is " + age # Error: cannot concatenate str and int

# ✅ Correct: convert to string first
text = "My age is " + str(age)

Data type summary table

TypePython NameMutable?Examples
strStringNo"Hello", 'Python', "123"
intIntegerNo42, -5, 1000000
floatFloatNo3.14, -0.5, 1.0
boolBooleanNoTrue, False
NoneTypeNullNoNone

Practical challenge: "Tip Calculator"

Write a program that calculates how much each person should pay for a shared dinner.

Test variables:

Python
total_bill = 450.00
num_people = 4
tip_percentage = 15 # 15%

# Your logic here
# tip = ...
# total_with_tip = ...
# total_per_person = ...

Hint: First calculate the tip as a percentage of the total, then add the tip to the total, and finally divide by the number of people.

tip

To calculate a percentage, multiply the total by the percentage divided by 100: tip = total_bill * (tip_percentage / 100).

Resources

Ready to continue? Now that you know how to store data, learn how to manipulate it with operators in Python.

Want to practice with interactive exercises? Use DivZone AI to create and test your own exercises.