Python Programming from First Principles: Learn to Code, Think Computationally, and Solve Real-World Problems
PDFEPUB
BOOK 000 · CHAPTER 2 · Variables

Variables

On this pageCreating and Using VariablesChanging ValuesNaming Conventions for VariablesCombining Variables and ExpressionsMini Project — Travel Distance Calculator

Programs become powerful when they can remember information and use it later. That’s exactly what variables do. A variable is a name that refers to a value. Assignment connects a name to a value, and later code can use that name. Assigning a value does not automatically copy the object.

Creating and Using Variables

To create a variable, use the assignment operator (=). The name appears on the left, and the value you want to store appears on the right.

age = 25
city = "London"
print(age)
print(city)
Listing 51 — Creating and Using Variables

Output

25
London

When you print age or city, Python retrieves the stored values.

Unlike mathematics, the = symbol in Python does not mean equality—it means assignment: make the name on the left refer to the value on the right.

Changing Values

Once a variable is created, you can update its value at any time. The new assignment overwrites the old one.

temperature = 20
print(temperature)

temperature = 25
print(temperature)
Listing 52 — Changing Values

Output

20
25

Variables are flexible. The same name can store different kinds of data at different points in a program, though doing so carelessly can make code confusing.

Naming Conventions for Variables

Good names make code easier to understand. Variable names must start with a letter or underscore, followed by letters, numbers, or underscores. They are also case-sensitive, so Name and name are different.

✅ Valid names:

name,age_2025,_score

❌ Invalid names:

2nd_place,first-name,total$

It’s a good habit to use descriptive names that explain the variable’s purpose. For example:

user_name = "Alice"
item_price = 19.99
Listing 53 — Naming Conventions for Variables

Combining Variables and Expressions

Variables can store values that you use in calculations or combine into new results.

price = 10
quantity = 3
total = price * quantity
print(total)
Listing 54 — Combining Variables and Expressions

Python evaluates the expression on the right first (10 * 3), then stores the result (30) in total. This allows you to perform operations dynamically, rather than typing every number directly into your code.

Mini Project — Travel Distance Calculator

Write a program that calculates how far a car travels based on speed and time.

Instructions:

  • Create two variables: speed (in kilometers per hour) and time (in hours).
  • Compute the distance using the formula distance = speed * time.
  • Display the result with a descriptive message.

Example Run:

Speed: 90
Time: 2
The car traveled 180 kilometers.
Listing 55 — Mini Project — Travel Distance Calculator