Getting Started with Programming

Variables


Learning Objectives

  • You understand a variable as a named value in a running program.
  • You can store user input in a variable and reuse it later.
  • You can reassign a variable and predict the result.
  • You can choose readable variable names that explain intent.

In the previous chapter, you saw a program that stored the user’s answer in a variable named favorite_color and then used that variable later. This chapter looks more closely at what variables are and why they matter.

A Variable Is a Name for a Value

A variable is a name that refers to a value in a running program. Variables are the main way Python remembers things while a program is executing.

name = "Ada"
age = 20

Here, name refers to the string "Ada", and age refers to the integer 20. After these two lines, those names can be used wherever the values would be:

print(name)
print(age)

That is the whole point of having variables: the same value can be used more than once, in more than one place, without typing it out again.

name = input("What is your name? ")
print(f"Hello, {name}")
print(f"Nice to meet you, {name}")

Without the variable, you would need to ask the user twice, or copy the value somewhere by hand. With it, the value is captured once and then reused as many times as needed.

Reuse a nickname

0 / 10 points

Ask the user for a nickname once, store it in a variable, and print two different lines that both include the exact nickname.

Do not ask for the nickname twice.

Example input:

Ada

One possible output:

Saved nickname: Ada
Welcome back, Ada

A Variable Must Exist Before It Can Be Used

A variable must be created before it can be used. This is done with an assignment statement: a line of code that gives a name to a value.

greeting = "Hello, world!"

The left-hand side of the = is the name of the variable, and the right-hand side is the value that it will refer to. After this line runs, there is a variable named greeting that holds the value "Hello, world!".

Before a variable is assigned, it does not exist, and trying to use it will cause an error. For example, the following program will fail:

print(greeting)
greeting = "Hello, world!"

Variables and natural-language programming

0 / 5 points

Drag and drop the natural-language programming steps to the area marked with “Program”. Arrange the steps so that the code prints the values “Hello”, “World”, and “3”, in any order you wish.

Assignment Changes the Program’s State

Python runs your program one line at a time. As it runs, a small picture of variables and their values is being built up and changed. That picture is called the program state.

When Python executes a line like this:

count = 3

the state changes. After that line, there is a variable named count and its value is 3.

If the program then executes:

count = count + 1

something slightly more interesting happens. Python reads the right-hand side first. The current value of count is 3, so count + 1 is 4. Then Python assigns that result back to count. After this line, count has the value 4.

This is one of the first places where what the code says is different from what is happening. The line looks symmetric, but the right-hand side is evaluated before the left-hand side is updated. Tracing the state, rather than just reading the text, is what makes lines like this clear.

To practise tracing, try “stepping through” a program to see this in action below. Before pressing “Next”, always predict what the program state and output will be after the next line runs. This is a skill that takes practice, but it is one of the most important things to get good at in programming.

Code

Step 1 of 10

1 / 10
Formatting...

State

main

No variables

Output

No output yet

Reassigning a Variable

A variable can be assigned again, and its new value replaces the old one.

mood = "tired"
mood = "awake"
print(mood)

This prints awake. The old value is gone — there is only one variable named mood, and it now refers to the second value. Reassigning is not a mistake. It is one of the most common things programs do.

You will reassign variables constantly when you start using loops in Part 2, but even short input-output programs use it:

answer = input("How are you? ")
answer = answer.strip()
print(f"Logged: {answer}")

This program reassigns answer to a cleaned-up version of itself. (strip() removes leading and trailing whitespace; you will see more string methods in the next chapter.)

Reassignment order

0 / 5 points

Arrange the lines so that the program prints awake.

Choosing Readable Names

A variable’s name has no technical effect on what the program does, but it has a large effect on whether the program can be read later.

Compare:

x = input("How many minutes did you study? ")

with:

study_minutes = input("How many minutes did you study? ")

Both work. The second tells the reader, including future you, what the value represents. Reading code is a large part of what you will do this course, so giving variables names that match their meaning is one of the most useful small habits you can build.

A few common conventions for Python:

  • Use lowercase words separated by underscores, like study_minutes or last_name.
  • Names usually describe what the value is, not how it is computed.
  • Single-letter names like x or n are fine for short temporary values, but avoid them for anything that lives for more than a few lines.

Critique variable names

0 / 10 points

Compare these two lines:

t = input("What topic did you revise? ")
revision_topic = input("What topic did you revise? ")

In two or three sentences, explain why revision_topic is usually a better variable name than t in this program.

Focus on readability. Do not claim that changing the variable name changes what Python computes; both lines can store the same kind of value.


What Counts as a Valid Variable Name

Python variable names can use letters, digits, and underscores, but they cannot start with a digit. They are also case-sensitive: count and Count are two different names.

A few names are reserved by the language itself and cannot be used as variables, such as if, else, for, while, def, and return. You will meet most of these in the parts ahead. If you accidentally use one of them, Python will report a syntax error.

A Small Example That Uses Several Variables

Suppose you are building the first version of a study log. The program asks the user what they studied, for how long, and prints a small confirmation:

subject = input("What did you study? ")
minutes_text = input("For how many minutes? ")
print(f"Logged {minutes_text} minutes of {subject}.")

This program uses two variables, subject and minutes_text. Each one captures one piece of information from the user. The final print line then combines them into a confirmation message.

Notice that minutes_text is text, not a number. That is fine here, because the program only displays it. As soon as the program needs to do arithmetic on the value — for example, add today’s minutes to yesterday’s total — the text will need to be converted, as you will see in Numbers and Arithmetic.

Check Your Understanding

  1. In your own words, what does an assignment statement like count = 3 actually do?
  2. After the following lines run, what is the value of total?
total = 5
total = total + 2
total = total + total
  1. Why is study_minutes usually a better variable name than x in the study log program?

AI Study Aid

Create a chapter diagram

We're looking into to what extent AI-generated diagrams could help with studying.

Use this study aid to generate an AI-generated visual summary of the material you just studied. Each diagram style emphasizes the content in a different way, so you can choose the focus that feels most useful.

Using the diagram generator is voluntary and does not affect your course progress. We encourage you to try it out and see if it helps, but it's totally up to you! Your answers help us understand how to make better study aids in the future.

Diagrams tried: 0