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 = 21binds the nameageto the value21. - 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.
name = "Asha"
age = 21
height = 1.62
is_student = True
print(name, age, height, is_student)name = "Asha" creates the variable name and connects it to the text "Asha". Text values are called strings and are written inside quotation marks.age = 21 stores the integer 21. Numbers are written without quotation marks.height = 1.62 stores a decimal number, which Python calls a float.is_student = True stores a Boolean value. True and False are written with a capital first letter and no quotation marks.print() displays the four values separated by spaces, so the output is Asha 21 1.62 True.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.
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)x = 10 connects the name x to the integer 10.type(x) returns the type of the value, so the output is 10 <class 'int'>.x = "ten" makes the same name refer to a string. The old value 10 is no longer connected to x.ten <class 'str'>. The type changed because the value changed.x + "!", which joins the two strings into "ten!", and then assigns the result back to x.ten!.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:
score1is valid but1scoreis 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, andNonecannot be used as names. - Case-sensitive:
Total,total, andTOTALare 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.
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)import keyword loads a standard library module that can tell whether a word is reserved.for loop takes the six names in the list one at a time and stores each one in name. The indented lines below run once for every name.name.isidentifier() is True when the text follows the identifier rules. keyword.iskeyword(name) is True for reserved words, so not reverses it. The result of the combined test is stored in ok.total_price, _count, and Total are valid. 2nd_place starts with a digit, my-var contains a hyphen, and class is a keyword, so those three are False.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
_helpertells 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_scoretoa, and avoid the lettersl,O, andIalone 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.
MAX_USERS = 100
user_count = 25
userCount = 30
print(user_count, userCount)
print("Free slots:", MAX_USERS - user_count)MAX_USERS is written in capital letters, which is the convention for a value that should not change while the program runs.user_count follows the recommended style: lowercase words joined by an underscore. It stores 25.userCount is a completely different name because Python is case-sensitive. It stores 30. Mixed case like this is not the Python style for variables.25 30, which proves that the two names are separate variables.user_count from MAX_USERS and prints Free slots: 75.Assigning Several Variables at Once
Python offers shortcuts that keep code short and readable:
- Multiple assignment:
a, b, c = 1, 2, 3assigns three values to three names in one statement. - Same value to several names:
x = y = 0givesxandythe same value. - Swapping values:
a, b = b, aexchanges two variables without needing a temporary one. - Augmented assignment:
count += 1is a shorter way to writecount = count + 1.
Try It: Multiple Assignment and Swapping
Click Test My Code to see all three shortcuts in action.
a, b, c = 1, 2, 3
x = y = 0
print(a, b, c, x, y)
a, b = b, a
print("After swap:", a, b)a becomes 1, b becomes 2, and c becomes 3. The number of names must equal the number of values.x = y = 0 connects both x and y to the value 0.1 2 3 0 0.b, a, which gives the pair 2, 1, and then assigns it to a, b. The two values are exchanged without a temporary variable.After swap: 2 1.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.
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)input() reads the first line of the Program Input box as text and stores it in first_name.last_name.int() converts it to a whole number before it is stored in age. If the text is not a whole number, Python stops with a ValueError.+ operator joins strings together. A space between the names is added as " ", and the result is stored in full_name.Hello, Asha Verma.age is a number, age + 1 is calculated, and the output is Next year you will be 21.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.
a = [1, 2, 3]
b = a
b.append(4)
print(a)
print(a is b)
c = a.copy()
c.append(5)
print(a, c)a = [1, 2, 3] creates a list object in memory and attaches the name a to it.b = a does not copy the list. It attaches the name b to the same list object.b.append(4) adds 4 to the end of the list. Since there is only one list, the change is visible through both names.[1, 2, 3, 4], even though the change was made through b.a is b checks whether both names refer to the very same object. The output is True.a.copy() creates a new list with the same items, and c is attached to the new list.5 to c changes only the copy. The original list is untouched.[1, 2, 3, 4] [1, 2, 3, 4, 5], which shows that a and c are now independent.Tip: Usedel nameto remove a name when you no longer need it. Using a deleted or never-created name raises aNameError.
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 = 5causes aSyntaxError. Writesecond_placeinstead. - Hyphens or spaces in names:
my-varis read asmyminusvar, andmy varis two separate words. Usemy_var. - Using a keyword as a name:
class = "A"orfor = 3causes aSyntaxError. Choose a different name, such asclass_name. - Shadowing a built-in name: naming a variable
list,str,sum,max, orinputhides the built-in function, and later calls to it will fail. Pick a different name. - Forgetting to convert input:
input()returns text, so"5" + 1raises aTypeError. Convert withint()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_salaryinstead ofmsorx. - Use snake_case for variables and ALL_CAPS for constants.
- Avoid names that differ only by capitalization, such as
dataandData. - Do not reuse built-in names like
list,dict, orinput. - 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_validorhas_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
scoreandScoreare 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.