Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 149 ยท Getting Started

Variables and Names

Learn how Python variables work - assignment, naming rules and conventions, multiple assignment, swapping values and dynamic typing - with examples to run.

Programs work with values: a price, a user's name, a list of scores. To use a value more than once, or to change it as the program runs, you give it a name. In Python, a name that refers to a value is called a variable.

Variables in Python are simpler than in many languages. You don't declare them in advance or say what type they hold. You just pick a name and assign a value. This lesson shows how assignment really works, which names are allowed, which names are good, and a few handy tricks like assigning several variables at once and swapping two values in a single line.

Creating a variable

You create a variable with an assignment statement: a name, a single equals sign, and a value.

Python Assignment

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Read = as "now refers to", not "equals". The statement city = "Nairobi" means: create the string "Nairobi", then make the name city refer to it. (Testing whether two things are equal uses ==, which you'll meet in Comparison and Logical Operators.)

The underscores in 4_400_000 are just for readability; Python ignores them in numbers.

Python works out the right-hand side first, then binds the name. That's why a variable can appear on both sides:

Python Updating a variable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

This "take the old value, compute a new one" pattern is so common that Python has shortcuts like balance -= 30. You'll learn them in Assignment Operators.

Using a name before assigning it

A variable doesn't exist until its first assignment runs. Using it earlier raises a NameError:

Python
print(total)   # NameError: name 'total' is not defined
total = 10

The same error appears when you misspell a name (totl), so when you see NameError, check spelling and order first.

Names are labels, not boxes

You'll often hear that a variable is "a box that holds a value". For Python, a better picture is a label tied to a value. The value (Python calls it an object) lives on its own; a name just points at it. Two names can point at the same object:

Python Two names, one object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

is checks whether two names refer to the same object. Because lists can be changed in place, the change made through shopping shows up through groceries. Numbers and strings can't be changed in place, so with them you'll rarely notice this sharing. You'll see much more about it in Data Types and Lists.

Naming rules

Python enforces a few hard rules for names (also called identifiers):

  • A name may contain letters, digits and underscores (_).
  • It can't start with a digit: player2 is fine, 2player is not.
  • No spaces or punctuation: first name and first-name are invalid. (first-name would mean "first minus name".)
  • Names are case-sensitive: total, Total and TOTAL are three different variables.
  • It can't be a keyword, one of the words that are part of Python's grammar, such as if, for, class, True or None.

Letters from other alphabets are allowed (grรถรŸe = 3 is valid), but most teams stick to plain English ASCII names so everyone can type them.

Python can list its own keywords:

Python Python's reserved words

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Soft keywords such as match, case and type only act as keywords in specific places, so you can still use them as variable names. It's clearer to avoid them anyway.

Don't reuse built-in names

Some names aren't keywords but are already taken by built-in functions: print, input, list, str, sum, max, id, type... Python lets you assign to them, which quietly hides the original:

Python Shadowing a built-in

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The fix is to choose a different name, such as total. If you ever get "object is not callable" on a familiar function, check whether you reused its name.

Naming conventions

Beyond the rules, PEP 8 (Python's style guide) sets conventions that nearly all Python code follows:

Kind of name Style Example
Variables and functions snake_case: lowercase words joined by underscores max_speed, user_count
Constants UPPER_SNAKE_CASE MAX_RETRIES, TAX_RATE
Classes CapWords (also called PascalCase) ShoppingCart
"Internal" names a leading underscore _cache

Python has no true constants: TAX_RATE = 0.2 can still be reassigned. The capital letters are a promise to other programmers that it won't be.

Good names make comments unnecessary. Compare:

Python
# Unclear
d = 7
x = d * 24

# Clear
days = 7
hours = days * 24

Some tips for naming:

  • Say what the value means, not what type it is: prices beats list1.
  • Booleans read well as yes/no questions: is_valid, has_discount.
  • Short names like i or x are fine for tiny loops and math, not for values that live long.
  • A single underscore _ conventionally means "a value I don't care about".

Assigning several variables at once

Python can assign several names in one statement by putting them on the left, separated by commas. The values on the right are matched up in order:

Python Multiple assignment

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last line fails with a ValueError because there are three values but only two names. This feature is called unpacking, and it works with any sequence, not just values separated by commas. Unpacking and Star Expressions covers it fully.

Careful with a = b = []. Chained assignment gives all names the same object. That's harmless for numbers, but todo = done = [] creates one list with two labels, so adding to todo also "adds" to done. Write todo, done = [], [] to get two separate lists.

Swapping two values

In many languages, swapping two variables needs a temporary third variable. In Python it's one line:

Python Swapping

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python evaluates the whole right-hand side first (making the pair ("tea", "coffee")), then unpacks it into the names on the left, so neither value is lost.

Dynamic typing

Python is dynamically typed: a name has no fixed type. The value has a type, and the same name can refer to values of different types over time:

Python Names can change type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

type() tells you the type of the value a name currently refers to. This flexibility is convenient, but changing what kind of value a name holds usually makes code harder to follow. Keep each variable to one kind of value. In larger projects, you can document the intended type with a type hint, such as answer: int = 42. Python doesn't enforce hints when running, but editors and tools check them. You'll learn more in Type Hints.

Deleting a name

The del statement removes a name. The value itself is cleaned up automatically once no names refer to it:

Python
temp = "scratch value"
del temp
print(temp)   # NameError: name 'temp' is not defined

You'll rarely need del for plain variables. It's more useful for removing items from lists and dictionaries.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which of these is a valid Python variable name?

    Names can't start with a digit, can't contain hyphens, and can't be keywords like class. second_place follows all the rules.
  2. 2. After a = 5 and b = 7, which line swaps their values?

    The right side is evaluated first, then unpacked into the names on the left. The first option loses the original value of a.
  3. 3. What do you get from x, y = 1, 2, 3?

    Plain unpacking needs exactly as many names as values, so Python raises ValueError (too many values to unpack).
  4. 4. After a = [1], b = a, b.append(2), what does print(a) show?

    b = a doesn't copy the list. Both names refer to the same list, so the change is visible through a.
  5. 5. Which name follows PEP 8 style for a constant?

    Constants use UPPER_SNAKE_CASE. Ordinary variables use snake_case, and camelCase isn't used for Python variables.

Summary

  • name = value makes a name refer to a value. The right side is evaluated first.
  • A variable exists only after it's assigned; otherwise you get a NameError.
  • Names are labels on objects. b = a makes both names point to the same object.
  • Names use letters, digits and underscores, can't start with a digit, are case-sensitive, and can't be keywords.
  • Follow PEP 8: snake_case variables, UPPER_SNAKE_CASE constants, and never reuse built-in names like list or sum.
  • a, b = 1, 2 assigns several names; a, b = b, a swaps them.
  • Python is dynamically typed: values have types, names don't.

Next: Input and Output, where you'll control exactly how print() shows things and read data from the user.