Fundamentals

Python Variables and Data Types Explained With Examples

A variable is a name referring to a value. Python determines the type of a value at runtime, so you do not declare `int` or `str` before assigning it. Types matter when you combine values.

Step by step

  1. Use strings for text and integers for whole numbers.
  2. Use floats for approximate decimal arithmetic, not exact currency calculations.
  3. Use booleans for yes/no conditions.
  4. Inspect values with `type()` when debugging.

Run this example

Use Python 3. Copy the code into a file or interactive Python environment.

customer = "Alex"
orders = 3
price = 4.5
active = True
print(customer, orders, price, active)
print(type(orders).__name__)

Expected output

Alex 3 4.5 True
int

Common issue

`'3' + 2` raises TypeError; convert intentionally with `int('3') + 2`.

Try it yourself

Add a `discount` float and print the price after discount.

Choose a type that matches the task

An integer stores a whole count, a float stores an approximate decimal quantity, and a string stores text. A Boolean represents a true-or-false condition. Lists keep an ordered collection; dictionaries associate keys with values. Assignment binds a name to an object rather than declaring a permanent type.

Text read from user input or CSV is still text, even when it looks like a number. Convert it explicitly before arithmetic. Keep identifiers such as postal codes as text so you do not lose meaningful characters.

Convert and calculate

Convert units with int; the dictionary makes the record fields explicit. The original string is left unchanged.

record = {"item": "Notebook", "units": "3", "price": 2.5}
units = int(record["units"])
print(record["item"])
print(f"Total: ${units * record['price']:.2f}")
print(type(units).__name__)

Expected output

Notebook
Total: $7.50
int

Avoid surprising changes

Assigning one list to a second name makes both names refer to the same list. Use list.copy() when you need a separate shallow copy. Floating-point arithmetic is approximate; use decimal.Decimal for calculations requiring a chosen decimal rounding policy.

Exercise with a check

Change units to "4" and price to 3.25: the total should be $13.00. Change units to "three" and identify the resulting ValueError. Decide how your program should report invalid input.

Keep learning

Read the relevant documentation · Free foundational resources

Related guides: How to Learn Python From Scratch: A Beginner's Roadmap and Python For Loops vs While Loops: When to Use Each.

Interested in applying these skills to a product? Explore the optional Python to Profit course. It focuses on product and business building, not replacing foundational Python study.