Giving Your Program a Memory: Variables and Data Types
The Big Idea
This chapter introduces variables—the fundamental building blocks for making programs remember, track, and manipulate information—and applies them to store our first pieces of inventory data for PyInventory.
Roadmap
What is a Variable? We'll use the "labeled box" analogy to understand how programs store information.
Creating Your First Variables: Learning the simple syntax to create and assign data to a variable.
Meet the Core Data Types: An introduction to the essential types of data we'll use in our inventory system:
- Text (
str
): For product names and descriptions. - Whole Numbers (
int
): For item quantities. - Decimal Numbers (
float
): For prices.
- Text (
The Art of Naming: How to choose clean, readable variable names—a hallmark of a professional developer.
Working with Variables: Performing basic mathematical operations to manipulate our data.
Dynamic Typing: Understanding Python's flexible approach to handling data types.
A Professional Way to Print: Using "f-Strings" to combine text and variables seamlessly for clean output.
Updating Our
main.py
Script: Evolving our project to use variables for the first time.
Full Chapter Content
Why Do Programs Need a Memory?
In Chapter 1, our program was simple. It performed one action—printing a message—and then it was done. It had no memory. To build something useful like an inventory system, our program needs to remember things: product names, how many items are in stock, their prices, and so on.
This is where variables come in. A variable is simply a named location in the computer's memory where you can store a piece of data.
Think of a variable as a labeled box. You can put something inside the box (the data), and the label (the variable's name) helps you find it again later.
Creating Your First Variables
Creating a variable in Python is incredibly easy. You just need a name, an equals sign (=
), and the data you want to store.
Let's go back to Python's interactive session. Open your command line and type python
(or python3
). At the >>>
prompt, let's create a variable to store a product's name:
>>> product_name = "High-Performance Laptop"
Let's break this down:
product_name
is the name of our variable (the label on the box).=
is the assignment operator. It tells Python to take the value on the right and store it in the variable on the left."High-Performance Laptop"
is the data—or value—we are storing.
Now, if you type product_name
and press Enter, Python will show you the value stored inside that variable:
>>> product_name
'High-Performance Laptop'
We can do the same for the quantity in stock and its price:
>>> quantity_in_stock = 25
>>> unit_price = 1499.99
Meet the Core Data Types
In the example above, we stored three different kinds of data, known as data types:
String (
str
): This is for text. Any sequence of characters enclosed in single ('
) or double ("
) quotes is a string.product_name
is a string.Integer (
int
): This is for whole numbers (positive, negative, or zero) without any decimal points.quantity_in_stock
is an integer.Float (
float
): This is for numbers that have a decimal point. Financial data, like prices, are a perfect use case for floats.unit_price
is a float.
Python automatically detects the data type when you assign the value. This is a feature called dynamic typing, which makes Python flexible and easy to use.
The Art of Naming Variables
How you name your variables is important. It's a key part of writing code that is easy to read and understand, which is critical for professional projects. Here are the rules and conventions:
Use
snake_case
: For variable names with multiple words, separate them with an underscore (_
). This is the standard Python convention (e.g.,unit_price
, notunitPrice
orunitprice
).Be Descriptive: A variable name should clearly describe the data it holds.
product_name
is much better thanpn
orx
.Rules: Names must start with a letter or an underscore, and can only contain letters, numbers, and underscores.
2_items
is invalid, butitem_2
is fine.
Working with Variables
Once you have data in variables, you can work with it. For our numeric types (int
and float
), we can perform standard math operations.
Let's calculate the total value of our laptop stock:
>>> total_value = quantity_in_stock * unit_price
>>> print(total_value)
37499.75
We created a new variable, total_value
, and stored the result of the calculation in it. This is far more powerful than working with raw numbers, because if we update the unit_price
or quantity_in_stock
, we can simply re-run the calculation to get the new total value.
>>> quantity_in_stock = 30
>>> total_value = quantity_in_stock * unit_price
>>> print(total_value)
44999.7
A Professional Way to Print: f-Strings
We often need to print a message that combines text and the values stored in variables. While you could try to piece them together with +
, there is a much cleaner, more modern way: f-Strings.
An f-String is a string literal that starts with the letter f
before the opening quote. Inside the string, you can place variable names directly within curly braces {}
.
Compare the old way with the f-String way:
# The old, clunky way
>>> print("Product: " + product_name + ", Price: $" + str(unit_price))
# The modern, professional f-String way
>>> print(f"Product: {product_name}, Price: ${unit_price}")
Both produce the same output, but the f-String is far more readable and less error-prone. Notice we didn't have to manually convert unit_price
to a string with str()
—the f-String handles it for us. This is the preferred method for formatting strings in modern Python.
Updating Our main.py
Script
Let's put everything we've learned into practice by updating our main.py
file. We'll transform it from a simple greeter into a mini-report for a single product.
Open your main.py
file in your text editor and replace its content with the following:
# --- PyInventory: A Step-by-Step Journey to Profit ---
# Chapter 2: Giving Your Program a Memory
# 1. Define variables to hold our first inventory item's data.
product_name = "Wireless Noise-Cancelling Headphones"
quantity = 50
price = 249.95
is_in_stock = True # A new data type: Boolean (True or False)
# 2. Use an f-String to create a formatted report.
print("--- Initial Inventory Item ---")
print(f"Product Name: {product_name}")
print(f"Quantity in Stock: {quantity}")
print(f"Unit Price: ${price}")
print(f"Is it in stock? {is_in_stock}")
# 3. Calculate the total value of this inventory item.
total_value = quantity * price
print(f"Total Value of Stock: ${total_value}")
print("------------------------------")
Notice we've added comments (#
) to explain our code and a new data type, Boolean (bool
), which can only be True
or False
. It's perfect for tracking status.
Save the file and run it from your command line (make sure you are in the py_inventory
directory):
python main.py
You should see a clean, well-structured report:
--- Initial Inventory Item ---
Product Name: Wireless Noise-Cancelling Headphones
Quantity in Stock: 50
Unit Price: $249.95
Is it in stock? True
Total Value of Stock: $12497.5
------------------------------
Chapter 2: Summary & What's Next
You've made a huge leap forward. Your program now has a memory.
You learned that variables are labeled boxes for storing data.
You met the core data types: strings (text), integers (whole numbers), and floats (decimal numbers).
You practiced naming variables like a professional using
snake_case
.You used f-Strings to create clean, readable output that combines text and variables.
Right now, our data is hard-coded—it's written directly into our script. If we want to track a different product, we have to edit the file. In the next chapter, we'll solve this by learning how to make our program interactive, allowing the user to provide input while the program is running.