Variables and Assignment

A variable is a name that refers to a particular value. It is called a variable because the value it refers to can change. An assignment statement assigns a value to a variable. If a variable of that name does not yet exist, then one is created. Assignment statements look like this:

Each of these statements causes the variable on the left side to refer to the value on the right side. It is also possible to have a variable on the right side of an assignment statement, in which case the variable on the left side will now refer to the same value as the variable on the right side. After the statement below, num_1 and num_2 will both refer to the value 12.

Suppose num_1 later changes to 99. Does num_2 change too? Keep that question in mind. A later section answers it.

You can print the value that a variable refers to like so:

Variable names should be descriptive of their purpose to enhance the readability of your code. They must start with a letter or an underscore. Subsequent characters can be numbers, letters or underscores. Variable names are case sensitive, so radius, Radius, raDius, and so on would be interpreted as different variables. A variable name can be almost anything, as long as it is not one of Python's reserved keywords. Every programming language has a few words that are reserved for special operations and cannot be reused for variables.

False class finally is return
True continue for lambda try
None def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise

Static typing vs. dynamic typing

Dynamic typing

Python is a dynamically typed language, meaning variables can change from type to type with any new assignment. For example, this is a legal statement in Python:

my_number = 57

my_number = 'fifty-seven'

Dynamic typing makes programming easy to start, but it becomes a problem as your code grows, because variables that keep changing type are harder to track.

To keep your variables straight, use the type function to see what type of value a variable currently refers to. See the example below:

Static typing

Static typing means types are checked before the code runs, when the program is translated into machine code (compile time). In a statically typed language, you must declare the type of a variable in advance, and it cannot change while the program runs. This catches type-related bugs early, before the code is run.

Static typing in the programming language C++, for example, would look something like:

std::string name = "John Doe";
int age = 30;

Because C++ has static typing, these variables cannot be assigned values of a different type later on in the code. For example, if you did this:

name = 30;  // This would raise a compile-time error

Static typing also makes code easier to read and maintain. The cost is flexibility: in a statically typed language, a variable keeps the same type for its whole life. That is usually a good thing. When you can trust what a variable holds, you do not need extra checks to find out whether it is a string or a number, and code that has to handle both is longer and easier to get wrong.

Type hinting

Type hinting lets you state the expected data type of a variable (or of a function argument, which we cover later). It is a middle ground between dynamic typing and static typing.

The Python interpreter ignores type hints when the program runs. Tools such as IDEs, linters, and type checkers use them to give better feedback, document the code, and catch bugs early. Hints help readability and debugging, but they will not stop your code from running when you assign the wrong type of value.

Type hints are specified using annotations placed immediately after the argument, parameter, or variable declaration. For example:

name: str = "Tuan Nguyen"
age: int = 33

In this example, the : str annotation after name indicates that name is a string variable, and the : int annotation after age indicates that age is an integer variable. Run it and change the values:

Remember that type hints are only suggestions. Unlike a compiler for a statically typed language, the Python interpreter does not enforce them. To check the types of arguments or variables, you can use a type checker like mypy.

This course checks for them, though. From here on, a quiz or check does not pass until each variable has a type hint where it is first given a value. Give the hint once. Later lines that change the value do not repeat it:

count: int = 0
count = count + 1

If one is missing, the result tells you the line and shows what to write.

Check your understanding. Run this program as it is. The hint says int, but the value is text. Python does not stop you: it stores the text and prints it. A hint that disagrees with its value is still a mistake, so fix it. Change the hint so it matches the value, then run it again.

Hint 1

int means a whole number. What kind of value is "thirty-three"? A few lines up, the lesson showed the hint for that kind of value.

Best practice

Type hinting is optional in Python, but it is widely considered good practice. Declaring types is a common pattern in programming languages, including C, C#, C++, and Java. The lessons and project solutions use hints throughout, and the course expects you to use them in your work from here on; quizzes check them.

Type hints also help your future self. Days after writing code, you will forget what you intended, and the hints will remind you.

Literals

A literal is a value you type directly into your code: a number such as 42, or text in quotes such as 'Hello'. It is the value itself. A variable is a name that refers to a value. Look at these lines:

print(42)
print('Hello, world!')
age: int = 33

Names such as age and print, and type hints such as int, are not literals. Only the numbers and the quoted text are.

A literal is fixed: you cannot turn 42 into 43. A variable name can be pointed at a new value, so if you need something that changes, use a variable.

