Academic Block

Python Variables & Naming RulesGet Certified

What Is a Variable in Python?

A variable is a name that refers to a value stored in the computer’s memory. You can think of it as a label attached to a piece of data. Once a value has a name, you can use that name again and again, change the value later, and make your program easier to read.

In Python you create a variable by assigning a value to a name with the assignment operator =. There is no separate declaration step and you do not have to write the type. Python works out the type from the value.

  • Assignment: age = 21 binds the name age to the value 21.
  • No declaration needed: a variable exists from the moment it is first assigned.
  • Dynamic typing: the type belongs to the value, not to the name, so a name can later refer to a different type.
  • Naming rules: a name may use letters, digits, and underscores, and cannot start with a digit.
  • Naming conventions: PEP 8 recommends lowercase names with underscores, such as total_price.

Creating Variables

The name goes on the left of the = sign and the value goes on the right. Python evaluates the right side first and then connects the name to the result. The = sign in Python is an assignment, not a statement of mathematical equality. To compare two values you use ==, which is covered in the operators lesson.

Try It: Variables That Hold Different Kinds of Data

Click Test My Code to run the program. Then change the values, for example your own name and age, and run it again.

What this code does: It creates four variables that store a piece of text, a whole number, a decimal number, and a True/False value. It then prints all four on one line.
name = "Asha"
age = 21
height = 1.62
is_student = True
print(name, age, height, is_student)

Python Variables Are Dynamically Typed

In many languages a variable is tied to one type for its whole life. In Python, the value has a type and the name is only a label, so the same name can refer to an integer now and a string later. The built-in type() function tells you the type of the value that a name currently refers to.

This freedom is convenient, but it also means you must keep track of what each variable holds. Using clear names helps a lot.

Try It: Reassigning a Variable

Click Test My Code and watch the type change when the variable is given a new value.

What this code does: It stores a number in x and prints the value together with its type. It then assigns a string to the same name, prints it again, and finally joins an exclamation mark onto the string.
x = 10
print(x, type(x))
x = "ten"
print(x, type(x))
x = x + "!"
print(x)

Rules for Naming Variables

A variable name is an identifier. Python enforces a few strict rules, and breaking any of them causes a SyntaxError.

  • Allowed characters: letters, digits, and the underscore _. Python 3 also accepts letters from other languages, but plain English letters are the usual choice.
  • Cannot start with a digit: score1 is valid but 1score is not.
  • No spaces or special symbols: characters such as -, @, $, %, and spaces are not allowed. Use an underscore instead of a space.
  • Cannot be a keyword: reserved words such as if, for, class, True, and None cannot be used as names.
  • Case-sensitive: Total, total, and TOTAL are three different variables.
  • No length limit: a name can be as long as you like, but shorter and clear names are easier to read.

Try It: Which Names Are Valid?

Python can check a name for you. The program tests six names with the string method isidentifier() and the keyword module. Click Test My Code, then add your own names to the list and run it again.

What this code does: It loops over a list of six candidate names. For each one it checks that the text follows the identifier rules and is not a reserved keyword, then prints True or False.
import keyword

for name in ["total_price", "2nd_place", "my-var", "_count", "class", "Total"]:
    ok = name.isidentifier() and not keyword.iskeyword(name)
    print(name, "->", ok)

Naming Conventions (PEP 8)

Rules decide what Python accepts. Conventions decide what other programmers expect to see. PEP 8, the official Python style guide, recommends the following:

  • Variables and functions: lowercase words separated by underscores, called snake_case, for example user_count.
  • Constants: all capital letters with underscores, for example MAX_USERS. Python does not stop you from changing a constant, so the capitals are a signal to other programmers.
  • Classes: capitalized words without underscores, called CapWords, for example ShoppingCart.
  • Leading underscore: a name such as _helper tells readers that it is meant for internal use.
  • Single underscore _: often used for a value that you do not plan to use.
  • Meaningful names: prefer average_score to a, and avoid the letters l, O, and I alone because they look like digits.

Try It: Case Sensitivity and Constants

Click Test My Code. Notice that user_count and userCount are two separate variables, which is why the second style is best avoided.

What this code does: It defines a constant in capital letters and two variables whose names differ only in style. It prints both variables to show that they hold different values, and then uses the constant to calculate how many free places remain.
MAX_USERS = 100
user_count = 25
userCount = 30

print(user_count, userCount)
print("Free slots:", MAX_USERS - user_count)

Assigning Several Variables at Once

Python offers shortcuts that keep code short and readable:

  • Multiple assignment: a, b, c = 1, 2, 3 assigns three values to three names in one statement.
  • Same value to several names: x = y = 0 gives x and y the same value.
  • Swapping values: a, b = b, a exchanges two variables without needing a temporary one.
  • Augmented assignment: count += 1 is a shorter way to write count = count + 1.

Try It: Multiple Assignment and Swapping

Click Test My Code to see all three shortcuts in action.

What this code does: It assigns three values in one line, gives two names the same starting value, and prints them. It then swaps two variables in a single statement and prints the swapped values.
a, b, c = 1, 2, 3
x = y = 0
print(a, b, c, x, y)
a, b = b, a
print("After swap:", a, b)

