Variables and Assignment

Quiz: counts toward finishing the lesson. Check: just for practice.

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.

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.

Check your understanding. Here the hint says int, but the value is a string. Predict what the program prints, then change output to that exact text, in quotes.

age: int = "thirty-three"
print(age)
Hint 1

The program does not stop. A type hint is only a note for you and for tools, so the value is stored and printed as it is.

Best practice and what we will do going forward in the course

Type hinting is optional in Python, but it is considered a best practice to provide type hints in your code whenever possible, especially in larger projects where code documentation and maintainability are important. "Declaring" our types is a far more common design pattern in programming languages, especially in influential, widespread languages like C, C#, C++, and Java.

As such, we use type hints throughout the lessons and project solutions, and we strongly encourage you to use them too. We believe this teaches good, general programming practice rather than niche, language-specific knowledge.

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

Literals

When a value is written in the code without being assigned to a variable, it is called a literal. A literal is a value written directly in the code, not assigned to a name (variable). Here are a few examples:

print(42)  # This line prints the integer literal 42
print('Hello, world!')  # This line prints the string literal 'Hello, world!'

Literals represent fixed values in the code. You can assign them to variables, pass them to functions, and use them like any other value. A literal's value cannot be changed. If you need a value that can change, use a variable.

Check your understanding. Count the literals in this program. A literal is a value written directly in the code. Change literal_count to that number.

total = 5 + 7
print("Total:", total)
Hint 1

There are two numbers on the first line and one piece of text on the second. total is a variable, so it does not count.

Quizzes

Note: these quizzes remind you to add type hints. Future quizzes and projects will assume you know to use them. Python does not enforce type hints, so make it a habit anyway.

  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.