Variables and Data Types

Reviewed & published by Brayan K

A variable in Python is a named container that stores a value in your program's memory, letting you label data and reuse or change it as the code runs.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Learn how to store, name, and work with different types of data in Python — the foundation of every program.

What You'll Learn in This Lesson

1 What Is a Variable?

A variable is a named container that stores a value in your computer's memory.

🎁 Think of it like a labeled box:

name = "Alice"    # Create a box labeled 'name', put "Alice" inside
age = 25          # Create a box labeled 'age', put 25 inside

When Python sees name = "Alice", it:

2 Why Do Variables Matter?

Without variables, your program would be stuck. It couldn't:

🌍 Variables in Real Programs

Let's look at how variables work together in a real scenario. Here's a simple receipt calculator — the kind of logic that powers every online shop:

# A simple receipt calculator
item_name    = "Python Book"
price        = 29.99
quantity     = 2
discount     = 5.00
tax_rate     = 0.20

subtotal     = price * quantity
after_disc   = subtotal - discount
tax_amount   = after_disc * tax_rate
total        = after_disc + tax_amount

print(f"Item:     {item_name}")
print(f"Subtotal: £{subtotal:.2f}")
print(f"Discount: -£{discount:.2f}")
print(f"Tax:      £{tax_amount:.2f}")
print(f"TOTAL:    £{total:.2f}")

Every variable has a clear, descriptive name. You can read this like a sentence. That's the goal of good variable naming.

Notice the :.2f inside the f-string — that formats a float to 2 decimal places (like £29.99, not £29.990000). You'll learn more formatting tricks as you progress.

3 Creating Variables — The Assignment Operator

In Python, you create a variable using the = sign:

user_name = "Boopie"
user_age = 16

You can update variables anytime:

points = 10          # Start with 10 points
points = points + 5  # Add 5 more
# Now points holds 15

points = 100         # Completely replace with 100
# Now points holds 100

4 The 4 Basic Data Types

Every variable stores a type of data. Python has 4 basic types you must know:

📝 Strings (str)

Text — must be inside quotes

name = "Alice"
city = 'New York'
empty = ""

⚠️ Even "123" is a string if it's in quotes!

🔢 Integers (int)

Whole numbers — no decimal point

age = 25
year = 2024
negative = -10

✓ You can do math with integers

💰 Floats (float)

Decimal numbers — has a decimal point

price = 19.99
pi = 3.14159
temp = -2.5

✓ Use for prices, measurements, percentages

✅ Booleans (bool)

True or False — exactly two options

is_student = True
has_license = False

⚠️ Capital T and F! true won't work.

📝 Deep Dive: Strings

Strings are the most common data type in real programs — almost every app deals with text. Here's everything you need to know at this stage.

String methods — built-in actions you can call on any string

message = "  Hello, World!  "

print(message.upper())      # "  HELLO, WORLD!  "  — all caps
print(message.lower())      # "  hello, world!  "  — all lowercase
print(message.strip())      # "Hello, World!"       — removes surrounding spaces
print(message.replace("World", "Python"))  # "  Hello, Python!  "

name = "alice"
print(name.capitalize())    # "Alice"  — first letter uppercase only
print(name.title())         # "Alice"  — title case (good for names)

Methods are called using a dot . after the variable name. Python has dozens of string methods — these are the most useful ones to start with.

Multiline strings — triple quotes

Need to store text that spans multiple lines? Use three quotes:

poem = """
Roses are red,
Violets are blue,
Python is awesome,
And so are you!
"""
print(poem)

Triple quotes preserve all line breaks and indentation exactly as written. Very useful for long messages, templates, or documentation.

Escape characters — special characters inside strings

print("Line 1\nLine 2")      # \n = new line
print("Col1\tCol2")          # \t = tab (indent)
print("He said \"Hello\"")  # \" = literal quote inside string

The backslash \ tells Python "this next character is special". The most common are \n (new line) and \t (tab).