Reading Values into Variables

Variables become really useful when their values come from the user. The input() function always returns text, so you convert the text to a number with int() or float() when you need to calculate with it. Good variable names make it clear what each piece of input means.

Try It: Variables and input()

The Program Input box is already filled with three lines: Asha, Verma, and 20. Click Run Code straight away, then try different values.

What this code does: It reads a first name, a last name, and an age. It joins the two names into a full name, greets the person, and calculates the age they will reach next year.
first_name = input("First name: ")
last_name = input("Last name: ")
age = int(input("Age: "))

full_name = first_name + " " + last_name
print("Hello,", full_name)
print("Next year you will be", age + 1)

Variables Are References, Not Boxes

It is tempting to picture a variable as a box that contains a value. A more accurate picture is a label attached to an object. When you write b = a, Python does not copy the data. It attaches a second label to the same object.

For simple values such as numbers and strings this makes no visible difference, because they cannot be changed in place. For mutable objects such as lists, a change made through one name shows up through the other. To get an independent copy, ask for one explicitly, for example with .copy().

Try It: Two Names for One List

Click Test My Code. Watch how adding an item through b also changes a, while the copy c stays independent.

What this code does: It creates a list and gives it a second name. It adds an item through the second name and shows that the first name sees the change. It then makes a true copy, changes the copy, and shows that the original is unaffected.
a = [1, 2, 3]
b = a
b.append(4)
print(a)
print(a is b)

c = a.copy()
c.append(5)
print(a, c)
Tip: Use del name to remove a name when you no longer need it. Using a deleted or never-created name raises a NameError.

Common Mistakes with Variables

  • NameError: using a variable before it has been assigned, or spelling it differently, gives NameError: name 'total' is not defined. Check spelling and capitalization.
  • Starting with a digit: 2nd_place = 5 causes a SyntaxError. Write second_place instead.
  • Hyphens or spaces in names: my-var is read as my minus var, and my var is two separate words. Use my_var.
  • Using a keyword as a name: class = "A" or for = 3 causes a SyntaxError. Choose a different name, such as class_name.
  • Shadowing a built-in name: naming a variable list, str, sum, max, or input hides the built-in function, and later calls to it will fail. Pick a different name.
  • Forgetting to convert input: input() returns text, so "5" + 1 raises a TypeError. Convert with int() first.
  • Confusing = and ==: a single = assigns a value, and a double == compares two values.

Good Habits for Naming Variables

  • Choose descriptive names such as monthly_salary instead of ms or x.
  • Use snake_case for variables and ALL_CAPS for constants.
  • Avoid names that differ only by capitalization, such as data and Data.
  • Do not reuse built-in names like list, dict, or input.
  • Give each variable one clear purpose instead of reusing it for unrelated values.
  • Use a boolean name that reads like a question, such as is_valid or has_access.

Key Takeaways

  • A variable is a name that refers to a value. You create it by assigning with =, and no declaration is needed.
  • Python is dynamically typed: the value has a type, and the same name can later refer to a value of another type.
  • Names may contain letters, digits, and underscores, cannot start with a digit, and cannot be keywords.
  • Names are case-sensitive, so score and Score are different variables.
  • Follow PEP 8: snake_case for variables, ALL_CAPS for constants, and CapWords for classes.
  • Multiple assignment and swapping, such as a, b = b, a, make code short and clear.
  • A variable is a label for an object, so two names can refer to the same mutable object.

Frequently Asked Questions

What is a variable in Python?

A variable is a name that refers to a value stored in memory. You create one by assigning a value with the = operator, for example age = 21. You can then use the name to read the value or replace it with a new one.

Do I need to declare a variable type in Python?

No. Python is dynamically typed, so you do not declare a type. The type belongs to the value, and Python determines it when the value is created. The same variable name can later be assigned a value of a different type.

What are the rules for naming variables in Python?

A name can contain letters, digits, and underscores. It cannot start with a digit, cannot contain spaces or special symbols such as hyphens, and cannot be a reserved keyword like if or class. Names are also case-sensitive.

Can a Python variable name start with an underscore?

Yes. A name may start with an underscore, such as _count. By convention a leading underscore tells other programmers that the name is meant for internal use. A single underscore alone is often used for a value that will not be needed.

Are Python variable names case-sensitive?

Yes. Name, name, and NAME are three different variables. This is why a spelling mistake in capitalization often causes a NameError. PEP 8 recommends using lowercase names for variables to avoid confusion.

What naming style does Python recommend for variables?

PEP 8 recommends snake_case for variables and functions, which means lowercase words separated by underscores, such as total_price. Constants are written in ALL_CAPS, such as MAX_SIZE, and class names use CapWords, such as ShoppingCart.

How do I assign multiple variables in one line in Python?

Write the names separated by commas on the left and the values on the right, for example a, b, c = 1, 2, 3. To give several names the same value, chain the assignments, for example x = y = 0. The number of names must match the number of values.

How do I swap two variables in Python?

Use tuple assignment: a, b = b, a. Python evaluates the right side first and then assigns the values, so you do not need a temporary variable.

Ready for the next step?Learn about the different kinds of values that variables can hold.
Next: Data Types →