Learn

Short lessons with real code you can edit and run on the page.

Variables in Python

Lesson 2 Python 3.14 Runs in your browser Updated
In short

A variable is a name that refers to a value stored in memory. You create one by writing the name, an equals sign and the value, and from then on the name stands in for that value until you assign something else to it.

Key facts

  • Assignment creates the variable. There is no separate declaration step.
  • The value has the type, not the variable. type(x) reports it.
  • Assigning again replaces the value, and the new value can be a different type.
  • Names are case sensitive, can't start with a digit, and can't be one of Python's 35 keywords.

What is a variable in Python?

A variable in Python is a name that refers to a value. It comes into existence the moment you assign a value to the name, so you don't declare it first or say what type it will hold.

Python
name = "Ada"
age = 36
print(name)
print(age)
Output
Ada
36

The equals sign assigns. It means "make this name refer to this value", not "these two things are equal". Comparing values takes two equals signs, which the booleans and comparisons lesson covers.

Once a name exists you can use it wherever the value would go. Here the variable is dropped into a sentence with an f-string, a string with an f before the opening quote and the variable name inside curly braces.

Python
name = "Ada"
print(f"Hello, {name}!")
Output
Hello, Ada!

What types of values can a Python variable hold?

A Python variable can hold a value of any type. The four basic types for single values are str, int, float and bool. The type belongs to the value, not the variable, and type() reports the type of the value a variable refers to right now. Lists and dictionaries, which hold several values, are in the data types lesson.

Four basic Python types for single values
TypeExample valueUsed for
str"Ada"Text of any length, including a single character or nothing at all
int36Whole numbers, positive or negative, with no fixed size limit
float1.75Numbers with a decimal point
boolTrueYes-or-no answers, with only two values, True and False
Python
name = "Ada"
age = 36
height = 1.75
is_student = True
print(type(name))
print(type(age))
print(type(height))
print(type(is_student))
Output
<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>

Quotes make a string, and a decimal point makes a float. "36" in quotes is a string that happens to contain digits, while 36 is a number you can do math with. The data types lesson goes into converting between them.

Can a variable change its value or type?

Yes to both. Assigning again replaces the old value, and the new value can be a different type. Python won't complain, which is convenient and occasionally surprising.

Python
x = 10
print(x)
x = x + 5
print(x)
x = "ten"
print(x)
Output
10
15
ten

x = x + 5 reads the current value of x, adds 5, and stores the result under the same name. Python always works out the right side first, then does the assignment.

How do you assign several variables at once?

Put the names on the left and the values on the right, separated by commas. Python pairs them up in order.

Python
city, country = "Lisbon", "Portugal"
print(city)
print(country)
a = b = 0
print(a, b)
Output
Lisbon
Portugal
0 0

The chained form a = b = 0 makes every name refer to the same value. With a number, that never causes trouble. With a list, which the data types lesson introduces, a change made through one name also shows up through the other. The comma form can also swap two variables in one line, as in a, b = b, a.

What are the rules for variable names in Python?

A name can contain letters, digits and underscores, and it can't start with a digit. Names are case sensitive, so score and Score are two different variables. Python's 35 keywords, words like if, for and class, can't be used as names.

Those are the rules. The convention on top of them, from the PEP 8 style guide, is lowercase words joined by underscores, like first_name or total_price. Pick names that say what the value is. Nobody remembers what x2 meant a week later.

Python
score = 10
Score = 99
print(score)
print(Score)
Output
10
99

score and Score are separate variables, so each keeps its own value.

Python variable names that are and are not allowed
NameAllowed?Why
user_nameYesLetters and an underscore, the PEP 8 style
user2YesA digit is fine after the first character
_cacheYesA leading underscore is allowed and, by convention, marks a name for internal use only
2userNoStarts with a digit
user-nameNoPython reads the hyphen as subtraction
classNoA keyword
UserNameYes, but avoid itValid, but PEP 8 keeps this style for class names, which come later

Common mistakes with variables in Python

These four mistakes with Python variables each stop the program with an error.

  • NameError: name 'total' is not defined. The variable was used before a value was assigned to it, or it's spelled differently from where it was created. Assign first, and check the spelling and capital letters.
  • SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='? The two sides are swapped, like 10 = x. The name goes on the left, the value on the right.
  • TypeError: can only concatenate str (not "int") to str. Text and a number were joined with +, like "Age: " + age when age is 36. Use an f-string, f"Age: {age}", or convert with str(age).
  • SyntaxError: invalid decimal literal. The name starts with a digit, like 2nd_place. Start with a letter or an underscore.

The first one is an error you'll meet often. Run it, then add total = 0 before the print and run it again.

Python
print(total)
Output
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    print(total)
          ^^^^^
NameError: name 'total' is not defined

Exercise

Create three variables before the print calls. language holds the text Python, creator holds the text Guido van Rossum, and year holds the number 1991.

Python

print(language)
print(creator)
print(year)
Output
Show the solution
language = "Python"
creator = "Guido van Rossum"
year = 1991

print(language)
print(creator)
print(year)

Quiz

This quiz has 5 questions. Pick an answer to see why it is right or wrong.

  1. 1What does this program print?

    x = 5
    x = "five"
    print(x)
  2. 2Which of these is a valid variable name?

  3. 3What does this program print?

    a, b = 1, 2
    a, b = b, a
    print(a, b)
  4. 4What does print(type(3.5)) show?

  5. 5What does the line age = 36 do?

Frequently asked questions

What is a variable in Python?
A variable is a name that refers to a value. The line name = "Ada" creates a variable called name that holds the text Ada, and print(name) shows Ada.
What types of values can a variable hold in Python?
Any type. The four basic ones for single values are str for text, int for whole numbers, float for decimals and bool for True or False. The type belongs to the value, and type() reports it for whatever a variable refers to right now.
Do I have to declare a variable type in Python?
No. The value carries its own type, so there is nothing to declare, and the same name can later refer to a value of a different type. Optional type hints, labels that say what type a name should hold, let code editors warn you about mistakes, but Python does not enforce them.
What is the difference between = and == in Python?
A single = assigns a value to a name. A double == compares two values and gives True or False.
Are Python variable names case sensitive?
Yes. name, Name and NAME are three separate variables, and using the wrong case usually raises a NameError.
Can a Python variable name start with a number?
No. A name has to start with a letter or an underscore. Digits are allowed after the first character, so user2 is fine and 2user is not.