password = "securePass123"
print(len(password))          # 13

# Useful for validation:
if len(password) >= 8:
    print("Password is long enough")  # You'll learn 'if' in the Control Flow lesson!

len() works on any string. It counts every character — letters, numbers, spaces, and symbols.

🔢 Deep Dive: Numbers (int and float)

Numbers seem simple — but there are a few behaviours that surprise beginners every time.

int vs float — when does each appear?

print(10 / 2)     # 5.0  ← always float, even though result is whole
print(10 // 2)    # 5   ← floor division, always int
print(10 % 3)     # 1   ← remainder (modulo)
print(2 ** 10)    # 1024 ← exponent (2 to the power of 10)

The regular / operator always returns a float in Python 3, even when dividing 10 by 2. If you need a whole number, use //.

Python lets you add underscores to large numbers to make them easier to read — Python ignores them:

salary     = 75_000          # Same as 75000
population = 8_000_000_000   # 8 billion
distance   = 384_400         # Distance to moon (km)

print(salary)       # 75000 — underscore disappears in output

Useful built-in number functions

print(round(3.7))        # 4    — round to nearest whole
print(round(3.14159, 2)) # 3.14 — round to 2 decimal places
print(abs(-25))          # 25   — absolute value (remove minus sign)
print(max(5, 12, 3))     # 12   — largest value
print(min(5, 12, 3))     # 3    — smallest value

These built-in functions work without any imports — Python provides them automatically.

Floating point precision — a known quirk

print(0.1 + 0.2)    # 0.30000000000000004  (not 0.3!)
print(round(0.1 + 0.2, 2))  # 0.3  ← use round() to fix

This isn't a Python bug — it's how computers store decimal numbers in binary memory. It affects every programming language. The fix is simple: use round() when displaying financial or precise values.

✅ Deep Dive: Booleans

Booleans look simple — just True or False — but they're the most powerful type in programming. Every decision your program makes comes down to a boolean.

Where booleans come from

You'll often get booleans by comparing values. These are called comparison expressions and you'll master them fully in the Operators lesson:

age = 18
print(age >= 18)   # True  — is age 18 or over?
print(age == 16)   # False — is age exactly 16?
print(age != 21)   # True  — is age NOT 21?

name = "Alice"
print(name == "Alice")   # True
print(name == "alice")   # False — case sensitive!

Truthy and Falsy — every value has a boolean equivalent

Python can treat any value as True or False. This is called truthiness:

print(bool(0))        # False — zero is always False
print(bool(1))        # True  — any non-zero number is True
print(bool(-99))      # True
print(bool(""))       # False — empty string is False
print(bool("hello"))  # True  — any non-empty string is True
print(bool(None))     # False

You don't need to memorise all of these now. Just know that the concept exists — it will click naturally when you reach conditional statements.

# Create variables of each type
name = "Alice"         # String
age = 25               # Integer
height = 5.6           # Float
is_student = True      # Boolean

# Print them out
print("Name:", name)
print("Age:", age)
print("Height:", height)
print("Is Student:", is_student)

# Check the type of each variable
print("Type of name:", type(name))
print("Type of age:", type(age))

# 🎯 YOUR TURN: Create your own variables below!
your_name = "___"
your_age = 0
print(f"Hi, I'm {your_name} and I'm {your_age} years old!")

5 Variable Naming Rules (MUST Know)

Python has strict rules for variable names. Break them = error.

📏 Naming Conventions and Constants

Python has community-agreed naming conventions (called PEP 8 style). Following them makes your code immediately readable to every other Python developer on earth.

snake_case — the Python standard

Use lowercase words separated by underscores for all regular variables and function names:

user_name = "Alice"
total_price = 49.99
is_logged_in = True
max_retry_count = 3

⚠️ Works but not Python style

userName = "Alice"
totalPrice = 49.99
isLoggedIn = True
maxRetryCount = 3

camelCase (like the second column) is valid Python but is the convention in other languages like JavaScript and Java. Stick to snake_case in Python.

A constant is a variable whose value should never change after it's set. Python doesn't enforce this — it's purely a convention to signal intent to other developers:

PI          = 3.14159
MAX_SCORE   = 100
SITE_NAME   = "Learn Code Swiftly"
TAX_RATE    = 0.20
DB_TIMEOUT  = 30

When you see ALL_CAPS, it means: "this value is fixed — don't change it elsewhere in the code." Other developers will immediately understand this convention.

# Bad — impossible to understand later:
x = 25
y = 4.99
z = True

# Good — self-documenting:
user_age    = 25
item_price  = 4.99
is_in_stock = True

One-character variable names (x, y, z) are only acceptable in short mathematical formulas. For everything else, use descriptive names. Your future self will thank you.

6 Updating Variables

Variables can be changed at any time. The old value is replaced.

favorite_color = "Blue"
print(favorite_color)  # Output: Blue

favorite_color = "Red"
print(favorite_color)  # Output: Red (Blue is gone!)

Shorthand operators make updating easier:

score = 10

score += 5   # Same as: score = score + 5  → 15
score -= 3   # Same as: score = score - 3  → 12
score *= 2   # Same as: score = score * 2  → 24
score /= 4   # Same as: score = score / 4  → 6.0

🔄 Multiple Assignment and Swapping

Python has some elegant shortcuts for assigning and rearranging variables that you'll use constantly.

Assign multiple variables in one line

# Instead of three separate lines:
x = 5
y = 10
z = 15

# You can write one line:
x, y, z = 5, 10, 15

# Check they worked:
print(x, y, z)    # 5 10 15

The number of variables on the left must exactly match the number of values on the right — otherwise Python raises a ValueError.

Assign the same value to multiple variables

# Set multiple counters to zero at once:
lives = score = level = 0
print(lives, score, level)    # 0 0 0

# Useful for initialising several related variables:
red = green = blue = 255

Swapping two variables — Python's elegant trick

In most languages, swapping two variables requires a temporary "placeholder" variable. Python doesn't:

Other languages (needs a temp):

a = 5
b = 10
temp = a   # save a
a = b      # overwrite a
b = temp   # restore old a

Python (one clean line):

a = 5
b = 10
a, b = b, a   # swap!
print(a, b)   # 10 5

This works because Python evaluates the entire right side first, then assigns. It's one of the small reasons developers enjoy writing Python.

7 Printing Variables (3 Ways)

There are multiple ways to display variables:

Method 1: Comma separation

name = "Alice"
age = 25
print(name, "is", age, "years old.")
# Output: Alice is 25 years old.

Python adds spaces automatically between items.

Method 2: String concatenation (+ operator)

name = "Alice"
age = 25
print(name + " is " + str(age) + " years old.")
# Output: Alice is 25 years old.

⚠️ Must convert numbers to string with str()!

✨ Method 3: f-strings (BEST — Modern Python)

name = "Alice"
age = 25
print(f"{name} is {age} years old.")
# Output: Alice is 25 years old.

Start with f, put variables in {} — cleanest option!

8 Type Conversion (Changing Types)

Sometimes you need to convert one type to another:

# String to number
age_text = "25"
age = int(age_text)       # Now it's an integer: 25
price = float("19.99")    # Now it's a float: 19.99

# Number to string
age = 25
age_text = str(age)       # Now it's text: "25"

# Check the type
print(type(age))          # <class 'int'>
print(type(age_text))     # <class 'str'>

🔁 Type Conversion: The Full Picture

Type conversion looks simple — but there are important edge cases that will catch you out if you're not aware of them.

What works and what doesn't

# ✅ These work:
int("42")        # → 42    (text digits → integer)
float("3.14")    # → 3.14  (text decimal → float)
str(100)         # → "100" (number → text)
bool(0)          # → False
bool("hello")    # → True

# ❌ These FAIL with a ValueError:
int("3.14")      # ERROR — can't convert decimal string to int directly
int("hello")     # ERROR — not a number at all
float("abc")     # ERROR

The two-step conversion trick

To convert "3.14" to an integer, you need to go through float first:

text = "3.14"

# ❌ This fails:
result = int(text)          # ValueError!

# ✅ This works — convert to float first, then to int:
result = int(float(text))   # → 3  (decimal is dropped, not rounded)

Notice: int() truncates (drops the decimal) rather than rounding. int(3.9) gives 3, not 4.

FunctionConverts toExampleResult
int()Integerint("42")42
float()Floatfloat("3.14")3.14
str()Stringstr(100)"100"
bool()Booleanbool(0)False
int(float())Int from decimal stringint(float("3.9"))3

9 Common Errors (And How to Fix Them)

Errors are normal! Here's what you'll see most often:

Happens when you mix types incorrectly:

age = 25
print("Age: " + age)  # ❌ Can't add string + number

✅ Fix: Convert with str() or use f-string:

print("Age: " + str(age))  # ✅ Works
print(f"Age: {age}")       # ✅ Even better

Using a variable that doesn't exist:

print(username)  # ❌ 'username' was never created

✅ Fix: Create the variable first:

username = "Alice"
print(username)  # ✅ Now it exists

Also check for typos: usernme ≠ username

Code is written incorrectly:

name = "Alice     # ❌ Missing closing quote
print("Hello"     # ❌ Missing closing parenthesis

✅ Fix: Check quotes and brackets match:

name = "Alice"
print("Hello")
# Profile Card Practice
name = "Boopie"
age = 16
favorite_color = "Green"
likes_coding = True

print("=== My Profile ===")
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Favorite Color: {favorite_color}")
print(f"Likes Coding: {likes_coding}")

# Updating values
print("\n=== After Birthday ===")
age += 1  # Happy birthday!
print(f"New age: {age}")

# Swapping two variables
print("\n=== Swap Example ===")
a = 5
b = 10
print(f"Before swap: a = {a}, b = {b}")
a, b = b, a  # Python's elegant swap!
print(f"After swap: a = {a}, b = {b}")

# ✅ Expected output:
# === My Profile ===
# Name: Boopie
# Age: 16
# Favorite Color: Green
# Likes Coding: True
#
# === After Birthday ===
# New age: 17
#
# === Swap Example ===
# Before swap: a = 5, b = 10
# After swap: a = 10, b = 5

Real-World Example: Student Grade Tracker

Let's put everything from this lesson together into one real program. Read it line by line — every concept here is something you've learned in Lessons 1 and 2.

# === Student Grade Tracker ===

# Student information (strings + int)
student_name  = "Jamie Chen"
student_id    = "S20241042"
year_group    = 11

# Subject scores (integers, 0-100)
maths_score   = 78
english_score = 85
science_score = 91
history_score = 72

# Calculate average (float division)
total_marks   = maths_score + english_score + science_score + history_score
average       = total_marks / 4
average       = round(average, 1)    # Round to 1 decimal place

# Determine pass/fail (boolean)
PASS_MARK     = 60                   # Constant — never changes
is_passing    = average >= PASS_MARK

# Assign grade letter
if average >= 90:
    grade = "A"
elif average >= 75:
    grade = "B"
elif average >= 60:
    grade = "C"
else:
    grade = "F"

# Display the report card
print("=" * 35)
print(f"   STUDENT REPORT — {student_name}")
print("=" * 35)
print(f"Student ID:   {student_id}")
print(f"Year Group:   {year_group}")
print()
print(f"Maths:        {maths_score}/100")
print(f"English:      {english_score}/100")
print(f"Science:      {science_score}/100")
print(f"History:      {history_score}/100")
print()
print(f"Average:      {average}/100")
print(f"Grade:        {grade}")
print(f"Status:       {'PASSING ✓' if is_passing else 'NEEDS IMPROVEMENT'}")
print("=" * 35)

Notice the if/elif/else block

You haven't formally learned this yet — that comes in the Control Flow lesson. But you can probably guess what it does just from reading it. That's Python's readability at work. By the end of the Control Flow lesson you'll write exactly this kind of logic yourself.

📋 Quick Reference

ConceptWhat It IsExample
VariableNamed container for datax = 10
String (str)Text in quotes"Hello"
Integer (int)Whole number25
FloatDecimal number3.14
Boolean (bool)True or FalseTrue
f-stringInsert variables in textf"Hi {name}"
type()Check data typetype(x)

❓ Frequently Asked Questions

Q: What is a variable in Python?

A: A named storage location that holds data your program can use or change later.

Q: What are the 4 main data types?

A: Strings (text), Integers (whole numbers), Floats (decimals), Booleans (True/False).

Q: Can variable names start with numbers?

A: No — they must start with a letter or underscore.

Q: Why do I get "TypeError: can only concatenate str..."?

A: You're trying to combine text + number. Use str() to convert, or use an f-string.

Q: What's the best way to print variables?

A: f-strings! They're cleaner and don't require type conversion: f"Age: {age}"

🎯 Mini Challenge: About Me Program

Create a program that introduces yourself:

# 🎯 YOUR TURN: Fill in your details!
name = "Your Name"
age = 0
favorite_color = "Your Color"
likes_coding = True

# Print your profile
print("=== About Me ===")
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Favorite Color: {favorite_color}")
print(f"Likes Coding: {likes_coding}")

# Update age (it's your birthday!)
age += 1
print(f"\nAfter my birthday, I'm now {age}!")

# ✅ Expected output:
# === About Me ===
# Name: Your Name
# Age: 0
# Favorite Color: Your Color
# Likes Coding: True
#
# After my birthday, I'm now 1!

Lesson complete — you now speak Python's data language!

You can create variables, work with all 4 core data types, update values with shorthand operators, and print output three different ways. Every single Python program ever written uses exactly these skills.

Practice quiz

Which symbol creates (assigns to) a variable in Python?

  • ==
  • =>
  • =
  • :=

Answer: =. A single = is the assignment operator. == is for comparison.

What are the 4 basic data types taught in this lesson?

  • str, int, float, bool
  • str, list, dict, set
  • int, long, double, char
  • text, number, decimal, flag

Answer: str, int, float, bool. The four core types are str, int, float, and bool.

What does type(3.14) return?

  • <class 'int'>
  • <class 'float'>
  • <class 'str'>
  • <class 'decimal'>

Answer: <class 'float'>. A number with a decimal point is a float.

Which is a VALID Python variable name?

  • 2name
  • user-name
  • _count
  • my name

Answer: _count. Names may start with a letter or underscore; no hyphens, spaces, or leading digits.

What does print(10 / 2) output?

  • 5
  • 5.0
  • 5.5
  • 2

Answer: 5.0. The / operator always returns a float in Python 3, so 10 / 2 is 5.0.

What is the value of int(float('3.9'))?

  • 4
  • 3.9
  • 3
  • Error

Answer: 3. int() truncates (drops the decimal) rather than rounding, giving 3.

After a = 5; b = 10; a, b = b, a, what is a?

  • 5
  • 10
  • 15
  • None

Answer: 10. Python evaluates the right side first, so the swap makes a = 10.

What does bool('') evaluate to?

  • True
  • False
  • Error
  • None

Answer: False. An empty string is falsy, so bool('') is False.

Which is the best (modern) way to print a variable inside text?

  • Comma separation
  • + concatenation with str()
  • f-strings
  • % formatting

Answer: f-strings. f-strings like f"{name}" are the cleanest, most modern option.

Using a variable that was never created raises which error?

  • TypeError
  • SyntaxError
  • NameError
  • ValueError

Answer: NameError. Referencing an undefined name raises a NameError.

Continue this course