Concepts / Storing Values in Variables

Storing Values in Variables

Go to the end of the line under Variable value and append ;C:\Python27 (please verify that this folder exists, it will be different for newer versions of Python) to the end of what is already there. Of course, use the appropriate folder name.

  • Programming

Why Variables Matter

Using only literal constants—hardcoded numbers like 5 or strings like 'hello'—quickly becomes limiting. Imagine writing a program to calculate someone's age: you would need to rewrite the entire program every time you wanted to use it for a different person. Variables solve this problem by giving you named storage locations in your computer's memory where you can keep information that changes. A variable is exactly what its name suggests: a container whose value can vary. Instead of writing the same calculation over and over with different numbers, you store a person's birth year in a variable, and your program works for anyone.

Variables are parts of your computer's memory where you store information. Unlike literal constants, you need a way to access these memory locations, so you give them names.

How Variable Assignment Works

When you assign a value to a variable, you are connecting a name to a location in memory that holds that value. The assignment operator, written as an equals sign (=), performs this connection. On the left side of the = you write the variable name; on the right side you write the value you want to store. This statement tells the computer: take the value on the right, find a spot in memory to store it, and remember that spot by the name on the left.

points toivariable nameMemory Location5=assignment operator5value to store
What happens when you assign a value to a variable? The variable name becomes a label for a memory location holding that value.

The Role of Variable Names

A variable name is your way of asking the computer to retrieve a value from memory. When you use a variable name in your code, the computer looks up that name, finds the memory location it refers to, and retrieves the value stored there. This is why you must give variables meaningful names: the name is the only way you and the computer have to refer to that stored value. Without a name, the value would be lost in memory with no way to access it.

retrievesretrievesretrievesagevariable name (key)25stored valuescorevariable name (key)98stored valuenamevariable name (key)Alicestored value
How does the system use a variable name to find and retrieve the stored value?

Data Types in Variables

Variables can hold values of different types, called data types. The basic types are numbers and strings. Numbers include both whole numbers (integers) and decimal numbers (floating-point values). Strings are sequences of characters, like words or sentences. When you store a value in a variable, the computer remembers not just the value itself but also what type of value it is. This matters because different types behave differently: you can add two numbers together, but adding two strings concatenates them (joins them end-to-end). In later chapters, you will learn how to create your own custom types using classes.

  • Numbers: integers (whole numbers like 5, -10, 0) and floating-point numbers (decimals like 3.14, -2.5)
  • Strings: text values like 'hello', 'Alice', or 'Python is fun'
  • Other types: booleans (true/false), lists, dictionaries, and custom types you define

A Complete Example: Assignment and Retrieval

Assigning and Using a Variable

Write out the steps of what happens when you assign the value 5 to a variable named i, and then use that variable in a print statement.

Create the assignment statement: You write i = 5. This tells the computer to store the value 5 in a memory location and associate it with the name i.

Computer allocates memory: The computer finds an available location in memory and stores the number 5 there.

Computer creates the binding: The computer records that the name i refers to this memory location. Now whenever you use the name i, the computer knows to look up this location.

Use the variable in a print statement: You write print(i). The computer sees the name i, looks it up, retrieves the value 5 from memory, and prints 5 to the screen.

The screen displays: 5

Appending to Environment Variables

A practical example of variable storage is working with environment variables, which are variables your operating system maintains. One common environment variable is the PATH, which tells your system where to find executable programs. When you need to add a new location to PATH, you do not replace the entire value; instead, you append (add to the end) the new path. This means you retrieve the current value, add a semicolon separator, then add the new path, and store the combined result back.

C:\Windows\System32;C:\ProgramFiles\Pythonoriginal PATH valueC:\Windows\System32;C:\ProgramFiles\Python;C:\Python27PATH after appending
What is the before and after state of a PATH variable when you append a new directory to it?

To append C:\Python27 to your PATH variable, you go to the end of the current value and add a semicolon (the separator between paths) followed by the new path. The key point is that the variable still has the same name (PATH), but its value has grown to include the new location. This is what makes variables powerful: you can change their contents without changing their names, and the rest of your system continues to use the same variable name to access the updated value.

Common Mistakes When Working with Variables

  • Confusing the variable name with the value it stores

    This confusion leads to misunderstanding how variables work. The name and the value are separate things: the name is a label, the value is what is stored.

    Fix: Always think of a variable name as a label or pointer to a location in memory, not as the value itself. The value can change, but the name stays the same.

  • Assuming a variable holds a specific memory address

    Memory addresses are managed by the operating system and are not guaranteed or exposed to you in most programming contexts. Relying on specific addresses makes code fragile and non-portable.

    Fix: Trust that the system will manage memory for you. Use variable names to refer to values, not memory addresses.

  • Forgetting that variables must be assigned before use

    If you have not stored anything in a variable, there is nothing to retrieve. The system will report an error.

    Fix: Always assign a value to a variable before you try to use it. Use the assignment operator (=) to store an initial value.

  • Not recognizing that variable values can change

    Variables are designed to hold changing values. When you assign a new value, the old value is replaced.

    Fix: Remember that each new assignment overwrites the previous value. If you need to keep both values, use two different variables.

Why This Matters in Real Programs

Consider a banking application. Instead of hardcoding account balances like 1000, 2500, 5000 throughout the program, you store each customer's balance in a variable with a meaningful name like customer_balance. When a customer makes a withdrawal, you retrieve the current balance, subtract the withdrawal amount, and store the new balance back in the same variable. The program works for any customer and any balance because the variable name stays the same while the value changes. This is why variables are fundamental to every real program: they let you write code once that works with many different pieces of data.

Practice: Trace Variable Storage

MEDIUM

Imagine you are the computer executing these steps. For each line, describe what happens in memory: (1) What value is being stored? (2) What variable name is it being stored under? (3) If you were to print the variable at this point, what would appear on the screen? Step 1: Assign name = 'Alice'. Step 2: Assign score = 95. Step 3: Print name. Step 4: Assign score = 98. Step 5: Print score.

Hints
  • After step 1, the name variable holds the string 'Alice' in memory.
  • After step 2, the score variable holds the number 95.
  • When you print a variable, the computer looks up that name and retrieves the value stored there.
  • After step 4, the score variable now holds 98 instead of 95. The old value is gone.

Key Takeaways

  • Variables are named storage locations in your computer's memory that hold values you want to use and manipulate in your program.
  • The assignment operator (=) connects a variable name to a value: the name becomes a label for a memory location, and the value is what is stored there.
  • Variable names are how you retrieve values from memory: when you use a variable name, the computer looks it up and retrieves the stored value.
  • Variables can store different data types—numbers (integers and floating-point), strings, and other types—and the type affects how the value behaves in operations.
  • Variables are powerful because you can change their values without changing their names, allowing the same code to work with different data.