Python Variable Names

Variable Names in Python

When naming your variables, you need to follow a few rules:

  1. A variable name must start with a letter or the underscore (_) character.
  2. It cannot start with a number.
  3. Variable names can only contain letters, numbers, and underscores (A-z, 0-9, and _).
  4. Variable names are case-sensitive (age, Age, and AGE are different variables).

Legal variable names:

python
1
2
3
myvar = "Smith"
_my_var = "Smith"
myVar2 = "Smith"

Illegal variable names:

python
1
2
3
2myvar = "Smith"  # Cannot start with a number
my-var = "Smith"  # Hyphens are not allowed
my var = "Smith"  # Spaces are not allowed

Python Case Sensitive

Variable names in Python are case-sensitive. This means that myVar, MyVar, and myvar are all different variables.

Example:

python
1
2
3
a = 4
A = "Sally"
# Here, a and A are two different variables

Python Multi-Word Variable Names

If your variable name has more than one word, there are a few common styles for writing it:

  • Camel Case: Each word except the first starts with a capital letter.
python
1
myVariableName = "Smith"
  • Pascal Case: Every word starts with a capital letter.
python
1
MyVariableName = "Smith"
  • Snake Case: Each word is separated by an underscore.
python
1
my_variable_name = "Smith"

Assigning Multiple Values to Variables

Python allows you to assign values to multiple variables at once.

Example:

python
1
2
3
4
x, y, z = "Orange", "Grapes", "Cherry"
print(x)
print(y)
print(z)

Assigning One Value to Multiple Variables

You can assign the same value to multiple variables in one line.

Example:

python
1
2
3
4
x = y = z = "Orange"
print(x)
print(y)
print(z)

Unpacking a Collection

If you have a collection (like a list or tuple), you can unpack its values into variables.

Example:

python
1
2
3
4
5
fruits = ["Orange", "Grapes", "Cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)

Frequently Asked Questions