Python Variable Names
Variable Names in Python
When naming your variables, you need to follow a few rules:
- A variable name must start with a letter or the underscore (_) character.
- It cannot start with a number.
- Variable names can only contain letters, numbers, and underscores (A-z, 0-9, and _).
- Variable names are case-sensitive (age, Age, and AGE are different variables).
Legal variable names:
1 2 3
myvar = "Smith" _my_var = "Smith" myVar2 = "Smith"
Illegal variable names:
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:
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.
1
myVariableName = "Smith"
- Pascal Case: Every word starts with a capital letter.
1
MyVariableName = "Smith"
- Snake Case: Each word is separated by an underscore.
1
my_variable_name = "Smith"
Assigning Multiple Values to Variables
Python allows you to assign values to multiple variables at once.
Example:
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:
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:
1 2 3 4 5
fruits = ["Orange", "Grapes", "Cherry"] x, y, z = fruits print(x) print(y) print(z)
Frequently Asked Questions
Variable names in Python are identifiers used to reference data values. They must start with a letter or an underscore and can include letters, numbers, and underscores.
In Python, the four types of variables are local, global, instance, and class variables, each having a different scope and usage.
Variable names are identifiers in Python used to store and reference values. They follow specific rules like starting with a letter or an underscore.
The __name__ variable in Python indicates the name of the current module. If the module is being run directly, __name__ is set to '__main__'.
Still have questions?Contact our support team