Python – Variable Names


Python Variable Naming Rules & Guidelines (20 Total)🧩 Basic Rules (Syntax Requirements):

  1. Must begin with a letter (a–z, A–Z) or an underscore _.
    my_var, _value
  2. Cannot begin with a digit.
    1value ❌ (Invalid)
  3. Can include letters, digits, and underscores only.
    user1, score_2
  4. Cannot contain spaces.
    user name ❌ → Use user_name
  5. Cannot contain special characters like @, #, $, %, etc.
    name$
  6. Cannot be a Python keyword.
    class, if, while ❌ → Reserved words
  7. Case-sensitive.
    age and Age are two different variables.
  8. No punctuation allowed (e.g., !, ?, .)
    price!
  9. Can be of any length.
    – But very long names are discouraged.
  10. Do not use dashes -
    my-variable ❌ → Use my_variable

🧠 Best Practices (Good Naming Habits):

  1. Use descriptive names.
    total_amount is better than ta.
  2. Use lowercase letters (snake_case) for regular variables.
    user_age
  3. Use all capital letters for constants (by convention).
    MAX_SPEED = 100
  4. Avoid single-character names (unless for short loops).
    – Use index instead of i, unless in a loop.
  5. Do not use names that are similar to built-in functions.
    – Avoid naming a variable list, str, int, etc.
  6. Prefix private/internal-use variables with an underscore _.
    _internal_value
  7. Avoid using double underscores unless you're defining special methods.
    __init__ is used by Python internally.
  8. Use consistent naming style throughout your code.
    – Stick to snake_case, don’t mix with camelCase.
  9. Avoid acronyms or shorthand unless widely known.
    user_id is better than uid.
  10. Comment your variables if their purpose isn't obvious.
    – Helps improve code readability and maintainability.

Do it