Check your understanding. How many literals does this program contain? Count only the numbers and the quoted text. Names such as price and count, and hints such as float and int, do not count. Give literal_count a type hint and replace None with your answer, then press Run.

price: float = 4.5
count: int = 3
print("Total:", price * count)
Hint 1

Look for numbers, and for text inside quotes. Then check every other word on each line: names and type hints are not literals.

Look at the first example again. Python uses the 42, the line ends, and there is no name left to ask for it. Where did it go? And what does it mean for a variable to "refer to" a value? The next section answers both.

Memory, addresses, and names

Your program's values live in the computer's memory. Picture memory as a wall of numbered lockers. Each locker holds one value, and its number is its address. Typing 12 in your code makes Python put a 12 in an empty locker:

Four numbered lockers, #1001 to #1004. The first holds the value 12 and the other three are empty. A dotted line from the typed 12 to the first locker shows Python storing it there.

These numbers are made up. Real addresses are much longer, and you will see some below.

To get the 12 back, you need its locker number. The front desk keeps a names register, a sheet that lists each name and the locker it uses:

The code a = 12 is shown beside a names register with one entry, a, holding the address #1001. An arrow leads from that entry to locker #1001 in memory, which holds 12.

That entry is a variable. The variable is not the data. It is a name written next to the address of the data. Several names can use the same locker, and assignment adds a line or changes the locker number on one. In the pictures below, an arrow follows the number from the register to the locker.

The code a = 12, b = a, c = a. In the names register, a, b and c each hold the address #1001. Three arrows lead to the same locker, #1001, which holds one 12.

All three names hold the same address, so there is one 12 in memory and three ways to reach it. Notice that b = a and c = a copy the address that a holds. They do not make a new 12, and they do not make b or c follow a. A name always leads to a value, never to another name.

Now give a a new value:

After a = 99, the names register holds b and c with the address #1001 and a with the address #1002. The arrows from b and c still lead to locker #1001, which holds 12. The arrow from a leads to locker #1002, which holds 99.

Writing 99 puts a new value in a new locker. Only the line for a changes, so its arrow now ends somewhere else. b and c still hold #1001, so they still give 12. (a is listed last only so the arrows do not cross.)

This answers the question from earlier. When num_1 later becomes 99, num_2 stays at 12, just as b and c do here.

A locker with no name listed against it cannot be reached again, because nobody has its number. Here Python stores 42, prints it, and then has no way to ask for it:

The code print(42). The names register is empty: no name uses address #1003. Locker #1003 holds 42, but nothing points at it.

Run this to see real addresses. The function id gives the address of the value a name leads to:

The numbers will differ from run to run, but a, b and c match at first, and only a changes. Typing the same number twice, as in a = 12 and then b = 12, may or may not give one address. Python sometimes reuses small numbers to save memory, and other languages do this differently, so do not count on it. Only an assignment from one name to another, like b = a, is certain to share.

Sharing an address cannot be seen with numbers, because a number never changes. It matters for values that can change, such as a list. You will meet lists in a later lesson, but here is a preview:

a = [1, 2]
b = a
b.append(3)
print(a)
[1, 2, 3]

b = a gave b the address of the same list, so a change made through b shows up through a. There was only ever one list.

Check your understanding. Here is a program, with the made-up addresses that id gave for the first two prints. Python stored the 5 at address 4001, and stored the 10 at address 4002. Predict what the last five prints show, then replace the five None values below with those numbers, giving each variable a type hint.

a: int = 5
b: int = a
c: int = a
print(id(a))  # prints 4001
print(id(b))  # prints 4001
a = 10
print(id(a))  # id_a
print(id(b))  # id_b
print(id(c))  # id_c
print(b)      # b_printed
print(c)      # c_printed
Hint 1

Only the line a = 10 moves a, to the new address 4002. b and c still hold the address of the 5.

You will use this idea again in the References section, where you will test whether two names share one value with is.

Quizzes

Note: these quizzes check that you added type hints, and will not pass without them. Future quizzes and projects will assume you know to use them. Python itself does not enforce type hints, so make it a habit.

  1. Assign the value 3.14159 to a variable named pi with the appropriate type hint, and then print out the value of that variable.
  1. Assign the value "Nguyen" to a variable named last_name with an appropriate type hint, and then print out the value of that variable.
  1. Assign the value 16.4 to a variable named length with an appropriate type hint, and then print out the type of the value that variable refers to.
  1. Assign the value "blacksmith" to a variable named occupation with an appropriate type hint, and then print out the type of the value that variable refers to.