KP

Python Variable Names: Rules, Examples, and Naming Styles

By Krishnamohan Yagneswaran
Tech Blog

Python – Variable Names

Understanding Variable Names

In Python, variable names can be very short or more descriptive, depending on the situation. Simple names like x or y are often used for small examples, while meaningful names such as user_age or total_score make programs easier to read and understand.


Rules for Naming Variables in Python

Python follows strict rules when it comes to variable names:

  • A variable name must begin with a letter or an underscore character
  • A variable name cannot begin with a number
  • Only letters, numbers, and underscores are allowed
  • Variable names are case-sensitive, meaning name, Name, and NAME are different
  • Python keywords cannot be used as variable names

Valid Variable Name Examples

The following examples follow Python’s naming rules:
"user = "Sam""
"user_name = "Sam""
"_user_id = 101"
"userAge = 25"
"USERLEVEL = "Beginner""
"user2_score = 90"

These variable names are valid and can be safely used in Python programs.


Invalid Variable Name Examples

The following examples are not allowed in Python:
"3user = "Sam""
"user-name = "Sam""
"user name = "Sam""

These names either start with a number, include unsupported characters, or contain spaces, which causes errors.

Always remember that variable names are case-sensitive, so changing letter case creates a new variable instead of updating an existing one.


Multi-Word Variable Names

Using multiple words in a variable name improves readability, but they must be written without spaces. Python developers commonly follow specific naming styles to achieve this.


Camel Case

In Camel Case, the first word starts with a lowercase letter, and each following word starts with an uppercase letter.

Example:
"userProfileName = "Alex""


Pascal Case

In Pascal Case, every word starts with a capital letter. This style is often used for class names.

Example:
"UserProfileName = "Alex""


Snake Case

In Snake Case, words are separated using underscores. This is the most commonly used style for variable names in Python.

Example:
"user_profile_name = "Alex""


Share this post:Share on TwitterShare on LinkedIn